回顾
jsp内置对象session,实现了与请求相关的HttpSession接口的对象,内置变量名为session。它封装了属于客户会话的所有信息。
sesson的重要方法
见表1所示。
表1 HttpSession的重要方法
方法 |
描述 |
| void setAttribute(String name,Object value) | 将对应的键-值对存入session 对象 |
| Object getAttribute(String name) | 从session 对象中根据键返回值 |
Enumeration getAttributeNames() |
从session 对象中得到所有的键。这些键以Enumeration 形式返回 |
void setMaxInactiveInterval(int interval) |
Specifies the time,in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should nevertimeout. |
| int getMaxInactiveInterval() | Returns the maximum time interval, inseconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method.A negative time indicates the session should never timeout. |
| String getId() | Returns a stringcontaining the unique identifier assigned to this session. |
HttpSession接口
可通过request对象的getSession方法得到一个和request对象相关联的HttpSession对象。
HttpSession getSession()
案例
jsp页面:
<body>
<form action="OutputWelcome">
对我说Hello:<input name="word" type="text"><br>
<input type="submit" value="确定">
<input type="reset" value="取消">
</form>
</body>
OutputWelcome.java:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class OutputWelcome
*/
public class OutputWelcome extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public OutputWelcome() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = this.getServletContext();
String str=request.getParameter("word");
HttpSession session = request.getSession();
session.setAttribute("wordlen",str.length());
RequestDispatcher rd = context.getRequestDispatcher("/welcome.jsp");
rd.forward(request,response);
// String str=request.getParameter("word");
// HttpSession session = request.getSession();
// session.setAttribute("saveit",str);
// response.sendRedirect("welcome.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
welcome.jsp:
<body>
you say:<%=request.getParameter("word") %>
length:<%=session.getAttribute("wordlen") %>
</body>

