jsp+servlet+jdbc增删改查功能实现(一)

环境:

Eclipse Neon.3 Release (4.6.3),

Tomcat 8.5

Jdk1.8

数据库:MySQL

效果图如下

jsp+servlet+jdbc增删改查功能实现(一)_第1张图片jsp+servlet+jdbc增删改查功能实现(一)_第2张图片

一、创建数据库t_user然后创建student表

create table student(
   id INT NOT NULL AUTO_INCREMENT,
   name VARCHAR(50) NOT NULL,
   age  INT(40) NOT NULL,
   gender VARCHAR(30) NOT NULL,
   major VARCHAR(50) NOT NULL,
   PRIMARY KEY ( id )
);

二、创建WEB项目配置好tomcat和jdk后,添加mysql驱动包 mysql-connector-java-5.1.30-bin.jar

三、创建bean包和dbservlet包如下图,bean下创建Page类和StudentInfo类,dbservlet下创建AllServlet类

jsp+servlet+jdbc增删改查功能实现(一)_第3张图片

三、各页面代码:

1.Page页面

package bean;

public class Page {
     private int totalPage;
     private int currentPage;
     private int totalRecord;
     private int currentRecord;
     private int pageSize=8;
     //获得和设置当前页
     public int getCurrentPage(){
    	 return currentPage;
     }
     public void setCurrentPage(int currentRecord,int pageSize){
    	 if(currentRecord%pageSize==0){
    		 currentPage=currentRecord/pageSize;
    	 }
    	 else{
    		 currentPage=currentRecord/pageSize+1;
    	 }
     }
     //获得和设置当前记录
     public int getCurrentRecord(){
    	 return currentRecord;
     }
     public void setCurrentRecord(int currentRecord){
    	 this.currentRecord=currentRecord;
     }
     //获得和设置每页记录数量
     public int getPageSize(){
    	 return pageSize;
     }
     public void setPageSize(int pageSize){
    	 this.pageSize=pageSize;
     }
     //获得和设置总页数
     public int getTotalPage(){
    	 return totalPage;
     }
     public void setTotalPage(int totalRecord,int pageSize){
    	 if(totalRecord%pageSize==0){
    		 totalPage=totalRecord/pageSize;
    	 }
    	 else{
    		 totalPage=totalRecord/pageSize+1;
    	 }
     }
     //获得和设置总记录
     public int getTotalRecord(){
    	 return totalRecord;
     }
     public void setTotalRecord(int totalRecord){
    	 this.totalRecord=totalRecord;
     }

     
}

2.StudentInfo.java代码

package bean;

public class StudentInfo {

		private int id;			   //学号
		private String name;       //姓名
		private int age;           //年龄
		private String gender;     //性别
		private String major;      //专业
		public StudentInfo(){
			
		}
		public StudentInfo(int id,String name,int age,String gender,String major){
			this.id=id;
			this.name=name;
			this.age=age;
			this.gender=gender;
			this.major=major;
		}
		public int getId(){
			return id;
		}
		public void setId(int id){
			this.id=id;
		}
		
		public String getName(){
			return name;
		}
		public void setName(String name){
			this.name=name;
		}
		
		public int getAge(){
			return age;
		}
		public void setAge(int age){
			this.age=age;
		}
		
		public String getGender(){
			return gender;
		}
		public void setGender(String gender){
			this.gender=gender;
		}
		public String getMajor(){
			return major;
		}
		public void setMajor(String major){
			this.major=major;
		}
}

3.AllServlet代码

package dbservlet;


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Page;
import bean.StudentInfo;

