需要使用的 技术 工具:

  1. idea 2022 开发工具
  2. MySql 5.6 数据库工具
  3. Apache Tomcat 8.5.85 web应用部署工具

主要功能有:

  1. 用户登录
  2. 用户注册
  3. 展示列表信息

涉及到的知识:

  1. Servlet
  2. JDBC
  3. 过滤器

先打开数据库 创建一个数据库 然后 创建对应的表结构

CREATE TABLE `user` (  `id` int(11) NOT NULL auto_increment,  `name` varchar(255) NOT NULL,  `pwd` varchar(255) NOT NULL,  `sex` varchar(255) NOT NULL,  `address` varchar(255) NOT NULL,  `info` varchar(255) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO `user` VALUES ('1', '123', '123', '', '北京', '123');INSERT INTO `user` VALUES ('2', '111, '111', '', '北京', '123123');

然后打开 idea 创建以下 几个目录:

com.filter //过滤器 解决中文字符集乱码
com.util //数据库连接工具类
com.entity //实体类
com.dao //数据操作类
com.servlet //servlet类

在filter下新建一个EncodingFilter用来解决中文字符集乱码,需要实现Filter接口,并且重写doFilter函数

package com.filter; import java.io.IOException; import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse; public class EncodingFilter implements Filter{    public EncodingFilter(){        System.out.println("过滤器构造");    }    public void destroy() {        System.out.println("过滤器销毁");    }    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {        request.setCharacterEncoding("utf-8"); //将编码改为utf-8        response.setContentType("text/html;charset=utf-8");        chain.doFilter(request, response);    }     public void init(FilterConfig arg0) throws ServletException {        System.out.println("过滤器初始化");    } }

然后到web.xml下进行对EncodingFilter相应的 xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"         version="4.0">    <!--  设置编码格式  -->    <filter>        <filter-name>EncodingFilter</filter-name>        <filter-class>com.filter.EncodingFilter</filter-class><!--全路径 从根包开始一直到类名-->    </filter>    <filter-mapping>        <filter-name>EncodingFilter</filter-name>        <url-pattern>/*</url-pattern> <!--* 为过滤所有-->    </filter-mapping>    <!--  设置首页为登录页 首页从默认的 index.jsp 换成 login.jsp  -->    <welcome-file-list>        <welcome-file>login.jsp</welcome-file>    </welcome-file-list></web-app>

在util下新建一个DBconn类用来处理对数据库的连接操作(用户名和密码需要对照自己的数据库进行更改)

package com.util;import java.sql.*;public class DBConnection {    //定义连接数据库的属性    private static String JDBC_DRIVER = "com.mysql.jdbc.Driver";    private static String url = "jdbc:mysql://localhost:3306/demo";    // 用户 密码    private static String username = "root";    private static String pwd = "123456";    private static Connection conn = null;    static ResultSet rs = null;    static PreparedStatement ps =null;        public static void init(){        try {            Class.forName(JDBC_DRIVER);            conn = DriverManager.getConnection(url,username,pwd);        } catch (Exception e) {            System.out.println("init [SQL驱动程序初始化失败!]");            e.printStackTrace();        }    }    public static int addUpdDel(String sql){        int i = 0;        try {            PreparedStatement ps =  conn.prepareStatement(sql);            i =  ps.executeUpdate();        } catch (SQLException e) {            System.out.println("数据库增删改异常");            e.printStackTrace();        }        return i;    }    public static ResultSet selectSql(String sql){        try {            ps =  conn.prepareStatement(sql);            rs =  ps.executeQuery(sql);        } catch (SQLException e) {            System.out.println("数据库查询异常");            e.printStackTrace();        }        return rs;    }    public static void closeConn(){        try {            conn.close();        } catch (SQLException e) {            System.out.println("数据库关闭异常");            e.printStackTrace();        }    }}

在entity下新建一个User实体类对应数据库中的每个字段

package com.entity;public class User {    private int id;    private String name;    private String pwd;    private String sex;    private String address;    private String info;    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 getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public String getInfo() {        return info;    }    public void setInfo(String info) {        this.info = info;    }}

在dao下新建一个UserDao接口 以及对应的方法实现类 规范开发 需要使用 接口及实现类

UserDao.java

package com.dao;import com.entity.User;import java.util.List;public interface UserDao {    public boolean login(String name,String pwd);//登录    public boolean register(User user);//注册    public List getUserAll();//返回用户信息集合    public boolean delete(int id) ;//根据id删除用户    public boolean update(int id,String name, String pwd,String sex, String home,String info) ;//更新用户信息}

在写一个 UserDaoImpl.java 实现UserDao接口,及未实现的方法

package com.dao;import com.entity.User;import com.util.DBConnection;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class UserDaoImpl implements UserDao {    DBConnection DBconn = new DBConnection();    // 注册用户    @Override    public boolean register(User user) {        boolean flag = false;        DBconn.init();        int i =DBconn.addUpdDel("insert into user(name,pwd,sex,address,info) " +                "values('"+user.getName()+"','"+user.getPwd()+"','"+user.getSex()+"','"+user.getAddress()+"','"+user.getInfo()+"')");        if(i>0){            flag = true;        }        DBconn.closeConn();        return flag;    }    // 查询 登录用户是否存在    @Override    public boolean login(String name, String pwd) {        boolean flag = false;        try {            DBconn.init();            ResultSet rs = DBconn.selectSql("select * from user where name='"+name+"' and pwd='"+pwd+"'");            while(rs.next()){                if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){                    flag = true;                }            }            DBconn.closeConn();        } catch (SQLException e) {            e.printStackTrace();        }        return flag;    }    // 获取用户    @Override    public List getUserAll() {        List list = new ArrayList();        try {            DBconn.init();            ResultSet rs = DBconn.selectSql("select * from user");            while(rs.next()){                User user = new User();                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPwd(rs.getString("pwd"));                user.setSex(rs.getString("sex"));                user.setAddress(rs.getString("address"));                user.setInfo(rs.getString("info"));                list.add(user);            }            DBconn.closeConn();            return list;        } catch (SQLException e) {            e.printStackTrace();        }        return null;    }    // 更新用户数据    @Override    public boolean update(int id, String name, String pwd, String sex, String home, String info) {        boolean flag = false;        DBconn.init();        String sql ="update user set name ='"+name                +"' , pwd ='"+pwd                +"' , sex ='"+sex                +"' , home ='"+home                +"' , info ='"+info+"' where id = "+id;        int i =DBconn.addUpdDel(sql);        if(i>0){            flag = true;        }        DBconn.closeConn();        return flag;    }    // 删除用户    @Override    public boolean delete(int id) {        boolean flag = false;        DBconn.init();        String sql = "delete  from user wherecolor: rgba(0, 0, 0, 1)">id;        int i =DBconn.addUpdDel(sql);        if(i>0){            flag = true;        }        DBconn.closeConn();        return flag;    }}

在servlet下创建DengluServlet用来实现对用户登录的操作 ,实现Servlet具体内容,然后需要去WEB_INF下的web.xml去配置servlet

package com.servlet;import com.dao.UserDao;import com.dao.UserDaoImpl;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet(name = "signinServlet", value = "/signinServlet")public class Signin extends HttpServlet { // serverlet 需要继承 HttpServerlet  并重写doGet和doPost方法    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method    }    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        String name = request.getParameter("name"); //得到jsp页面传过来的参数        String pwd = request.getParameter("pwd");        UserDao ud = new UserDaoImpl();        if(ud.login(name, pwd)){            request.setAttribute("xiaoxi", "欢迎用户"+name); //向request域中放置信息            request.getRequestDispatcher("/success.jsp").forward(request, response);//转发到成功页面        }else{            response.sendRedirect("index.jsp"); //重定向到首页        }    }}

两点要注意的地方:

一:getParameter与getAttribute两者的区别

request.setAttribute(“xiaoxi”, “欢迎用户”+name);//向request域中放置信息 ( 键值对的形式) 名字为xiaoxi 内容为”欢迎用户”+name

request.getAttribute(“xiaoxi”);//得到request域中放置名字为xiaoxi的信息

request.getParameter(“name”);//得到request域的参数信息(得到jsp页面传过来的参数)

getAttribute表示从request范围取得设置的属性,必须要先setAttribute设置属性,才能通过getAttribute来取得,设置与取得的为Object对象类型 。

getParameter表示接收参数,参数为页面提交的参数,包括:表单提交的参数、URL重写(就是xxx?id=1中的id)传的参数等,因此这个并没有设置参数的方法(没有setParameter),而且接收参数返回的不是Object,而是String类型

二:转发与重定向的区别

(1).重定向的执行过程:Web服务器向浏览器发送一个http响应–》浏览器接受此响应后再发送一个新的http请求到服务器–》服务器根据此请求寻找资源并发送给浏览器。它可以重定向到任意URL,不能共享request范围内的数据。
(2).重定向是在客户端发挥作用,通过新的地址实现页面转向。
(3).重定向是通过浏览器重新请求地址,在地址栏中可以显示转向后的地址。
(4).转发过程:Web服务器调用内部方法在容器内部完成请求和转发动作–》将目标资源发送给浏览器,它只能在同一个Web应用中使用,可以共享request范围内的数据。
(5).转发是在服务器端发挥作用,通过forward()方法将提交信息在多个页面间进行传递。
(6).转发是在服务器内部控制权的转移,客户端浏览器的地址栏不会显示出转向后的地址。

在servlet下创建一个ZhuceServlet用来实现用户注册的操作

package com.servlet;import com.dao.UserDao;import com.dao.UserDaoImpl;import com.entity.User;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;@WebServlet(name = "LogonServlet", value = "/LogonServlet")public class Logon extends HttpServlet{    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        super.doGet(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String name = req.getParameter("name"); //获取jsp页面传过来的参数        String pwd = req.getParameter("pwd");        String sex = req.getParameter("sex");        String address = req.getParameter("address");        String info = req.getParameter("info");        User user = new User(); //实例化一个对象,组装属性        user.setName(name);        user.setPwd(pwd);        user.setSex(sex);        user.setAddress(address);        user.setInfo(info);        UserDao ud = new UserDaoImpl();        if( ud.register(user) ){            req.setAttribute("username", name);  //向req域中放置参数            req.setAttribute("xiaoxi", "注册成功");            req.getRequestDispatcher("/login.jsp").forward(req, resp);  //转发到登录页面        }else{            resp.sendRedirect("login.jsp");//重定向到首页        }    }}

在servlet下创建SearchallServlet用来返回数据库中所有用户信息Searchall.java

package com.servlet;import com.dao.UserDao;import com.dao.UserDaoImpl;import com.entity.User;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.util.List;@WebServlet(name = "SearchallServlet", value = "/SearchallServlet")public class Searchall extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        super.doGet(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        UserDao ud = new UserDaoImpl();        List userAll = ud.getUserAll();        req.setAttribute("userAll", userAll);        req.getRequestDispatcher("/showall.jsp").forward(req, resp);    }}

在servlet下创建DeleteServlet用来删除用户操作DeleteServlet.java

package com.servlet;import com.dao.UserDao;import com.dao.UserDaoImpl;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;@WebServlet(name = "DeleteServlet", value = "/DeleteServlet")public class Delete extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        super.doGet(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String id = req.getParameter("id");        int userId = Integer.parseInt(id);        UserDao ud = new UserDaoImpl();        if(ud.delete(userId)){            req.setAttribute("xiaoxi", "删除成功");            req.getRequestDispatcher("/Searchall").forward(req, resp);        }else{            resp.sendRedirect("index.jsp");        }    }}

在servlet下创建UpdateServlet操作用来更新用户信息UpdateServlet.java

package com.servlet;import com.dao.UserDao;import com.dao.UserDaoImpl;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;@WebServlet(name = "UpdateServlet", value = "/UpdateServlet")public class Update extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        super.doGet(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String id = req.getParameter("id");        int userId = Integer.parseInt(id);        String name = req.getParameter("name");        String pwd = req.getParameter("pwd");        String sex = req.getParameter("sex");        String home = req.getParameter("home");        String info = req.getParameter("info");        System.out.println("------------------------------------"+userId);        UserDao ud = new UserDaoImpl();        if(ud.update(userId, name, pwd, sex, home, info)){            req.setAttribute("xiaoxi", "更新成功");            req.getRequestDispatcher("/Searchall").forward(req, resp);        }else{            resp.sendRedirect("index.jsp");        }    }}

配置servlet

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"         version="4.0">    <!--  设置编码格式  -->    <filter>        <filter-name>EncodingFilter</filter-name>        <filter-class>com.filter.EncodingFilter</filter-class><!--全路径 从根包开始一直到类名-->    </filter>    <filter-mapping>        <filter-name>EncodingFilter</filter-name>        <url-pattern>/*</url-pattern> <!--* 为过滤所有-->    </filter-mapping>    <servlet><!--servlet类路径配置-->        <servlet-name>LogonServlet</servlet-name>        <servlet-class>com.servlet.Logon</servlet-class>    </servlet>    <servlet>        <servlet-name>SigninServlet</servlet-name>        <servlet-class>com.servlet.Signin</servlet-class>    </servlet>    <servlet>        <servlet-name>SearchallServlet</servlet-name>        <servlet-class>com.servlet.Searchall</servlet-class>    </servlet>    <servlet>        <servlet-name>DeleteServlet</servlet-name>        <servlet-class>com.servlet.Delete</servlet-class>    </servlet>    <servlet>        <servlet-name>UpdateServlet</servlet-name>        <servlet-class>com.servlet.Update</servlet-class>    </servlet>    <!--配置Servlet 类-->    <servlet-mapping>        <servlet-name>LogonServlet</servlet-name>        <url-pattern>/LogonServlet</url-pattern>    </servlet-mapping>    <servlet-mapping>        <servlet-name>SigninServlet</servlet-name>        <url-pattern>/SigninServlet</url-pattern>    </servlet-mapping>    <servlet-mapping>        <servlet-name>SearchallServlet</servlet-name>        <url-pattern>/SearchallServlet</url-pattern>    </servlet-mapping>    <servlet-mapping>        <servlet-name>DeleteServlet</servlet-name>        <url-pattern>/DeleteServlet</url-pattern>    </servlet-mapping>    <servlet-mapping>        <servlet-name>UpdateServlet</servlet-name>        <url-pattern>/UpdateServlet</url-pattern>    </servlet-mapping>    <!--  设置首页为登录页  -->    <welcome-file-list>        <welcome-file>login.jsp</welcome-file>    </welcome-file-list></web-app>

新建jsp页面 login

    登录页    用户名:

密码:


zhuce.jsp 用户注册页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html><head>    <title>My JSP 'BB.jsp' starting page</title></head><body ><form action="LogonServlet"method="post" style="padding-top:-700px;">    输入用户名:<input name="name" type="text"><br><br>    输入密码:<input name="pwd" type="password"><br><br>    选择性别:<input type="radio"name="sex"value="男"checked><input type="radio"name="sex"value="女"><br><br>    选择家乡:    <select name="address">        <option value="上海">上海</option>        <option value="北京" selected>北京</option>        <option value="纽约">纽约</option>    </select><br>    填写个人信息:<br>    <textarea name="info" row="5"cols="30"></textarea><br>    <input type="reset"value="重置"><input type="submit"value="注册"></form></body></html>

失败页面 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html>  <head>    <title></title>  </head>  <body>  <p>失败</p>  </body></html>

success.jsp 成功页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>My JSP 'success.jsp' starting page</title></head><body>    ${xiaoxi} <br>    <a href="showall.jsp">查看所有用户</a></body></html>

完成以上工作就可以 运行 Tomcat服务,然后运行啦

本博文参考大佬http://blog.csdn.net/qq_23994787/article/details/73612870

本文来自博客园,作者:萧熙,转载请注明原文链接:https://www.cnblogs.com/xiaoxiblog/p/17180633.html