注册登录案列

news2024/11/15 16:21:28

案列需求:

在主测页面中输入用户数据,点击注册按钮完成用户注册

实现步骤

1.创建数据库表,Mysql代码如下:

CREATE TABLE tb_user(
id int primary key auto_increment,
username VARCHAR(32),
password VARCHAR(32),
nickname varchar(32),
age int
);

2.创建web项目

添加有必要的jar,配置文件,工具类,JavaBean(user类)

创建自己的包

3.编写页面

4.编写服务器servlet

目录结构:

资源文件

dao层:

dao层接口:servletdao:

import ll.com.entity.tbuser;

import java.util.List;

public interface servletdao {
    public boolean register(tbuser user);//注册的方法
    public tbuser denglu1(tbuser user);//登录的方法
    public List<tbuser> FindAll();//查询所有是数据
    public boolean AddServlet(tbuser user);//添加的方法
    boolean delete(int id);//根据id删除一个数据
    public boolean update(tbuser user);//根据id修改数据
    public int findTotal(); //查询总条数
    List<tbuser> findPage(int i, int pageSize);
    public tbuser findById(int id);//根据id查询数据
}

dao层实现类servletimpl

package ll.com.dao.impl;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class servletimpl implements servletdao {
    @Override
    public boolean register(tbuser user) {
        String sql="insert into tb_user values(null,?,?,?,?)";
        boolean b = DBUtil.updateTable(sql, user.getUsername(), user.getPassword()
                , user.getNickname(), user.getAge());
        return b;
    }

    @Override
    public tbuser denglu1(tbuser user) {
      String sql="select * from tb_user where username=? and password=?";
      List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class,user.getUsername(),user.getPassword());
      if(tbusers.size()>0){
        return tbusers.get(0);
      }
       return null;
    }

    @Override
    public List<tbuser> FindAll() {
        String sql="select * from tb_user";
        List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class);

        return tbusers;
    }

    @Override
    public boolean AddServlet(tbuser user) {
        String sql="insert into tb_user values(null,?,?,?,?)";
        boolean b = DBUtil.updateTable(sql, user.getUsername(), user.getPassword()
                , user.getNickname(), user.getAge());
        return b;
    }

    @Override
    public boolean delete(int id) {
        String sql="delete from tb_user where id = ?";
        boolean b = DBUtil.updateTable(sql, id);
        return b;
    }

    @Override
    public boolean update(tbuser user) {
        String sql ="update tb_user set password = ?,nickname = ?,age = ? where id = ?";
        boolean b = DBUtil.updateTable(sql,
                user.getPassword(), user.getNickname(),
                user.getAge(), user.getId());
        return b;
    }

    @Override
    public int findTotal() {
        Connection connection = DBUtil.getConnection();
        String sql="select  count(*) from Tb_user";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            int total=0;
            while (resultSet.next()){
                total = resultSet.getInt(1);
            }
            resultSet.close();
            preparedStatement.close();
            connection.close();
            return total;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;

    }

    @Override
    public List<tbuser> findPage(int i, int pageSize) {
        String sql="select * from tb_user limit ?,?";
        List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class, i, pageSize);
        return tbusers;
    }

    @Override
    public tbuser findById(int id) {
        String sql="select * from tb_user where id = ?";
        List<tbuser> userList = DBUtil.queryTable(sql, tbuser.class, id);
        if(userList.size()>0){
            return userList.get(0);
        }
        return null;
    }


}

:实体类tbuser:

package ll.com.entity;

public class tbuser {
    private int id;
    private String username;
    private String password;
    private String nickname;
    private int age;

    public tbuser() {
    }

