request对象的生命周期是针对一个客户端(说确切点就是一个浏览器应用程序)的一起请求 当请求完毕之后,request里边的内容也将被释放点
而session的生命周期也是针对一个客户端 但是却是在别人设置的会话周期内(一般是20-30分钟) session里边的内容将一直存在 即便关闭了这个客户端浏览器 session也不一定会马上释放掉的
使用时response.sendRedirect(),如果是跨域跳转,则session会丢失,否则不会。
例如:在本地机上有项目名问web1和web2的两个项目同时运行,从web1跳转到web2当然是跨域跳转,session丢失。但如果是从地址http://localhost:8080/web1跳转到http://127.0.0.1:8080/web2也同样会丢失session。
在web1的servlet中执行response.sendRedirect("/web1/page2.jsp")是域内跳转,session不会丢失,但保存在request中的属性值在page2.jsp中无法取到,也就是说在page2.jsp中通过request.getAttribute()的方法无法取得值,所以只能通过把参数写到url中的方式传递参数,例如:response.sendRedirect("/web1/page2.jsp?action=select").
因为forward()就是转发。sendRedirect就是重定向。两者最大的区别就是一个是:
forward()执行后还是在同一个requestrequest范围,而sendRedirect执行之后就不在同一个request范围里面。
RequestDispatcher.forward()是在服务器端起作用,当使用forward()时,Servletengine传递HTTP请求从当前的Servlet or JSP到另外一个Servlet,JSP 或普通HTML文件,也即你的form提交至a.jsp,在a.jsp用到了forward()重定向至b.jsp,此时form提交的所有信息在 b.jsp都可以获得,参数自动传递.
response.sendRedirect()是在用户的浏览器端工作,sendRedirect()可以带参数传递,比如servlet?name=frank传至下个页面,同时它可以重定向至不同的主机上,且在浏览器地址栏上会出现重定向页面的URL.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="getSession.jsp" method="post">
<p>用户名<input type="text" name="uname"></p>
<p>密码<input type="text" name="pwd"></p>
<p><input type="submit" value="提交"></p>
</form>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String uname=request.getParameter("uname");
String upwd=request.getParameter("pwd");
if(uname !=null & upwd !=null){
out.println(uname+"uname");
session.setAttribute("uname", codeToString(uname));
System.out.println(session.getAttribute("uname"));
response.sendRedirect("array.jsp");
}
%>
<%!
public String codeToString(String str) {//中文编码转换
String s=str;
try{
byte tempB[]=s.getBytes("utf-8");
s=new String (tempB,"utf-8");
return s;
}catch (Exception e){
return s;
}
}
%>
</body>
</html>
跳转到的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
你的用户名是:
<%=(String) session.getAttribute("uname") %>
</body>
</html>