java登录验证码、2周内自动登录例题、注销

本文详细介绍了如何实现网站注册页面的邮箱激活、验证码功能、登录过程中的验证码校验、2周自动登录选项以及登录后安全操作,包括清除cookie和session管理。涵盖了前端Ajax交互、后端验证与Cookie/Session使用。
摘要由CSDN通过智能技术生成

接上一篇注册页面邮箱激活

一、验证码

在这里插入图片描述

  1. 验证码Servlet页面:CodeController,同样继承BaseServlet ,value=“/code”,Login.jsp生成的图片<img ></img>图片路径就是 src= “/code?methode=createCode”
  2. CodeController页面有createCode方法
  3. 重点就是ValidateCode code = new ValidateCode(width,height,codeCount,lineCount);然后code.getCode()
  4. 再把code放到session里面session = request.getSession();
  5. 最后输出code.write(response.getOutputStream())
  6. 最后在Login.jsp页面实现jQuery、ajax:点击验证码图片自动刷新

Login.jsp页面验证码图片

 <div class="inputBox">
        <input type="text" placeholder="验证码" name="code"> 
        <p>
        <img id="pagecode" src="/qfshop_war_exploded/code?method=createCode" alt="">
        </p>
 </div>

CodeController页面

@WebServlet(name = "CodeController",value = "/code")
public class CodeController extends BaseServlet {
    public void createCode(HttpServletRequest req,HttpServletResponse resp){
        ValidateCode code = new ValidateCode(100,35,4,21);
        String codes = code.getCode();
        HttpSession session = req.getSession();
        session.setAttribute("codes",codes);
        try {
            code.write(resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Ajax

<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
  $(function(){
  	$("#pagecode").click(function(){
  		$("#pagecode").attr("src","/项目路径/code?method=createCode&t="+Math.random())
  	})
  })
</script>

二、2周自动登录

在这里插入图片描述

  1. Login.jsp页面的form表单action=“/user?method=login”
  2. <input type=“checkbox” name=“autologin”>
  3. 重点就是UserController的login方法处理这个autologin

三、登录

  1. Login.jsp页面的form表单action=“/user?method=login”

具体代码Login.jsp登录页面代码

  1. UserController页面的login方法
  2. 重点就是cookie内置对象对象
    状态管理之Cookie和Session
3.1 UserController的login方法
  1. 获取form表单提交过来的username和password
  2. 获取验证码,
  3. 先判断验证码是否输入正确,输入错误提示重新输入并重新跳转当前登录页面
  4. 验证码正确就调用业务逻辑查找user
  5. 再判断用户名和密码是否正确,输入错误提示重新输入并重新跳转当前登录页面
  6. 最后判断是否激活,未激活就提示去看邮箱,并重新跳转到当前登录页面
  7. 都正确,就把当前的user
  8. 获取2周自动登录的复选框是否为空,如果为空,把name=autoLoginUser的cookie的value设置为空,并且cookie的生命周期设置为0,复选框不为空,就是要实现自动登录功能,就把当前的username+“:"+password放在cookie对象里,让AutoFilter去过滤

以下出现的Constants.FORWORD等,都在Constants.java常量类中定义了

public static String login(HttpServletRequest req,HttpServletResponse resp){
	String username = req.getParameter("username");
	String password = req.getParameter("password");
	String inputVcode = req.getParameter("code");
	HttpSession session = req.getSession();
	String code = (String)session.getAttribute("codes");
	if(inputVcode==null&!inputVcode.equalsIgnoreCase(code)){
		req.setAttribute("msg","验证码错误,请重新输入")return Constants.FORWORD+Constants.FLAG+"/index.jsp";
	}
	UserService userService = new UserServiceImpl();
	User user = userService.login(username,password);
	//如果user为空,说明用户名或者密码输入错误
	if(user == null){
		req.setAttribute("msg","账户或密码输入错误,请重新登录");
		return Constants.FORWORD+Constants.FLAG+"/index.jsp";
	}
	//user不为空,再判断是否激活
	if(user.getStatus()==0){
		req.setAttribute("msg", "账号未激活,请查看邮箱激活账号");
        return Constants.FORWARD + Constants.FLAG + "/Login.jsp";
	}
	session.setAttribute("LoginUser",user);
	//实现自动登录,把username和password保存再cookie
	//先判断input输入框(type="checkbox" name="auto")是否为空
	String auto = req.getParameter("auto");
	if(auto!=null){
	//不为空就保存到客户端
			String content = username+Constants.FLAG+password;
            Cookie cookie = new Cookie(Constants.AUTO_NAME,content);
            cookie.setPath("/");
            cookie.setMaxAge(14*24*60*60);//2周内保存
            resp.addCookie(cookie);
	}else {
   //为空就不自动登录,不必把当前的username和password存到客户端cookie
   //以下代码是把已经存在的cookie作一个修改,value修改为空,生命周期修改为0,浏览器关闭就无了
		Cookie ck = new Cookie("autoLoginUser","");
		ck.setPath("/");
		ck.setMaxAge(0);
		resp.addCookie(ck);
        }
}

四、AutoFilter对login.jsp页面过滤

@WebFilter("/Login.jsp")
public class AutoFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String content = null;
            for (Cookie cookie : cookies) {
                //如果获取到cookie的名字对于Constants.AUTO_NAME
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    //就获取这个cookie的value值
                    content = cookie.getValue();
                }
            }
            if (content != null) {
                String[] split = content.split(Constants.FLAG);
                String username = split[0];
                String password = split[1];

                UserService userService = new UserServiceImpl();
                User user=userService.login(username, password);
                if (user != null) {
                    HttpSession session = request.getSession();
                    session.setAttribute("loginUser",user);
                    HttpServletResponse response = (HttpServletResponse)resp;
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }else{
                    chain.doFilter(req, resp);
                }
            }
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

五、注销

  1. 直接再UserController页面定义loginOut方法
  2. 清空session中的用户数据
  3. 清空和覆盖cookie存储的自动登录的autoLoginUser,也就是在Constants定义的AUTO_NAME
  4. 最后跳转到登录页面
public String loginOut(HttpServletRequest req, HttpServletResponse resp){

        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");
        
        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
        
        return Constants.FORWARD+Constants.FLAG+"/Login.jsp";
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

素心如月桠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值