    public tbuser(int id, String username, String password, String nickname, int age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nikname) {
        this.nickname = nikname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "tbuser{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nikname='" + nickname + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

实体类PageBean:

package ll.com.entity;

import java.util.List;

public class PageBean<T> {
    private int count;
    private int totalPage;
    private List<T> userList;
    private int currentPage;
    private int pageSize;

    public PageBean() {
    }

    public PageBean(int count, int totalPage, List<T> userList, int currentPage, int pageSize) {
        this.count = count;
        this.totalPage = totalPage;
        this.userList = userList;
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getUserList() {
        return userList;
    }

    public void setUserList(List<T> userList) {
        this.userList = userList;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Override
    public String toString() {
        return "PageBean{" +
                "count=" + count +
                ", totalPage=" + totalPage +
                ", userList=" + userList +
                ", currentPage=" + currentPage +
                ", pageSize=" + pageSize +
                '}';
    }
}

过滤器filterServlet:

package ll.com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class filterServlet implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();

        if(uri.contains("zhuce.jsp") || uri.contains("denglu.jsp") || uri.contains("login") || uri.contains("checkCode")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            HttpSession session = request.getSession();
            Object username = session.getAttribute("username");
            if(username != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                session.setAttribute("msg","请先登录");
                request.getRequestDispatcher("/denglu.jsp").forward(request,servletResponse);
            }
        }

    }

    @Override
    public void destroy() {

    }
}

业务层Userservrceimpl:

package ll.com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class filterServlet implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();

        if(uri.contains("zhuce.jsp") || uri.contains("denglu.jsp") || uri.contains("login") || uri.contains("checkCode")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            HttpSession session = request.getSession();
            Object username = session.getAttribute("username");
            if(username != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                session.setAttribute("msg","请先登录");
                request.getRequestDispatcher("/denglu.jsp").forward(request,servletResponse);
            }
        }

    }

    @Override
    public void destroy() {

    }
}

业务层Userservrce:

package ll.com.servlce;

import ll.com.entity.PageBean;
import ll.com.entity.tbuser;

import java.util.List;

public interface Userservice {
    public boolean register(tbuser user);//注册的方法
    public tbuser denglu1(tbuser user);//登录的方法
    public List<tbuser> FindAll();//查询所有是数据
    public boolean AddServlet(tbuser user);//添加的方法
    boolean delete(int id);//根据id删除一个数据
    public boolean update(tbuser user);//根据id修改数据
    //查询总条数
    public tbuser findById(int id);//根据id查询数据

    public PageBean findByPage(String page, String size);
}

工具类DButil:

package ll.com.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

//数据库工具类
public class DBUtil {
    private static DataSource ds = null;

