Java教程

cookie 实现Java项目登入页面(记住密码)功能

本文主要是介绍cookie 实现Java项目登入页面(记住密码)功能,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.编写jsp页面的checkbox

 2.编写servlet(登入成功的状态下存储cookie)

package stu.adam.control;

import stu.adam.entity.Customer;
import stu.adam.service.CustomerService;
import stu.adam.service.Impl.CustomerServiceImpl;

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(name="customerlogin",urlPatterns = "/CustomerServlet")
public class CustomerServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        CustomerService customerService=new CustomerServiceImpl();
        String account=request.getParameter("username");
        String password=request.getParameter("password");

        //获取 是否《记住密码》 选项
        String remember=request.getParameter("remember");

        Customer customer=new Customer(account,password);
        Customer tempcustomer=customerService.customerLogin(customer);


        if(tempcustomer!=null){
        //登入成功


            if("true".equals(remember)){
                Cookie cookie =new Cookie(account,password);
                //cookie有效期
                //一个月
                cookie.setMaxAge(60*60*24*30);
                //cookie发送到浏览器
                response.addCookie(cookie);

            }
            response.sendRedirect("classinfo?type=show");

        }else {
            //登入失败
            PrintWriter out=response.getWriter();
            out.write("登入失败,账号或者密码错误");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

3.浏览器查看是否存储成功

4.这段代码可以验证cookie是否存在(有需要情况下可以跳过数据库验证)

    /*
         * 如果用记住密码选项,并且cookie存在于服务端的cookies里面那么就不需要验证密码
         * */
        boolean flagCookie = false;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(account)) {
                flagCookie = true;
                break;
            }
        }

 

 

 

这篇关于cookie 实现Java项目登入页面(记住密码)功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!