Home  >  Article  >  Web Front-end  >  servlet方式通过Cookie记住登录时的用户名和密码_html/css_WEB-ITnose

servlet方式通过Cookie记住登录时的用户名和密码_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:34:321848browse

1.建立web工程

2.创建存放servlet的包

 

3右键包,新建servlet,路径将前面的servlet去掉,只需要doPost和doGet方法

编写servlet

CookieServlet.java代码如下:

package test1029;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CookieServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");                String uname=request.getParameter("uname");        String password=request.getParameter("password");        String ck=request.getParameter("ck");                //被选中的状态是on 没有被选中的状态下是null        if("on".equals(ck)){        //构造Cookie对象        //添加到Cookie中        Cookie c=new Cookie("users", uname+"-"+password);                //设置过期时间        c.setMaxAge(600);                //存储        response.addCookie(c);    }    }}

 

配置文件web.xml

  test1029      This is the description of my J2EE component    This is the display name of my J2EE component    CookieServlet    test1029.CookieServlet        CookieServlet    /CookieServlet        index.html    index.htm    index.jsp    default.html    default.htm    default.jsp  

index.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%//el表达式String names="";String pwd="";//取出CookieCookie [] c=request.getCookies();for(int i=0;i              My JSP 'index.jsp' starting page                              
用户名:
密码:
记住用户名和密码

效果图:

1、项目运行之后,先进入登录界面,填写用户名和密码,效果如下图

 

2.登录后:

 

 

3.重新访问登录页面,效果如下:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn