cookie的使用

import java.io.IOException;
import java.io.PrintWriter;
 
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 javax.validation.constraints.Null;
 
/**
 * Servlet implementation class rLogin
 */
@WebServlet("/rLogin")
public class rLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public rLogin() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应的字符集编码
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter(); //获得输出流
         
        String strID=request.getParameter("uid");
        String strPassword=request.getParameter("upassword");
        String isRemember=request.getParameter("rememberMe");
         
        boolean isExist=false;
        boolean isLogin=false;
        //校验Cookie中有无登录名信息
        Cookie[] cookies=request.getCookies();
        if (cookies==null){
            out.print("没有Cookie");
        }
        else {
            for(int i=0;i<cookies.length;i++){
                if(cookies[i].getName().equals("uid"));
                isExist=true;
                out.println("拥有Cookie");
            }
        }
         
        //检查登录信息是否正确
        if("tom".equals(strID)&&"123".equals(strPassword)){
            isLogin=true;
        }
         
        //若已选择记住我且Cookie中无信息,则写入Cookie信息
        if("yes".equals(isRemember)&&isExist==false&&isLogin==true){
            Cookie user_id=new Cookie("uid", strID);
            Cookie user_password=new Cookie("upassword", strPassword);
            user_id.setMaxAge(60*60*24*30);
            user_password.setMaxAge(60*60*24*30);
            response.addCookie(user_id);
            response.addCookie(user_password);
        }
         
         
        if(isExist&&!"yes".equals(isRemember)&&isLogin==false){
            out.println("登录失败");
        }
        //登录信息正确或Cookie中有数据,都可登录
        else if(isExist||isLogin){
            out.println("成功登录");
        }
        else{
            out.println("登录失败");
        }
    }
 
}
 

 

上一篇:httpservlet 总结


下一篇:创建jsp文件时报错,"javax.servlet.http.HttpServlet" was not found on the Java)