    public static DataSource getDataSource(){
        return  ds;
    }
    //加载jdbc.properties配置文件,得到数据库连接的参数,加载驱动
    static {
        try {
            //从jdbc.properties文件读取我们需要的参数
            //1.创建出Properties对象
            Properties properties = new Properties();
            //2.打开读jdbc.properties文件的输入流(可以是字符流,也可以字节流)
            InputStream reader = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            //3.通过properties对象的load方法加载输入流--把jdbc.properties中内容读到properties中
            properties.load(reader);
            //4.DruidDataSourceFactory获得数据源对象
            ds = DruidDataSourceFactory.createDataSource(properties);
            //加载驱动
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //连接数据库
    public static Connection getConnection(){
        try {
            //改成从数据库连接池获取连接
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //断开连接回收资源
    public static void closeConnection(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //通用的表的 增删改操作
    public static boolean updateTable(String sql ,Object... params){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            int number = pstmt.executeUpdate();
            if(number>0){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeConnection(conn);

        }
        return false;
    }

    //jdbc的封装可以用反射机制来封装,把从数据库中获取的数据封装到一个类的对象里
    public static <T> List<T> queryTable(String sql, Class<T> cls, Object... params) {
        List<T> list = new ArrayList<T>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            if (params != null && params.length>0) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1, params[i]);
                }
            }
            resultSet = pstmt.executeQuery();
            //封装数据:列名获得是关键
            ResultSetMetaData metaData = resultSet.getMetaData();
            int len = metaData.getColumnCount();//得到列的个数
            while(resultSet.next()){
                //获得参数中Class<T> cls对应的实体类的对象
                T objectInstance = cls.newInstance();//实体的无参构造

                for (int i = 0; i < len; i++) {
                    String column_name = metaData.getColumnName(i+1);
                    Object column_value = resultSet.getObject(column_name);
//					System.out.println(column_name+"\t"+column_value);
                    //把属性名和值,与对应的实体类进行关联
                    Field field = cls.getDeclaredField(column_name);
                    field.setAccessible(true);
                    field.set(objectInstance, column_value);
                }
                list.add(objectInstance);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeConnection(conn);
        }
        return list;
    }
//获得链接的方法
    public static Connection getConnecttion(){

        Connection connection = null;
        try {
            connection = ds.getConnection();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

}


表面层AddServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        tbuser user = new tbuser();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setAge(Integer.parseInt(age));
        Userservice servletdao = new Userviceimpl();
        boolean b = servletdao.AddServlet(user);
        resp.sendRedirect(req.getContextPath()+"/FindByPage");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}

表面层checkCodeservlet:

package ll.com.Web;

import cn.dsna.util.images.ValidateCode;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/checkCode")
public class checkCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ValidateCode validateCode = new ValidateCode(200,40,4,6);
        String code = validateCode.getCode();//获取验证码
        HttpSession session = req.getSession();//把验证码储存到session域里面
       session.setAttribute("code",code);
        
        //接受是否记住此次数据
        String remember = req.getParameter("remember");
        //把验证码以流的形式响应给客户
        validateCode.write(resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

表面层DeleteServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/delete")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //2.封装数据
        //3.调用DAO层
        Userservice userDao=new Userviceimpl();
        boolean b = userDao.delete(Integer.parseInt(id));
        //4.跳转资源
      resp.sendRedirect(req.getContextPath()+"/FindByPage");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

表面层findAllServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/delete")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //2.封装数据
        //3.调用DAO层
        Userservice userDao=new Userviceimpl();
        boolean b = userDao.delete(Integer.parseInt(id));
        //4.跳转资源
      resp.sendRedirect(req.getContextPath()+"/FindByPage");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

表面层FindByidServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/findById")
public class FindByIdServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受数据
        String id = req.getParameter("id");
        //2.封装数据
        //3.调用DAO
        Userservice userDao = new Userviceimpl();
        tbuser user = userDao.findById(Integer.parseInt(id));
        //4.资源跳转
        req.setAttribute("user", user);
        req.getRequestDispatcher("/update.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

表面层FindByPageServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.entity.PageBean;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/FindByPage")
public class FindByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受数据
        String Page = req.getParameter("currentPage");//当前页
        String Size = req.getParameter("pageSize");//每页查多少
        if(Page=="" || Page==null){
            Page="1";
        }
        if(Size=="" || Size==null){
            Size="2";
        }
        //2.封装数据
        //3.调用业务层
        Userservice servletdao = new Userviceimpl();
        PageBean PageBean = servletdao.findByPage(Page, Size);
        //4.资源跳转

        req.setAttribute("pageBean",PageBean);
        req.getRequestDispatcher("/listAdd.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

表面层LoginServlet:

package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码
        req.setCharacterEncoding("utf-8");
        //接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //接受验证码
        String code = req.getParameter("checkCode");
        HttpSession session = req.getSession();
        String code1 = (String) session.getAttribute("code");
        //接受是否记住用户名的数据
        String remember = req.getParameter("remember");

        if(code1.equalsIgnoreCase(code)){
            //1.校验成功,
            //2.封装数据
            tbuser user = new tbuser();
            user.setUsername(username);
            user.setPassword(password);
            //调用DAO
            Userservice dao = new Userviceimpl();
            tbuser tbuser = dao.denglu1(user);
            if(tbuser==null){
                //重新登录:请求转发到登录的页面,同时携带提示消息
                req.setAttribute("omg","账号或者密码有误");
                req.getRequestDispatcher("/denglu.jsp").forward(req,resp);
            }else{
                if(remember !=null){
                    //把用户名存储到cookie
                    Cookie cookie = new Cookie("username",tbuser.getUsername());
                    //设置cookie存活时间
                    cookie.setMaxAge(60*60);
                    //设置cookie的作用范围
                    cookie.setPath(req.getContextPath());
                    //把cookie相应给游览器
                    resp.addCookie(cookie);
                }else {
                    Cookie cookie = new Cookie("username",tbuser.getUsername());
                    //设置cookie存活时间
                    cookie.setMaxAge(0);
                    //设置cookie的作用范围
                    cookie.setPath(req.getContextPath());
                    //把cookie相应给游览器
                    resp.addCookie(cookie);
                }
                //登录成:重定向到一个查询所有数据的servlet/web/findAll
                //登录成功后 把用户的信息储存到session中
                session.setAttribute("username",username);
                session.setAttribute("loginUser",tbuser);
                resp.sendRedirect(req.getContextPath()+"/FindByPage");
            }
        }else {
            session.setAttribute("msg","验证码错误");
            req.getRequestDispatcher("/denglu.jsp").forward(req,resp);
        }



    }
}

表面层RegidterServlet:

package ll.com.Web;
import ll.com.entity.tbuser;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //接收数据
       req.setCharacterEncoding("utf-8");
        String username=req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        //封装数据
        tbuser user = new tbuser();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setAge(Integer.parseInt(age));
       //调用工作成
        Userservice userdao = new Userviceimpl();
        boolean b = userdao.register(user);
        if(b){
           resp.sendRedirect(req.getContextPath()+"/denglu.jsp");
        }else{
         req.getRequestDispatcher("/zhuce.jsp").forward(req,resp);
        }
    }
}

表面层UpdateServlet:

package ll.com.Web;

import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;

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("/update")
public class UpdateSrevlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        //2.封装数据
        tbuser user=new tbuser();
        user.setId(Integer.parseInt(id));
        user.setPassword(password);
        user.setNickname(nickname);
        user.setAge(Integer.parseInt(age));
        //3.调用DAO
        Userservice userDao=new Userviceimpl();
        boolean b = userDao.update(user);
        //4.资源跳转
     resp.sendRedirect(req.getContextPath()+"/FindByPage");
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);

    }


}

