EL&JSTL:EL:部门信息查询、JSTL:部门查询

EL:部门信息查询:

 工具类DBUtil:连接数据库、SqlSession:用来接收一条sql语句,并执行,并把执行结果转为实体类对象,这几个类没写

DBUtil类:工具类:

package com.bjpowernode.util;

import java.sql.*;

/**
 * author : 动力节点
 * 2019/3/14 0014
 */
public class DBUtil {

    private static String className="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/bjpowernode";
    private static String username="root";
    private static String password="123456";
    private static  Connection conn=null;
    private static  PreparedStatement ps=null;
    static{
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn(){

        try {
            conn= DriverManager.getConnection(url, username,password);
            //conn.setAutoCommit(false);//设置事务为手动提交
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    public static PreparedStatement  createStatement(String sql){
        getConn();
        try {
            ps= conn.prepareStatement(sql);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return ps;
    }

    public static void close(ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void close( PreparedStatement ps,Connection conn){
        close(null, ps, conn);
    }

    public static void close(ResultSet rs, PreparedStatement ps,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

RequestUtil类:这个工具类好像没用

package com.bjpowernode.util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Enumeration;


public class RequestUtil {

    /*
     *  功能:将请求协议包参数信息,赋值给对应的实体类对象
     *
     *  要求: 请求参数名称必须与实体类对象属性名【完全一致】
     */
    public static Object init(HttpServletRequest request,Class classFile){
        Object obj = null;
        Enumeration paramNames=null;
        //1.创建一个对应的实体类的对象
        try {
            obj =  classFile.newInstance();
            //2.得到当前请求协议包中所有的【参数名称】
            paramNames =request.getParameterNames();
            //3.读取请求参数并赋值
            while (paramNames.hasMoreElements()){
                String paramName =(String)paramNames.nextElement();//deptNo
                String value = request.getParameter(paramName);
                if(value!=null && !"".equals(value)){

                    Field fieldObj =  classFile.getDeclaredField(paramName);//private Integer deptNo;
                    fieldObj.setAccessible(true);
                    String typeName = fieldObj.getType().getName();
                    if("java.lang.String".equals(typeName)){
                        fieldObj.set(obj, value);
                    }else if("java.lang.Integer".equals(typeName)){
                        fieldObj.set(obj, Integer.valueOf(value));
                    }else if("java.lang.Double".equals(typeName)){
                        fieldObj.set(obj, Double.valueOf(value));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return obj;
    }
}

 sqlSession:工具类

package com.bjpowernode.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SqlSession {

    /*
     *  作用:
     *      1)将接受一条查询语句,并执行
     *      2)将得到执行结果数据行,转换为实体类对象
     *      3)将实体类对象保存到List
     *
     */
    public static List  selectList(String sql,Class classFile){

        PreparedStatement ps = DBUtil.createStatement(sql);
        ResultSet rs = null;
        Field fieldArray[]=null;
        List list = new ArrayList();
        //1.推送查询语句得到一个结果集[ResultSet]
        try {
            rs =ps.executeQuery();

            //2.获得实体类相关属性
            fieldArray = classFile.getDeclaredFields();
            //3.赋值转换
            while(rs.next()){
                Object obj =  classFile.newInstance();
                for(int i=0;i<fieldArray.length;i++){
                    Field fieldObj = fieldArray[i];//private Integer deptNo;
                    String fieldName = fieldObj.getName();//deptNo
                    String value =rs.getString(fieldName);
                    init(obj,value,fieldObj);

                }
                list.add(obj);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DBUtil.close(rs);
        }

        return list;
    }


    public static List  selectList(String sql, Class classFile, HttpServletRequest request){

        PreparedStatement ps=null;
        Connection con = null;
        ResultSet rs = null;
        Field fieldArray[]=null;
        List list = new ArrayList();
        ServletContext application = request.getServletContext();
        Map conPool=null;
        //1.推送查询语句得到一个结果集[ResultSet]
        try {

            conPool = (Map)application.getAttribute("key");
            Iterator it = conPool.keySet().iterator();
            while(it.hasNext()){
                con =(Connection)  it.next();
                boolean flag = (boolean)conPool.get(con);
                if(flag==true){
                    conPool.put(con, false);
                    break;
                }else{
                    con=null;
                }
            }

            if(con==null){
                //等待  Thread.wait();
                //新建一个connection
            }

            ps = con.prepareStatement(sql);

            rs =ps.executeQuery();

            //2.获得实体类相关属性
            fieldArray = classFile.getDeclaredFields();
            //3.赋值转换
            while(rs.next()){
                Object obj =  classFile.newInstance();
                for(int i=0;i<fieldArray.length;i++){
                    Field fieldObj = fieldArray[i];//private Integer deptNo;
                    String fieldName = fieldObj.getName();//deptNo
                    String value =rs.getString(fieldName);
                    init(obj,value,fieldObj);

                }
                list.add(obj);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            conPool.put(con, true);
        }

        return list;
    }

    private static void init(Object obj,String value,Field fieldObj){

        //1.通知JVM,当前程序要使用fieldObj属性
        fieldObj.setAccessible(true);
        //2.赋值
        try {
            if(value==null){
                fieldObj.set(obj, value);
            }else{

                String typeName = fieldObj.getType().getName();
                if("java.lang.Integer".equals(typeName)){
                    fieldObj.set(obj, Integer.valueOf(value));
                }else if("java.lang.Double".equals(typeName)){
                    fieldObj.set(obj, Double.valueOf(value));
                }else if("java.lang.String".equals(typeName)){
                    fieldObj.set(obj, value);
                }
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    /*
     * 1.根据接收的【实体类对象】自动生成一条INSERT
     * 2.负责将INSERT推送到数据库中执行,返回操作行数
     *  INSERT INTO  [表名]  (字段1,字段2)   value(值1,值2)
        -----------  -----  ------------   -------------
     *
     */
    public static int insert(Object obj){
        String tableName=null;
        StringBuffer columnStr = new StringBuffer("(");
        StringBuffer valueStr =  new StringBuffer(" value(");
        StringBuffer sql = new StringBuffer("INSERT INTO  ");
        Field fieldArray[]  = null;
        PreparedStatement ps = null;
        int flag =0;
        //1.根据实体类获得操作的表名
        tableName = getName(obj.getClass());
        //2.获得需要赋值字段序列
        try {
            fieldArray = obj.getClass().getDeclaredFields();
            for(int i=0;i<fieldArray.length;i++){
                Field fieldObj = fieldArray[i];
                fieldObj.setAccessible(true);
                Object value = fieldObj.get(obj);
                String typeName = fieldObj.getType().getName();
                if("java.lang.String".equals(typeName)){
                    if(value!=null &&  !"".equals(value)){
                        if(columnStr.length()==1){
                            columnStr.append(fieldObj.getName());
                            valueStr.append("'");
                            valueStr.append(value);
                            valueStr.append("'");
                        }else{
                            columnStr.append(",");
                            columnStr.append(fieldObj.getName());
                            valueStr.append(",'");
                            valueStr.append(value);
                            valueStr.append("'");
                        }
                    }
                }else if("java.lang.Integer".equals(typeName) || "java.lang.Double".equals(typeName)){
                    if(value!=null && ((Integer)value)!=0){
                        if(columnStr.length()==1){
                            columnStr.append(fieldObj.getName());
                            valueStr.append(value);
                        }else{
                            columnStr.append(",");
                            columnStr.append(fieldObj.getName());
                            valueStr.append(",");
                            valueStr.append(value);

                        }
                    }
                }


            }
            columnStr.append(")");
            valueStr.append(")");

            sql.append(tableName);
            sql.append(columnStr);
            sql.append(valueStr);
            System.out.println("sql: "+sql.toString());

            ps = DBUtil.createStatement(sql.toString());
            flag = ps.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            DBUtil.close(null);
        }

        return flag;
    }

    //根据实体类得到类型名
    private static String getName(Class classFile){

        String classPath =  classFile.getName();//com.bjpowernode.model.Dept
        int index = classPath.lastIndexOf(".");
        String typeName = classPath.substring(index+1);
        return typeName;
    }


    /*
     *  1.根据得到实体类对象内容,自动生成一条更新数据
     *  2.自动执行更新语句
     */
    public static int update(Object obj,String primaryKey){
        String tableName = null;
        StringBuffer setBuffer = new StringBuffer(" set ");
        StringBuffer whereBuffer = new StringBuffer (" where ");
        StringBuffer sql = new StringBuffer("update ");
        Field fieldArray[]=null;
        int flag = 0;
        PreparedStatement ps =null;
        //1.获得操作表名
        tableName = getName(obj.getClass());
        //2.设置需要更新字段信息
        try {
            fieldArray = obj.getClass().getDeclaredFields();
            for(int i=0;i<fieldArray.length;i++){
                Field fieldObj = fieldArray[i];
                fieldObj.setAccessible(true);
                String fieldName = fieldObj.getName();
                String typeName = fieldObj.getType().getName();
                Object value = fieldObj.get(obj);

                if(fieldName.equals(primaryKey)){
                    whereBuffer.append(fieldName);
                    whereBuffer.append(" = ");
                    if("java.lang.String".equals(typeName) || "java.util.Date".equals(typeName)){
                        whereBuffer.append("'");
                        whereBuffer.append(value);
                        whereBuffer.append("'");
                    }else{
                        whereBuffer.append(value);
                    }
                }else{

                    if(setBuffer.length()>5){
                        setBuffer.append(",");
                    }
                    setBuffer.append(fieldName);
                    setBuffer.append(" = ");
                    if("java.lang.String".equals(typeName) || "java.util.Date".equals(typeName)){
                        setBuffer.append("'");
                        setBuffer.append(value);
                        setBuffer.append("'");
                    }else{
                        setBuffer.append(value);
                    }



                }
            }

            sql.append(tableName);
            sql.append(setBuffer);
            sql.append(whereBuffer);
            System.out.println("sql : "+sql);
            ps = DBUtil.createStatement(sql.toString());
            flag = ps.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            DBUtil.close(null);
        }
        return flag;

    }

}

实体类Dept:

package com.bjpowernode.model;

public class Dept {
    private Integer deptNo;
    private String dname;
    private String loc;

    public Dept(Integer deptNo, String dname, String loc) {
        this.deptNo = deptNo;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptNo() {
        return deptNo;
    }

    public void setDeptNo(Integer deptNo) {
        this.deptNo = deptNo;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }
}

dao层:

package com.bjpowernode.dao;

import com.bjpowernode.model.Dept;
import com.bjpowernode.util.SqlSession;

import java.util.List;

public class DeptDao {
    public Dept findById(String deptNo){
        String sql="select * from dept where deptno="+deptNo;
        List deptList= SqlSession.selectList(sql,Dept.class);

        return (Dept) deptList.get(0);
    }
}

控制层DeptFindIdSeervlet:

package com.bjpowernode.controller;

import com.bjpowernode.dao.DeptDao;
import com.bjpowernode.model.Dept;

import java.io.IOException;

public class DeptFindByIdServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String deptNo=null;
        DeptDao dao=new DeptDao();
        Dept dept=null;
        //1.读取来自浏览器发送的请求协议包中的请求参数【部门编号】
        deptNo=request.getParameter("deptno");
        //2.JDBC查询当前部门编号关联的详细信息(结果是Dept对象)
        dept=dao.findById(deptNo);
        //3.将查询到的信息添加到request
        request.setAttribute("key",dept);
        //4.向tomcat申请调用dept.jsp。将数据写入到响应包
        request.getRequestDispatcher("/dept.jsp").forward(request,response);
    }
}

dept.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/7/20
  Time: 12:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%--需要加jstl的标签--%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
   <center>
       <table border="2">
           <tr>
               <td>部门编号</td>
               <td><input type="text" value="${key.deptNo}"></td>
           </tr>
           <tr>
               <td>部门名称</td>
               <td><input type="text" value="${key.dname}"></td>
           </tr>
           <tr>
               <td>部门位置</td>
               <td><input type="text" value="${key.loc}"></td>
           </tr>
       </table>
   </center>
</body>
</html>

JSTL:部门查询:

 

工具类是上方DBUtil类、SqlSession类 

Dept类:

package com.bjpowernode.model;

public class Dept {
    private Integer deptNo;
    private String dname;
    private String loc;

    public Dept(Integer deptNo, String dname, String loc) {
        this.deptNo = deptNo;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptNo() {
        return deptNo;
    }

    public void setDeptNo(Integer deptNo) {
        this.deptNo = deptNo;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }
}

dao层:

package com.bjpowernode.dao;

import com.bjpowernode.model.Dept;
import com.bjpowernode.util.SqlSession;

import java.util.List;

public class DeptDap {
    public List findAll(){
        String sql="select * from dept";
        List deptList= SqlSession.selectList(sql, Dept.class);
        return deptList;
    }
}

controller层:

 DeptFindServlet:

package com.bjpowernode.controller;

import com.bjpowernode.dao.DeptDap;

import java.io.IOException;
import java.util.List;

public class DeptFindServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        List deptList=null;
        DeptDap dao=new DeptDap();

        //1.JDBC查询所有部门的信息
        deptList=dao.findAll();
        //2.部门信息添加到request
        request.setAttribute("key",deptList);
        //3.请求转发,向tomcat申请dept.jsp
        request.getRequestDispatcher("/dept.jsp").forward(request,response);
    }
}

dept.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/7/20
  Time: 12:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%--需要加jstl的标签--%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
   <center>
       <table border="2">
           <tr>
               <td>部门编号</td>
               <td>部门名称</td>
               <td>部门位置</td>
           </tr>

           <c:forEach items="${key}" var="dept">
              <tr>
                  <td>${dept.deptNo}</td>
                  <td>${dept.dname}</td>
                  <td>${dept.loc}</td>
              </tr>
           </c:forEach>
       </table>
   </center>
</body>
</html>

数据库中的表:

 

猜你喜欢

转载自blog.csdn.net/dengfengling999/article/details/125892731