public class AllServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	 //doPost方法
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		    request.setCharacterEncoding("UTF-8");
   		    response.setCharacterEncoding("UTF-8");
			String methodName=request.getParameter("methodName");
			int method=Integer.parseInt(methodName);
		try {  
			switch(method)
		       {
		    	case 0:
					insert(request,response);
		        case 1:
                    difpage(request,response);
			        break;    
		    	case 2:
  				    delete(request,response);
  			        break;       
		        case 3:
  				    update(request,response);
  				    break;
		        case 4:
		        	update1(request,response);
			        break;
		        case 5:
		        	dispatch(request,response);
			        break;
		       }
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	}
	//doGet方法
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
       doPost(request,response);
    }
	
	
    //数据库连接方法
	public Connection connect() throws ClassNotFoundException, SQLException{
    	Connection conn=null; 
	    Class.forName("com.mysql.jdbc.Driver");
	    String url = "jdbc:mysql://localhost:3306/t_user?"
                + "user=root&password=19900908&useUnicode=true&characterEncoding=UTF8";
		conn=DriverManager.getConnection(url); 
		return conn;
	}
	//关闭数据库资源
	public void close(Statement stat,Connection conn) throws SQLException{
		if(stat!=null){
	    	   stat.close();
	    }
	    if(conn!=null){
	    	   conn.close();
	    }
	}
	//插入方法
	public void insert(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
    	Connection conn=null;
    	Statement stat=null;
		String id=request.getParameter("id");
        String name=request.getParameter("name");
        String age=request.getParameter("age");
        String gender=request.getParameter("gender");
        String major=request.getParameter("major");
		conn=connect();
		stat=conn.createStatement();
    	stat.execute("insert into student(id,name,age,gender,major) values("+id+",'"+name+"',"+age+",'"+gender+"','"+major+"')"); 
    	close(stat,conn);
    }
    //查询方法
    public ArrayList select(String id,String name) throws ClassNotFoundException, SQLException{
    	Connection conn=null;
    	Statement stat=null;
	    ResultSet rs=null;
	    conn=connect();
		stat=conn.createStatement();
    	ArrayList result=new ArrayList();
    	if(id==""&&name==""){
    	     rs=stat.executeQuery("select * from student"); 
    	}
    	if(id!=""&&name==""){
   	        rs=stat.executeQuery("select * from student where id="+id+""); 
     	}
    	if(id==""&&name!=""){
   	        rs=stat.executeQuery("select * from student where name='"+name+"'"); 
   	    }
    	if(id!=""&&name!=""){
      	    rs=stat.executeQuery("select * from student where id="+id+" and name='"+name+"'"); 
      	}
    	while(rs.next())
        {
        	StudentInfo st=new StudentInfo();
        	st.setId(rs.getInt("id"));
        	st.setName(rs.getString("name"));
        	st.setAge(rs.getInt("age"));
        	st.setGender(rs.getString("gender"));
        	st.setMajor(rs.getString("major")); 
        	result.add(st);	
        }
	    if(rs!=null){
	    	  rs.close();
	       }
	    close(stat,conn);
    	return result;
    }
    //条件查询跳转
    public void dispatch(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException{
    	String id5=request.getParameter("id");
    	String name5=request.getParameter("name");  
     if(select(id5,name5).isEmpty()){
        	request.getRequestDispatcher("selectnothing.jsp").forward(request, response);
        }
       else{
    		request.setAttribute("result", select(id5,name5));
            request.getRequestDispatcher("idnameselect.jsp").forward(request, response);	
        }
    }
    //设置分页相关参数方法
	public Page setpage(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
		String crd=request.getParameter("currentRecord");
		//String id=request.getParameter("id");
      //  String name=request.getParameter("name");
    	ArrayList result=select("","");
    	Page pager=new Page();
    	pager.setTotalRecord(result.size()); 
    	pager.setTotalPage(result.size(),pager.getPageSize());
    	if(crd!=null)
        {
    		int currentRecord=Integer.parseInt(crd);
            pager.setCurrentRecord(currentRecord);
            pager.setCurrentPage(currentRecord,pager.getPageSize());
        }
    	return pager;
	}
	//获得分页显示的子集
	 public void difpage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException{
		// String id=request.getParameter("id");
	 //    String name=request.getParameter("name");
		 ArrayList result=select("","");
		 Page pager=new Page();
		 pager=setpage(request,response);
  	     List subResult=null;
  	     int currentRecord=pager.getCurrentRecord();
         if(currentRecord==0){
         	if(pager.getTotalRecord()<8){
         		subResult=(List) result.subList(0,pager.getTotalRecord());
         	}
         	else{
         		subResult=(List) result.subList(0,pager.getPageSize());
         	}         
         }
         else if(pager.getCurrentRecord()+pager.getPageSize()) result.subList(pager.getCurrentRecord(),pager.getCurrentRecord()+pager.getPageSize());
         }
         else
         {
              subResult=(List) result.subList(pager.getCurrentRecord(),result.size());
         }
         request.setAttribute("pager", pager);
	     request.setAttribute("subResult", subResult);
		 request.getRequestDispatcher("layout.jsp").forward(request, response);
     }
    //信息删除方法
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException{
    	Connection conn=null;
    	Statement stat=null;
    	conn=connect();
 		stat=conn.createStatement();
 		String id2=request.getParameter("id");
		stat.execute("delete from student where id="+id2+"");
		request.getRequestDispatcher("delete.jsp").forward(request, response);
    } 
    //信息修改方法
    public void update1(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException{
    	String id4=request.getParameter("id");
	    request.setAttribute("result", select(id4,""));
        request.getRequestDispatcher("update1.jsp").forward(request, response);
    }   
    public void update(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException{
    	Connection conn=null;
    	Statement stat=null;
        String id3=request.getParameter("id");
        String name3=request.getParameter("name");
        String age3=request.getParameter("age");
        String gender3=request.getParameter("gender");
        String major3=request.getParameter("major");
    	conn=connect();
 		stat=conn.createStatement();
		stat.execute("update student set id="+id3+",name='"+name3+"',age="+age3+",gender='"+gender3+"',major='"+major3+"' where id="+id3+"");
		request.setAttribute("result", select(id3,""));    
	    request.getRequestDispatcher("update.jsp").forward(request, response); 
    } 
   
}

四、jsp页面见下一篇

你可能感兴趣的:(Java,Web)