java简单案例:servlet

    技术2022-07-10  171

    注册删除查找

    前言环境说明代码结构图User类DButile类UserDao类UserService类AddServlet类index.jspadd.jspdelect.jspselect.jsp数据库运行结果

    前言

    暑期实践课第4课

    环境说明

    1、mysql 5.7版本 2、mysql中创建testtt的数据库,在testtt数据库中有一张user的表 3、user的表中有id,username,password 三个字段 4、Tomcat 8.5.32版本

    代码结构图

    User类

    package com.wdd0629.model; public class User { private int id; private String name; private String password; private String age; //按住键盘上的alt + insert键 选择 getter and setter 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } //按住键盘上的alt + insert键 选择 tostring() @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", age='" + age + '\'' + '}'; } }

    DButile类

    package com.wdd0629.util; import java.sql.*; public class DBUtile { public static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); System.out.println("连接数据库"); //创建连接 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testtt?useSSL=false","root","123456"); return connection; } public static void closeAll(ResultSet rs, Statement stmt,Connection conn) throws SQLException { if (rs!=null){ rs.close(); } if (stmt!=null){ stmt.close(); } if (conn!=null){ conn.close(); } } }

    UserDao类

    package com.wdd0629.dao; import com.wdd0629.model.User; import com.wdd0629.util.DBUtile; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserDao { //注册功能 public int add(User user) { Connection connection = null; PreparedStatement pstmt = null; int count = 0; try{ connection = DBUtile.getConnection(); //获得执行sql的Statement对象 pstmt = connection.prepareStatement("insert into user (name,password,age) values (?,?,?)"); pstmt.setString(1,user.getName()); pstmt.setString(2,user.getPassword()); pstmt.setString(3,user.getAge()); //执行sql,获得结果 count = pstmt.executeUpdate(); System.out.println("insert操作:"+count); return count; }catch (Exception e){ e.printStackTrace(); }finally { try { DBUtile.closeAll(null,pstmt,connection); } catch (SQLException e) { e.printStackTrace(); } } return count; } //删除功能 public int delect(User user){ Connection connection =null; PreparedStatement pstmt =null; int count=0; try{ connection =DBUtile.getConnection(); pstmt =connection.prepareStatement("Delete from user where name=?"); pstmt.setString(1,user.getName()); count=pstmt.executeUpdate(); }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (SQLException e){ e.printStackTrace(); }finally { try { DBUtile.closeAll(null, pstmt, connection); } catch (SQLException e) { e.printStackTrace(); } } return count; } //查找功能 public User selectByName(String name){ ResultSet rs =null; Connection connection = null; PreparedStatement pstmt = null; DBUtile util = new DBUtile(); User user = new User(); try{ connection = util.getConnection(); pstmt = connection.prepareStatement("select * from user where name=?"); pstmt.setString(1,name); rs = pstmt.executeQuery(); //处理结果集 while (rs.next()){ user.setId(rs.getInt(1)); user.setName(rs.getString(2)); user.setPassword(rs.getString(3)); user.setAge(rs.getString(4)); } }catch (Exception e){ e.printStackTrace(); }finally { try { util.closeAll(rs, pstmt, connection); } catch (SQLException e) { e.printStackTrace(); } } return user; } }

    UserService类

    package com.wdd0629.service; import com.wdd0629.dao.UserDao; import com.wdd0629.model.User; import java.sql.SQLException; public class UserService { UserDao userDao = new UserDao(); //注册功能 public int add(User user){ System.out.println("service中add方法被调用"); return userDao.add(user); } //查找功能 public User selectByName(String name){ return userDao.selectByName(name); } //删除功能 public int delect(User user){ return userDao.delect(user); } }

    AddServlet类

    package com.wdd0629.servlet; import com.wdd0629.model.User; import com.wdd0629.service.UserService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; public class AddServlet extends HttpServlet { UserService userService = new UserService(); protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("执行了doPost"); String method = req.getParameter("method"); if (method.equals("save")){ insert(req,resp); }else if (method.equals("search")){ search(req,resp); }else if (method.equals("delect")){ delete(req,resp); } } //注册功能 public void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user =new User(); String name =req.getParameter("name"); String password =req.getParameter("password"); String age =req.getParameter("age"); user.setName(name); user.setPassword(password); user.setAge(age); System.out.println(user); int count = userService.add(user); if (count>0){ resp.sendRedirect("/index.jsp"); }else { resp.getWriter().write("failed"); } } //删除功能 public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=GBK"); resp.setContentType("text/html"); User user = new User(); String name =req.getParameter("name"); user.setName(name); int count = userService.delect(user); if(count>0){ resp.getWriter().write("删除成功"); }else { resp.getWriter().write("失败"); } } //查找功能 public void search(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=GBK"); resp.setContentType("text/html"); String name =req.getParameter("name"); User user1 =userService.selectByName(name); if(user1!=null){ resp.getWriter().write("<h1>用户名:"+user1.getName()+"</h1><h1>密码:"+user1.getPassword()+"</h1><h1>年龄:"+user1.getAge()); }else { resp.getWriter().write("失败!"); } } }

    index.jsp

    <%-- Created by IntelliJ IDEA. User: 荍三岁 Date: 2020/6/29 Time: 10:15 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1>注册页面</h1> <form action="/login" method="post"> name:<input name="name" type="text"> password:<input name="password" type="password"> <input type="submit" value="login"> </form> <a href="add.jsp">跳转到注册页面</a> <a href="search.jsp">跳转到查询页面</a> <a href="delect.jsp">跳转到删除页面</a> </body> </html>

    add.jsp

    <%-- Created by IntelliJ IDEA. User: 荍三岁 Date: 2020/6/30 Time: 10:21 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>注册</title> </head> <body> <form action="/add?method=save" method="post"> name:<input name="name" type="text"> password:<input name="password" type="password"> age:<input name="age" type="text"> <input type="submit" value="注册"> </form> </body> </html>

    delect.jsp

    <%-- Created by IntelliJ IDEA. User: 荍三岁 Date: 2020/7/1 Time: 9:29 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>删除</title> </head> <body> <form action="/add?method=delect" method="post"> <input name="name" placeholder="请输入要删除的Name"> <input type="submit" value="删除"> </form> </body> </html>

    select.jsp

    <%-- Created by IntelliJ IDEA. User: 荍三岁 Date: 2020/7/1 Time: 8:57 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>查找</title> </head> <body> <form action="/add?method=search" method="post"> <input name="name" placeholder="请输入需要查找的名字"> <input type="submit" value="查找"> </form> </body> </html>

    数据库

    运行结果

    Processed: 0.014, SQL: 9