Call the data dictionary data through ajax to dynamically add to the drop-down list of the web page

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right 

Article directory

Table of contents

foreword

1. Data dictionary creation

2. Preparation

1. Data dictionary

2. Backend code

2.1 Database entity class

2.2 Database control layer

2.3 Business logic layer

2.4 Servlet layer

2. Front-end code

3. Final display

Summarize


foreword

In order for users to encounter the problem of inconsistency between the drop-down list data and the database when filling in the information, in order to solve unnecessary troubles, ajax is used to obtain the database data of the background query and display it on the page

1. Data dictionary creation

The main purpose of the data dictionary is to query the table and generally do not add, delete, or modify; the data dictionary is generally a project that does not change frequently or the data is often used by other data tables, extracted and made into a data collection and put into a table

2. Preparation

1. Data dictionary

2. Backend code

Table Structure:

2.1 Database entity class

package com.shuju.bean;

import java.io.Serializable;

public class Shuju implements Serializable {
    private int id;
    private int parentId;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getParentId() {
        return parentId;
    }

    public void setParentId(int parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.2 Database control layer

The first step is to download the tool class BaseDao, which is displayed at the top of the article.

second step

Create a data dictionary implementation class to implement the Dao layer interface

Inherit the BaseDao tool class to implement the data dictionary interface

package com.shuju.dao.impl;

import com.shuju.bean.Shuju;
import com.shuju.dao.BaseDao;
import com.shuju.dao.ShujuDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ShujuDaoImpl extends BaseDao implements ShujuDao {
    @Override
    public List<Shuju> getShujuList(int parentId) {
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        List<Shuju> list=new ArrayList<>();
        try{
            conn=this.getConnection();//父类的BaseDao类连接数据库方法
            String sql="SELECT id,parent_id,name FROM `shuju` where parent_id=? ";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,parentId);
            rs=pstmt.executeQuery();
            while (rs.next()){
                Shuju shuju=new Shuju();
                shuju.setId(rs.getInt(1));
                shuju.setParentId(rs.getInt(2));
                shuju.setName(rs.getString(3));
                list.add(shuju);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.closeAll(conn,pstmt,rs);//父类的BaseDao类关闭方法
        }
        return list;
    }
}

2.3 Business logic layer

Create a data dictionary business logic layer implementation class to implement the service layer interface

Call Dao layer method

package com.shuju.service.impl;

import com.shuju.bean.Shuju;
import com.shuju.dao.ShujuDao;
import com.shuju.dao.impl.ShujuDaoImpl;
import com.shuju.service.ShujuService;

import java.util.List;

public class ShujuServiceImpl implements ShujuService {
    private ShujuDao shujuDao=new ShujuDaoImpl();
    @Override
    public List<Shuju> getShujuList(int parentId) {
        return shujuDao.getShujuList(parentId);
    }
}

2.4 Servlet layer

Get front-end user input

Call the business logic layer code

jump page

package com.shuju.servlet;

import com.alibaba.fastjson.JSON;
import com.shuju.bean.Shuju;
import com.shuju.service.ShujuService;
import com.shuju.service.impl.ShujuServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/shujuServlet")
public class ShujuServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);//doGet里面调用doPost
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//请求的中文乱码问题
        resp.setCharacterEncoding("UTF-8");//响应的中文乱码问题
        String opr = req.getParameter("opr");//选择调用的servlet中的那个方法
        ShujuService shujuService=new ShujuServiceImpl();//创建业务逻辑层对象
        if ("list".equals(opr)){
            List<Shuju> sexlist=shujuService.getShujuList(1001);
            List<Shuju> minzulist=shujuService.getShujuList(1005);
            Map<String,Object> data = new HashMap<>();
            data.put("sexlist",sexlist);
            data.put("minzulist",minzulist);
            Map<String,Object> result = new HashMap<>();
            result.put("code",0);
            result.put("data",data);
            result.put("msg","成功调用");
            String resultStr = JSON.toJSONString(result);//阿里巴巴的转json的工具
            PrintWriter pw = resp.getWriter();
            pw.write(resultStr);//设置要返回的内容
            pw.close();
        }
    }
}

2. Front-end code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form>
    性别:<select id="Sexselect">
    </select>
</form>
</body>
<script src="js/jquery.js"></script><!--引用jquery-->
<script>
    $.ajax({
        url:"shujuServlet?opr=list",
        type:"post",
        data:{
        },
        dataType:"json",
        success:function (data){
            var Sexselect=document.getElementById("Sexselect");
            Sexselect.innerHTML="<option value='0'>请选择</option>";<!--给初始值-->
            for (var i=0;i<data.data.sexlist.length;i++){
                var shujulist=data.data.sexlist[i];
                var option=document.createElement("option");
                option.setAttribute("value",shujulist.id);<!--后端可获取的值-->
                option.setAttribute("name","projectId");<!--后端调用的名字-->
                option.innerHTML=shujulist.name;<!--列表里显示的值-->
                Sexselect.appendChild(option);
            }
        }
    })
</script>
</html>

3. Final display

Enter the address of the front-end web page in the url box

Summarize

The above code is for reference, if there is any error, you can submit it at any time

Guess you like

Origin blog.csdn.net/zky__sch/article/details/131307211