接下类就是处理我们前端的带代码:

前端Add.jsp:

<%--
  Created by IntelliJ IDEA.
  Date: 2024/9/11
  Time: 11:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <style>
        .one{
            display: inline-block;
            width: 45px;
            height: 23px;
            background-color: gainsboro;
            color: black;
        }
    </style>
</head>
<body>
${sessionScope.username}
<div align="center">
    <h1>添加页面</h1>
    <form id="reg-form" action="${pageContext.request.contextPath}/add" method="post">
        <table>
            <tr>
                <td>账号:</td>
                <td>
                    <input name="username" type="text" id="username" onblur="checkusername">
                    <span id="username_err" class="err_msg" style="color: red; display: none">添加账号不正确</span>
                </td>
            </tr>
            <tr>
                <td>密码:</td>
                <td>
                    <input name="password" type="password" id="psd" onblur="checkpassword">
                    <span id="password_err" class="err_msg" style="color: red; display: none">密码输入有误</span>
                </td>
            </tr>
            <tr>
                <td>网名:</td>
                <td>
                    <input name="nickname" type="text">
                </td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td>
                    <input name="age" type="text" id="age" onblur="checkage">
                    <span id="age_err" class="err_msg" style="color: red; display: none">年龄不符</span>
                </td>
            </tr>
        </table>
        <div>
            <input value="添加" type="submit" id="reg_btn"/>
            <a href="/web/FindByPage" class="one">返回</a>
        </div>
    </form>
    <script>
        function checkusername() {
            let usernameValue = document.getElementById("username").value;
            let reg = /^\w{10}$/;
            if (reg.test(usernameValue)) {
                document.getElementById("username_err").style.display = "none";
                return true;
            } else {
                document.getElementById("username_err").style.display = "block";
                return false;
            }
        }
        function checkpassword() {
            let passwordValue = document.getElementById("psd").value;
            let reg = /^.{6,12}$/;
            if (reg.test(passwordValue)) {
                document.getElementById("password_err").style.display = "none";
                return true;
            } else {
                document.getElementById("password_err").style.display = "block";
                return false;
            }
        }
        function checkage() {
            let value = document.getElementById("age").value;
            let num= parseInt(value);
            if(num>=15 && num<=80){
                document.getElementById("age_err").style.display = "none";
                return true;
            }else {
                document.getElementById("age_err").style.display = "block";
                return false;
            }
        }
        document.getElementById("reg-form").onsubmit=function(){
            //4.2 三个输入框只要有一个非法就阻止表单提交,都合法才能提交表单
            return checkusername() && checkpassword() && checkage();
        }
    </script>
</div>
</body>
</html>

前端denglu.jsp:

