當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSP Cookie案例
生活随笔
收集整理的這篇文章主要介紹了
JSP Cookie案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
項目目錄
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>Servlet1</servlet-name><servlet-class>FirstServlet</servlet-class></servlet><servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>SecondServlet</servlet-name><servlet-class>SecondServlet</servlet-class></servlet><servlet-mapping><servlet-name>Servlet1</servlet-name><url-pattern>/servlet1</url-pattern></servlet-mapping><servlet-mapping><servlet-name>SecondServlet</servlet-name><url-pattern>/servlet2</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list> </web-app>index.html
這個頁面用戶輸入名字后,提交到了servlet1—>FirstServlet里面
<form action="servlet1" method="get">名字:<input type="text" name="userName"/><br/><input type="submit" value="go"/> </form>FirstSerlvlet.java
這個頁面給用戶添加cookie,并且go為獲取cookie的鏈接
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class FirstServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response){try{response.setContentType("text/html");PrintWriter out = response.getWriter();String n=request.getParameter("userName");out.print("Welcome "+n);Cookie ck=new Cookie("uname",n);//creating cookie objectresponse.addCookie(ck);//adding cookie in the response//creating submit buttonout.print("<form action='servlet2' method='get'>");out.print("<input type='submit' value='go'>");out.print("</form>");out.close();}catch(Exception e){System.out.println(e);}} }SecondServlet.java
獲取到cookie的值
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class SecondServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response){try{response.setContentType("text/html");PrintWriter out = response.getWriter();Cookie ck[]=request.getCookies();out.print("Hello "+ck[0].getValue());out.close();}catch(Exception e){System.out.println(e);}}}總結
以上是生活随笔為你收集整理的JSP Cookie案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL Sever 基本命令案例
- 下一篇: JSP RequestDispatche