第二十天:Servlet+mysql+html 增删改查 (代码)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/java_wht/article/details/72803559

0.数据库的sql如下:

create table user(
 id int primary key auto_increment,
 name varchar(20),
 salary varchar(9),
 age varchar(2),
 sex char(2),
 tel varchar(11));

1.index.html 用户注册的首页:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>用户注册!</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>	
    	<form action="add" method="post" align="center">
  		<h1> 这是一个用户注册页面!</h1>
    		<table align="center">
    			<tr><td>name:</td><td><input type="text" name="name"/></td></tr>
    			<tr><td>salary</td><td><input type="text" name="salary"/></td></tr>
    			<tr><td>age:</td><td><input type="text" name="age"/></td></tr>
    			<tr><td>sex:</td><td>M:<input type="radio" name="sex" value="M"/>
    			W:<input type="radio" name="sex" value="W"/></td></tr>
    			<tr><td>tel:</td><td><input type="text" name="tel"/></td></tr>
    		</table>
    		<input type="submit" value="提交"/>
    	</form> <br>
  </body>
</html>
2.add的Servlet

package com.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

//页面注册用户的Servlet
@SuppressWarnings("serial")
public class Add extends HttpServlet{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
        //避免出现乱码可以提前设置一下
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset=gbk");
        PrintWriter pw=response.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test01","root","1234");
            String sql="insert into user(name,salary,age,sex,tel) values(?,?,?,?,?)";
            PreparedStatement ps= conn.prepareStatement(sql);
            ps.setString(1, request.getParameter("name"));
            ps.setString(2, request.getParameter("salary"));
            ps.setString(3, request.getParameter("age"));
            ps.setString(4, request.getParameter("sex"));
            ps.setString(5, request.getParameter("tel"));
            pw.println("<h1>"+"用户注册成功!"+"</h>");
            System.out.println(ps.executeUpdate());
            response.sendRedirect("list");
           // pw.println("<h1><a href='list'>"+"查看所有用户列表!"+"</a></h>");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
3.delete的Servlet
package com.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

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

//从查出来的表上,删除已经注册的用户的Servlet
@SuppressWarnings("serial")
public class Delete extends HttpServlet{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
            response.setContentType("text/html;charser=gbk");
            PrintWriter pw=response.getWriter();
            try {
                //查找驱动
                Class.forName( "com.mysql.jdbc.Driver");
                //驱动管理器建立链接
                Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test01","root","1234");
                //创建含有操作数据库方法的statement
                 Statement st=conn.createStatement();
                 String sql="delete from user where id='"+request.getParameter("deleteId")+"'";
                 st.executeUpdate(sql);
                 response.sendRedirect("list");
                 conn.close();pw.close();
                 //pw.println("<h1><a href='list'>list</a></h1>");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}
4.list的Servlet

package com.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

//从数据库查询数据显示到表格的Servlet
@SuppressWarnings("serial")
public class List extends HttpServlet{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset=gbk");
        try {
            //查找驱动
            Class.forName("com.mysql.jdbc.Driver");
            //建立链接
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test01", "root", "1234");
            //获取支持sql的statement
            Statement st=conn.createStatement();
            //根据写的sql语句查询结果到ResultSet集合中去
            String sql="select * from user";
            ResultSet  set=st.executeQuery(sql);
            PrintWriter pw=response.getWriter();
            //定义一个表头
            pw.println("<table border='2px'><tr>"
                    + "<td>id</td>"
                    + "<td>name</td>"
                    + "<td>salary</td>"
                    + "<td>age</td>"
                    + "<td>sex</td>"
                    + "<td>tel</td>"
                    + "<td>delete</td>"
                    + "<td>update</td>"
                    + "</tr>");
            while(set.next()){
                    int id=set.getInt(1);
                    String name=set.getString(2);
                    String salary=set.getString(3);
                    String age=set.getString(4);
                    String sex=set.getString(5);
                    String tel=set.getString(6);
                    pw.println("<tr>"
                            + "<td>"+id+"</td>"
                            + "<td><a href='view?viewId="+id+"'>"+name+"</a></td>"
                            + "<td>"+salary+"</td>"
                            + "<td>"+age+"</td>"
                            + "<td>"+sex+"</td>"
                            + "<td>"+tel+"</td>"
                            +"<td>"+"<a href='delete?deleteId="+id+"'>delete</a>"+"</td>"        
                            +"<td>"+"<a href='modify?updateId="+id+"'>update</a>"+"</td>"        
                            + "<tr>");
            }
                pw.println("</table>");
                pw.println("</h1><a href='login.html'>add</a></h1>");
                pw.close();    conn.close();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
    }
}
5.modify+update的Servlet,通过modify相当去一个第三方

package com.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//修改页面的servlet
@SuppressWarnings("serial")
public class Modify extends HttpServlet{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset=gbk");
        PrintWriter pw=response.getWriter();
            //创建数据库链接
             try {
                Class.forName("com.mysql.jdbc.Driver");
             Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test01","root","1234");
             String sql="select * from user where id=? ";
             PreparedStatement ps=conn.prepareStatement(sql);
             ps.setString(1, request.getParameter("updateId"));
             ResultSet rs=ps.executeQuery();
             pw.println("<html><head>");
             pw.println("<meta http-equiv='content-type' content='text/html;charset=utf-8'></head>");
             
             pw.println("<h1>Update User</h1>");
             
             Integer id=Integer.parseInt(request.getParameter("updateId"));
             pw.println("<form action='update?updateId="+id+"' method='post'>"
                     + "<table>");
             while(rs.next()){
                 String name=rs.getString("name");
                 String salary=rs.getString("salary");
                 String age=rs.getString("age");
                 String sex=rs.getString("sex");
                 String tel=rs.getString("tel");
                 pw.println("<tr>");
                 pw.println("<td>name:</td>");
                 pw.println("<td><input type='text' name='name' value='"+name+"'/></td></tr>");

                 pw.println("<tr>");
                 pw.println("<td>salary:</td>");
                 pw.println("<td><input type='text' name='salary' value='"+salary+"'/></td></tr>");
                 
                 pw.println("<tr>");
                 pw.println("<td>age:</td>");
                 pw.println("<td><input type='text' name='age' value='"+age+"'/></td></tr>");
                 
                 pw.println("<tr>");
                 pw.println("<td>sex:</td><td>");
                 if(sex.equals("M")){
                     pw.println("M:<input checked='checked' type='radio' name='sex' value='M'/>");
                     pw.println("W:<input type='radio' name='sex' value='W'/>");
                 }else{
                     pw.println("M:<input type='radio' name='sex' value='M'/>");
                     pw.println("W:<input checked='checked' type='radio' name='sex' value='W'/>");
                 }
                 pw.println("</td></tr>");
                 
                 pw.println("<tr><td>tel:</td>");
                 pw.println("<td><input type='text' name='tel' value='"+tel+"'/></td></tr>");
                 
                 pw.println("<tr><td><input type='submit' vlaue='submit'/></td></tr>");
                 pw.println("</table></form></html>");
             }
             conn.close();
             conn.close();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }   
}

package com.user.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

//将修改后的数据提交给这个表单的Servlet
@SuppressWarnings("serial")
public class Update extends HttpServlet{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html;charset=gbk");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test01","root","1234");
            String sql="update user set name=?,salary=?,age=?,sex=?,tel=?  where id=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            Integer id=Integer.parseInt(request.getParameter("updateId"));
            String name=request.getParameter("name");
            String salary=request.getParameter("salary");
            String age=request.getParameter("age");
            String sex=request.getParameter("sex");
            String tel=request.getParameter("tel");
            
            ps.setString(1,name);
            ps.setString(2,salary);
            ps.setString(3, age);
            ps.setString(4, sex);
            ps.setString(5, tel);
            ps.setInt(6,id);
            
            ps.executeUpdate();
            
            response.sendRedirect("list");
            conn.close();
            ps.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
6.xml映射文件
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">
   <servlet>
   		<servlet-name>myView</servlet-name>
   		<servlet-class>com.user.servlet.View</servlet-class>
   </servlet>
   <servlet>
   		<servlet-name>myModify</servlet-name>
   		<servlet-class>com.user.servlet.Modify</servlet-class>
   </servlet>
   <servlet>
   		<servlet-name>myUpdate</servlet-name>
   		<servlet-class>com.user.servlet.Update</servlet-class>
   </servlet>
   	<servlet>
   		<servlet-name>myDelete</servlet-name>
   		<servlet-class>com.user.servlet.Delete</servlet-class>
   	</servlet>
 	<servlet>
 		<servlet-name>myList</servlet-name>
 		<servlet-class>com.user.servlet.List</servlet-class>
 	</servlet>
 	<servlet>
 		<servlet-name>myAdd</servlet-name>
 		<servlet-class>com.user.servlet.Add</servlet-class>
 	</servlet>
 	<servlet-mapping>
 		<servlet-name>myAdd</servlet-name>
 		<url-pattern>/add</url-pattern>
 	</servlet-mapping>
 	<servlet-mapping>
 		<servlet-name>myList</servlet-name>
 		<url-pattern>/list</url-pattern>
 	</servlet-mapping>
 	<servlet-mapping>
 		<servlet-name>myDelete</servlet-name>
 		<url-pattern>/delete</url-pattern>
 	</servlet-mapping>
 	<servlet-mapping>
 		<servlet-name>myUpdate</servlet-name>
 		<url-pattern>/update</url-pattern>
 	</servlet-mapping>
 	<servlet-mapping>
 		<servlet-name>myModify</servlet-name>
 		<url-pattern>/modify</url-pattern>
 	</servlet-mapping>
 	<servlet-mapping>
 		<servlet-name>myView</servlet-name>
		<url-pattern>/view</url-pattern>
 	</servlet-mapping>
 </web-app>
展开阅读全文

没有更多推荐了,返回首页