Java-JSP+Cookie+Session改造登录

Posted 名字真的很急用

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java-JSP+Cookie+Session改造登录相关的知识,希望对你有一定的参考价值。

实现功能:

  • 验证码
  • 保存用户名和密码
  • 提示登录错误信息

第一步定义接口,实现登录的方法

package com.mappers;

import com.pojo.Customer;
import org.apache.ibatis.annotations.Param;

public interface CustomerMapper 

    public Customer login(@Param("name") String name, @Param("pass")String password);

第二步在mapper里写SQL语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mappers.CustomerMapper">


    <select id="login" resultType="com.pojo.Customer">
        select * from customer where name=#name and password=#pass

    </select>
</mapper>

第三步实现service方法,实现三层架构模式

public class CustomerService 

    public boolean loginService(String name,String password)
        SqlSession session = Utils.getSession();
        Customer login = session.getMapper(CustomerMapper.class).login(name, password);
        if(login==null)
            return false;
        
        return true;
    

第四步实现servlet

package com.Controller;

import com.Service.CustomerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class loginServlet extends HttpServlet 
    CustomerService customerService = new CustomerService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取请求验证码的参数
        String checkCode = req.getParameter("captcha");
        //获取生成的验证码
        //session的应用场景,将servlet生成的验证码存储到session中。
        String savedCode = (String) req.getSession().getAttribute(
                "captcha");

        //检验验证码是否正确,验证码不区分大小写
        String error=null;
        if(savedCode.equalsIgnoreCase(checkCode))
            if(username!=null&&username!=""&&password!=null&&password!="")

                boolean login =customerService.loginService(username,password);
                if(login)
                    //利用cookie保存用户名和密码
                    String remember = req.getParameter("remember");
                    if(remember!=null)
                        Cookie cookie = new Cookie("name",username);
                        cookie.setPath(req.getContextPath());
                        cookie.setMaxAge(15*24*60*60);
                        resp.addCookie(cookie);

                        Cookie cookie2 = new Cookie("pass",password);
                        cookie2.setPath(req.getContextPath());
                        cookie2.setMaxAge(15*24*60*60);
                        resp.addCookie(cookie2);
                    



                  req.getRequestDispatcher("/success.jsp").forward(req,resp);
                
                else
                   error="用户名或者密码错误";
                   req.setAttribute("error",error);
                    req.getRequestDispatcher("login.jsp").forward(req,resp);
                
            
            else
                error="用户名或者密码为空";
                req.setAttribute("error",error);
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            
        
        error="验证码错误";
        req.setAttribute("error",error);
        req.getRequestDispatcher("login.jsp").forward(req,resp);

    

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

最后前端代码

<%--
  Created by IntelliJ IDEA.
  User: 86133
  Date: 2021/10/5
  Time: 16:37
  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>
<%String  error = (String )request.getAttribute("error");
  if(error==null)
      error="";
  
    String name=null;
    String password=null;
    Cookie[] cookies = request.getCookies();
     for (Cookie c:cookies)
        if(c!=null)
            if(c.getName().equals("name"))
                name=c.getValue();
                if(name==null)
                    name="";
                
            
            if(c.getName().equals("pass"))
                password=c.getValue();
                if(password==null)
                    password="";
                
            
        
     

%>



<div style="color: red"><%=error%></div>
<form action="/login" method="post" >
    用户名: <input name="username" type="text"  value="<%=name%>"/><br/>&nbsp;&nbsp;码:<input name="password" type="password" value="<%=password%>"/><br/>
    验证码:<input type="text" name="captcha">
    <img src="/captcha" width="130px" height="48px" id="captcha" onClick="changeCaptche()"/><br>

    <input type="checkbox" name="remember"/>记住用户名和密码<br>
    <input type="submit" value="提交" /><br>


</form>
<script>
    //用户点击图片实现切换图片
    function changeCaptche()
        console.log("点击图片了")
        var imgElement = document.getElementById("captcha");
//因为当访问路径没有改变的时候,服务器会认为我们发送的是同一个请求,所以服务器会返回一个状态码304,所以服务器会从缓存中读取数据
//如果每次访问的URL有变化了,就不会从缓存中读取数据,因此可以在请求的地址后面加一个动态参数,例如时间日期。
        imgElement.setAttribute("src","/captcha?date="+new Date())

    



</script>
</body>

</html>


提示错误信息

以上是关于Java-JSP+Cookie+Session改造登录的主要内容,如果未能解决你的问题,请参考以下文章

Java-JSP+Cookie+Session改造登录

JAVA-JSP内置对象之session对象设置并获得session生命周期

JAVA-JSP内置对象之session对象获得session的其他信息

JAVA-JSP内置对象之session对象

Re:从零开始的Spring Session

JavaWeb之会话技术