假设a.jsp是客户端,b.jsp是客户端,c.jsp是服务端
现在要做的就是客户端在a.jsp页面提交表单信息到服务端c.jsp,c.jsp再将表单信息保存到cookie中,并转发或者重定向到b.jsp客户端,这样就
达到了我们将服务端生成的cookie保存到客户端的作用,但是中文输入保存cookie时会报错
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.net.URLDecoder"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>客户端a页面</title> </head> <body> <% String uname=""; Cookie[] cookies = request.getCookies(); if(cookies!=null) for(Cookie cookie:cookies){ if("uname".equals(cookie.getName())){ //客户端获取cookie 后 解 码 uname= URLDecoder.decode(cookie.getValue(), "UTF-8"); } } %> <form action="./c.jsp" method="get"> 姓名:<input type="text" name = "uname" value="<%=uname %>"/><br/> 密码:<input type="password" name="upsd"/><br/> <input type="submit" value="提交" /> <!-- 发送信息到服务端,服务端再用cookie保存返回到客户端 --> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>客户端b页面</title> </head> <body> c已经将cookie给我了 </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.net.URLEncoder"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>服务端c页面</title> </head> <body> 我是c服务端页面,我要保存cookie,然后转发回b客户端页面<br/> <% request.setCharacterEncoding("UTF-8"); String name = request.getParameter("uname"); String psd = request.getParameter("upsd"); Cookie c1 = new Cookie("uname", URLEncoder.encode(name, "UTF-8")); //ck.setPath("/"); //设置cookie的路径,只有包含这个路径(以这个路径为前缀)的文件才能访问这个cookie c1.setMaxAge(Integer.MAX_VALUE); //设置cookie的最大保存时间 response.addCookie(c1); Cookie c2 = new Cookie("upsd",psd); out.print(c1.getName()+"====="+c1.getValue()); response.addCookie(c1); response.addCookie(c2); response.sendRedirect("./b.jsp"); %> </body> </html>