<%--
  Created by IntelliJ IDEA.
  Date: 2024/9/10
  Time: 10:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
    .one{
        margin-top: 150px;
    }
    .one1{
        display: inline-block;
        width: 45px;
        height: 23px;
        background-color: gainsboro;

    }
    .one1>a{
        color: black;
        font-size: 14px;
    }
    .one1:hover{
        width: 45px;
        height: 23px;
        background-color: azure;
    }
</style>
</head>
<body>
<%
    String username=null;
    Cookie [] cookies = request.getCookies();
    if(cookies !=null){
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            if(name.equals("username")){
                username=cookie.getValue();
            }
        }
    }
    if(username==null){
        username="";
    }
%>
<div align="center" class="one">
<h1>登录页面</h1>
<h4 style="color: red" >${requestScope.omg}</h4>
    <h4 style="color: red">${sessionScope.msg}</h4>

<form action="${pageContext.request.contextPath}/login" method="post">
    账号:&nbsp;&nbsp;&nbsp;<input type="text" name="username" value="<%=username%>"><br>
    密码:&nbsp;&nbsp;&nbsp;<input type="password" name="password"><br>
    验证码:<input type="text" name="checkCode"><br/>
    <img src="/web/checkCode" id="img" onclick="checkcode()"><br/>
  记住用户名:<input type="checkbox" name="remember"><br/>
    <span>
    <input type="submit" value="登录">
    <span class="one1"  border="black"><a  href="/web/zhuce.jsp" class="four">注册</a></span>
    </span>
</form>
    <script>
        function checkcode() {
           let ing = document.getElementById("img");
            img.src="/web/checkCode?time="+new Date().getTime();
        }
    </script>
</div>
</body>
</html>

前端listAdd.jsp:

<%--
  Created by IntelliJ IDEA.
  Date: 2024/9/10
  Time: 17:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <style>
        a {
            text-decoration: none;
        }
        .active{
            color:red;
            font-weight:bold;
        }
    </style>
</head>
<body>
欢迎:${sessionScope.username}
<table width="1000" align="center" border="1px">
    <tr>
        <td colspan="5" align="right">
            <a href="${pageContext.request.contextPath}/Add.jsp" style="color: aqua" >添加数据</a>
        </td>
    </tr>
    <tr>
        <td>user.id</td>
        <td>账号</td>
        <td>昵称</td>
        <td>年龄</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${requestScope.pageBean.userList}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.nickname}</td>
            <td>${user.age}</td>
            <td>
            <a href="/web/findById?id=${user.id}">修改 |</a>
            <a href="javascript:deleteById(${user.id})">删除</a>
            </td>
        </tr>
    </c:forEach>
    <tr>
        <td colspan="5">
            <%--如果是第一页则没有上一页 --%>
            <c:if test="${requestScope.pageBean.currentPage>1}">
                <a href="/web/FindByPage?currentPage=${requestScope.pageBean.currentPage-1}&
pageSize=${requestScope.pageBean.pageSize}">上一页</a>&nbsp;&nbsp;&nbsp;
            </c:if>

            <c:forEach begin="1" end="${requestScope.pageBean.totalPage}" var="i">
                <%--如果是当前页 添加字体颜色样式 --%>
                <c:if test="${i==requestScope.pageBean.currentPage}">
                    <a class="active" href="/web/FindByPage?currentPage=${i}&pageSize=${requestScope.pageBean.pageSize}">${i}</a>
                </c:if>

                <c:if test="${i!=requestScope.pageBean.currentPage}">
                    <a href="/web/FindByPage?currentPage=${i}&pageSize=${requestScope.pageBean.pageSize}">${i}</a>
                </c:if>

            </c:forEach>&nbsp;&nbsp;&nbsp;
            <%--如果是最后一页则没有下一页 --%>
            <c:if test="${requestScope.pageBean.currentPage!=requestScope.pageBean.totalPage}">
                <a href="/web/FindByPage?currentPage=${requestScope.pageBean.currentPage+1}&
                pageSize=${requestScope.pageBean.pageSize}">下一页</a>&nbsp;&nbsp;&nbsp;
            </c:if>
            总${requestScope.pageBean.totalPage}页
            共${requestScope.pageBean.count}条
            每页查${requestScope.pageBean.pageSize}条
        </td>
    </tr>
</table>
<script>
    function deleteById(id) {
    let b=window.confirm("你确定要删除吗?")
        if(b){
            location.href="http://localhost:8080/web/delete?id="+id;
        }
    }
