zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JSP Response.addCookie()方法:添加cookie对象

JSP方法对象Cookie 添加 response
2023-06-13 09:12:00 时间

本示例使用 addCookie 方法将信息保存在 cookie 对象中,并获取 cookie 中信息输出在页面中,运行结果如图所示。

JSP Response.addCookie()方法:添加cookie对象

本示例关键代码如下:


 body 

 request.setCharacterEncoding( GBK 

 String name = request.getParameter( name //获取页面中提交的表单信息

 String hobby = request.getParameter( hobby 

 Cookie cookies[] = request.getCookies();//获取cookie对象

 if(cookies!=null){//判断cookie对象是否为空

 for(int i=0;i cookies.length;i++){

 if(cookies[i].getName().equals( name )){//判断指定对象是否为空

 name = cookies[i].getValue();

 }else if(name!=null){

 Cookie c = new Cookie( name ,name);//创建cookie对象

 c.setMaxAge(50);

 response.addCookie(c);

 if(cookies!=null){

 for(int i=0;i cookies.length;i++){

 if(cookies[i].getName().equals( hobby ))

 hobby=cookies[i].getValue();

 }else if(name!=null){

 Cookie c=new Cookie( hobby ,hobby);

 response.addCookie(c);//添加cookie对象

 p 保存数据到cookie的测试 /p 

 form action= index.jsp method= post 

 姓名: input type= text name= name value= %if(name!=null)out.println(name);

 % %--如果cookie中保存了相关信息,在页面中显示--% 

 兴趣: input type= text name= hobby value= %if(hobby!=null)out.println(hobby);% 

 input type= submit value= 保存 

 /form 

 你的名字是: %if(name!=null)out.println(name);% 

 你的兴趣是: %if(hobby!=null)out.print(hobby);% 

 /body 

22775.html

javaJSP