2.創(chuàng)建存放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"); //被選中的狀態(tài)是on 沒有被選中的狀態(tài)下是null if("on".equals(ck)){ //構(gòu)造Cookie對(duì)象 //添加到Cookie中 Cookie c=new Cookie("users", uname+"-"+password); //設(shè)置過期時(shí)間 c.setMaxAge(600); //存儲(chǔ) 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 /CookieServletindex.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表達(dá)式String names="";String pwd="";//取出CookieCookie [] c=request.getCookies();for(int i=0;i"> My JSP 'index.jsp' starting page
效果圖:
1、項(xiàng)目運(yùn)行之后,先進(jìn)入登錄界面,填寫用戶名和密碼,效果如下圖
2.登錄后:
3.重新訪問登錄頁面,效果如下:
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com