</script>
</body>
</html>

前端update.jsp:

<%--
  Created by IntelliJ IDEA.
  Date: 2024/9/11
  Time: 15:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <style>
       .one{
           display: inline-block;
           width: 45px;
           height: 23px;
           background-color: gainsboro;
           color: black;
       }
   </style>
</head>
<body>
<div align="center">
<h3>修改名为:${sessionScope.username}的账号</h3>
<form id="reg-form" action="${pageContext.request.contextPath}/update" method="post">
        <input type="hidden" name="id" value="${requestScope.user.id}"/>
        <div>
            账号:<input name="username" type="text" id="username" onblur="checkusername" value="${requestScope.user.username} " readonly/>
        </div>
       <div>
           密码:<input name="password" type="password" id="psd" onblur="checkpassword" value="${requestScope.user.password}"/>
       </div>
        <div>
            网名:<input name="nickname" type="text" value="${requestScope.user.nickname}"/>
        </div>
       <div>
           年龄:<input name="age" type="text" id="age" onblur="checkage" value="${requestScope.user.age}"/>
       </div>

        <div>
            <input value="修改" type="submit" id="reg_btn">
            <a href="/web/FindByPage" class="one">返回</a>
        </div>
</form>
</div>
</body>
</html>

前端zhuce.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 龙蕾
  Date: 2024/9/9
  Time: 14:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <style>
       .one{
           margin-top: 150px;
       }
       a{
           text-decoration: none;
       }

       .two{
           color: cornflowerblue;
       }
       .one1{
           display: inline-block;
           width: 45px;
           height: 23px;
           background-color: gainsboro;

       }
       .one1>a{
           color: black;
           font-size: 14px;
       }
       .one1:hover{
           width: 45px;
           height: 23px;
           background-color: azure;
       }
   </style>
</head>
<body>
<div align="center"  class="one">
<h1 class="two">注册页面</h1>
<form id="reg-form" action="${pageContext.request.contextPath}/register" method="post" class="five">

    <table>
        <tr>
            <td>账号:</td>
            <td>
                <input name="username" type="text" id="username" onblur="checkusername">
                <span id="username_err" class="err_msg" style="color: red; display: none">账号不正确</span>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input name="password" type="password" id="psd" onblur="checkpassword">
                <span id="password_err" class="err_msg" style="color: red; display: none">密码输入有误</span>
            </td>
        </tr>
        <tr>
            <td>网名:</td>
            <td>
                <input name="nickname" type="text">
            </td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td>
                <input name="age" type="text" id="age" onblur="checkage">
                <span id="age_err" class="err_msg" style="color: red; display: none">年龄不符</span>
            </td>
        </tr>
    </table>
    <span >
       <span> <input value="注 册" type="submit" id="reg_btn" class="three"></span>
       <span class="one1"  border="black"><a  href="/web/denglu.jsp" class="four">登录</a></span>
    </span>
</form>
</div>
<script>
    function checkusername() {
        let usernameValue = document.getElementById("username").value;
        let reg = /^\w{10}$/;
        if (reg.test(usernameValue)) {
            document.getElementById("username_err").style.display = "none";
            return true;
        } else {
            document.getElementById("username_err").style.display = "block";
            return false;
        }
    }
    function checkpassword() {
        let passwordValue = document.getElementById("psd").value;
        let reg = /^.{6,12}$/;
        if (reg.test(passwordValue)) {
            document.getElementById("password_err").style.display = "none";
            return true;
        } else {
            document.getElementById("password_err").style.display = "block";
            return false;
        }
    }
    function checkage() {
        let value = document.getElementById("age").value;
        let num= parseInt(value);
        if(num>=15 && num<=80){
            document.getElementById("age_err").style.display = "none";
            return true;
        }else {
            document.getElementById("age_err").style.display = "block";
            return false;
        }
    }
    document.getElementById("reg-form").onsubmit=function(){
        //4.2 三个输入框只要有一个非法就阻止表单提交,都合法才能提交表单
        return checkusername() && checkpassword() && checkage();
    }
</script>
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2140033.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【题解】【枚举】—— [USACO1.5] 回文质数 Prime Palindromes

【题解】【枚举】—— [USACO1.5] 回文质数 Prime Palindromes [USACO1.5] 回文质数 Prime Palindromes题目描述输入格式输出格式输入输出样例输入 #1输出 #1 提示 思路1.素数筛法1.1.思路解析1.2.参考代码 解法1.打表1.1.思路解析1.2.AC代码 解法2.构造回文数2.1.思路解析2.2.…

Java集合进阶--双列集合

双列集合的特点&#xff1a; 1 双列集合一次需要存一对数据&#xff0c;分别为键和值 2 键不能重复&#xff0c;值能重复 3 键和值是一一对应的&#xff0c;每一个键只能找到自己对应的值 4 键值这个整体 我们称之为 “键值对” 或者 “键值对对象” &#xff0c;在Java中叫做 …

react hooks--useState

概述 useState 可以使函数组件像类组件一样拥有 state&#xff0c;也就说明函数组件可以通过 useState 改变 UI 视图。那么 useState 到底应该如何使用&#xff0c;底层又是怎么运作的呢&#xff0c;首先一起看一下 useState 。 问题&#xff1a;Hook 是什么? 一个 Hook 就是…

【思博伦】史上最详细思博伦测试仪使用精讲(三)!图解超赞超详细!!!

目录 2.2.14 抓包过滤条件配置 2.2.14.1 配置抓Tx或Rx方向的包 2.2.14.2 添加自定义过滤条件 2.2.14.3 按照包类型配置Qualify Events 2.2.14.4 按照包类型配置Start Events ​​​​​​​2.2.14.5 按照包类型配置Stop Events ​​​​​​​2.2.15 端口计数器统计 ​​…

大数据处理技术:HBase的安装与基本操作

目录 1 实验名称 2 实验目的 3 实验内容 4 实验原理 5 实验过程或源代码 5.1 Hbase数据库的安装 5.2 创建表 5.3 添加数据、删除数据、删除表 5.4 使用Java操作HBase 6 实验结果 6.1 Hbase数据库的安装 6.2 创建表 6.3 添加数据、删除数据、删除表 6.4 使用Java操…

25嘉士伯笔试测评希音笔试测评秋招校招SHL笔试题型分享

25嘉士伯笔试测评用的SHL笔试测评题库&#xff0c;分为两部分&#xff1a; 综合能力部分有计算题 图形推理题 连线题 逻辑题 日历题等等&#xff0c;36min24道题&#xff0c;新手很难做完&#xff1b; 岗位匹配度测评分为8道综合能力性格测试题&#xff0c;给三个选项选出最符…

【系统架构师】-论文-2024-2009年系统架构师历年论文题目

2024年5月 大数据Lambda架构的应用与分析 云原生云上DevOps运维应用与分析 模型驱动软件开发方法与应用 论单元测试在软件回归测试中的应用和分析 2023年 论面向对象设计的应用与实现 论多数据源集成的应用与实现 论软件可靠性模型的设计与实现 论边缘计算技术的设计与实现 …

Java:抽象类和接口(1)

一 抽象类 1.什么是抽象类 在 Java SE 中&#xff0c;抽象类是一种用于为其他类提供通用行为的类。它允许你定义一组方法和字段&#xff0c;而具体的实现留给子类来完成。抽象类不能被实例化&#xff0c;必须通过继承它的子类来实现其抽象方法并进行实例化。 public abstrac…

MATLAB系列04:循环结构

MATLAB系列04&#xff1a;循环结构 4. 循环结构4.1 while循环4.2 for循环4.2.1 运算的细节4.2.2 break语句和continue语句4.2.3 嵌套循环 4.3 逻辑数组和向量化4.3.1 逻辑数组的重要性4.3.2 用 if/else 结构和逻辑数组创建等式 4.4 总结 4. 循环结构 循环(loop)是一种 MATLAB …

初识Linux · 进程(4)

目录 前言&#xff1a; 进程的状态 直接谈论进程的状态 僵尸进程和孤儿进程 纯理论部分 运行态&#xff1a; 阻塞态&#xff1a; 挂起态&#xff1a; 进程的优先级以及切换问题 切换&#xff1a; 优先级&#xff1a; 前言&#xff1a; 承接上文&#xff0c;进程1到…

CPU 和 GPU:为什么GPU更适合深度学习?

目录 什么是 CPU &#xff1f; 什么是 GPU &#xff1f; GPU vs CPU 差异性对比分析 GPU 是如何工作的 &#xff1f; GPU 与 CPU 是如何协同工作的 &#xff1f; GPU vs CPU 类型解析 GPU 应用于深度学习 什么是 CPU &#xff1f; CPU&#xff08;中央处理器&#xff09;…

二叉树链式结构遍历(指针、递归)

当二叉树不使用数组实现&#xff0c;而是使用链式结构&#xff0c;用指针将节点相连时&#xff0c; 二叉树便会衍生出很多问题&#xff0c;如前序遍历、中序遍历、后序遍历、层序遍历。 下面我将用递归的方法完成二叉树的遍历。 但在这之前&#xff0c;我们还得构造链式结构…

深入解析 Apache Ranger

一. 概述 1.什么是 Apache Ranger&#xff1f; Apache Ranger 是一个为大数据平台提供集中化安全管理的开源框架&#xff0c;专门用于确保 Hadoop 生态系统中的数据安全。Ranger 通过提供细粒度的访问控制和监控&#xff0c;帮助组织实现对数据的全面安全管理&#xff0c;确保…

第四天旅游线路预览——从换乘中心到观鱼台

第四天&#xff1a;从贾登峪到喀纳斯风景区入口&#xff0c;晚上住宿贾登峪&#xff1b; 换乘中心有4 路车&#xff0c;喀纳斯②号车&#xff0c;去观鱼台&#xff0c;路程时长约20分钟&#xff1b; 将上面的的行程安排进行动态展示&#xff0c;具体步骤见”Google earth stu…

7.Jmeter数据驱动(csv数据文件设置)+Jmeter数据库操作

一、Jmeter数据驱动 因为&#xff1a;工作中&#xff0c;有些公司一个接口就是一个吻用例&#xff0c;另外一些公司一个接口有几十个用例&#xff0c;就需要用到数据驱动。 特别注意&#xff1a;断言&#xff0c;如果有共同字段&#xff0c;那么就用json断言&#xff0c;如果没…

文档管理系统Mayan EDMS的安装

今天台风 “贝碧嘉” 在上海登陆&#xff0c;这名字起的那叫一个绝&#xff0c;听起来像是 卑鄙家&#xff0c; 说的就是这台风 卑鄙到家了 什么是 EDMS&#xff1f; EDMS 代表电子文档管理系统&#xff0c;它是 DMS 的更现代版本。DMS 是文档管理系统。一种用于存储、排序和分…

二叉树的前中后序遍历(非递归迭代实现)

1.二叉树的前序遍历 1.1 思路分析 前序遍历的顺序是根-左子树-右子树&#xff0c;所以首先从根节点开始&#xff0c;顺着访问左子树&#xff1a;1、2、4。此时&#xff0c;还剩下节点1、节点2、节点3的右子树没有访问。后面倒着访问节点1、2、4的右子树就行了。所以非递归的前…

解决跨境电商平台账号无法访问的常见问题

跨境电商的迅猛发展&#xff0c;越来越多的卖家选择在全球各大电商平台如亚马逊、eBay等进行商品销售。然而&#xff0c;在实际运营过程中&#xff0c;卖家经常会遇到账号无法访问、应用打不开等问题&#xff0c;导致业务受阻。本文将针对这些问题进行详细分析&#xff0c;并提…

【医疗影像】THE BEER-LAMBERT LAW

吸光度 A l o g 10 ( I 0 I ) A log_{10}(\frac{I_0} I) Alog10​(II0​​) 如果您了解光谱仪如何工作&#xff0c;您就会知道它使一系列波长的光穿过物质溶液&#xff08;样品cell&#xff09;&#xff0c;同样地&#xff0c;也会穿过溶剂&#xff08;参考cell&#xff09; …

信息安全工程师(5)域名与域名解析

一、域名 1. 定义与功能 域名&#xff08;Domain Name&#xff09;是互联网上用于标识网站或服务器地址的名称&#xff0c;由一串由点分隔的字符组成&#xff0c;如“example.com”。域名的主要功能是提供一种便于记忆和输入的地址形式&#xff0c;以代替难以记忆的IP地址。域名…