Using session in Servlet:
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("Servlet HelloWorld!"); HttpSession session = request.getSession(false); if(session == null) { response.sendRedirect("ServletLogin"); return; }else { System.out.println(session.getId()); Integer totalAccess = (Integer) session.getAttribute("totalAccess"); // Get session attribute; if(totalAccess == null) { totalAccess = 0; } totalAccess += 1; session.setAttribute("totalAccess", totalAccess); // set attribute response.getWriter().write("TotalAccess: " + session.getAttribute("totalAccess")); }
Using session in JSP:
Jsp page directive:
<%@ page
[ language=”java” ]
[ extends=”package.class” ]
[ import=”{package.class | package.*}, …” ]
[ session=”true | false” ]
[ buffer=”none | 8kb | sizekb” ]
[ autoFlush=”true | false” ]
[ isThreadSafe=”true | false” ]
[ info=”text” ]
[ errorPage=”relativeURL” ]
[ contentType=”mimeType [ ;charset=characterSet ]” | “text/html ; charset=ISO-8859-1” ]
[ isErrorPage=”true | false” ]
%>
“session = true” by default. when access “session”, if session is not existing, will create one by default.
we can set:
<%-- Prevent the creation of a session –%>
<%@ page session="false">
to prevent the Creation of a Session in a JSP Page.
We didn’t mention about the thread safe of session, here is a post from IBM DW:
http://www.ibm.com/developerworks/library/j-jtp09238/index.html
JSP在include时如果不在被Include文件中声明编码, 在外部文件中将出现乱码. 解决方案就是:
在被Include jsp文件中声明:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
此时如果外部jsp编码为 utf-8 — 即: 两者utf-8大小写不同, 将会出现如下错误:
Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html; charset=utf-8, new: text/html; charset=UTF-8)]
可通过配置Eclipse/MyEclipse jsp文件默认编码来避免不必要的操作: http://liguoliang.com/2011/set-eclipse-jsp-files-encoding-utf-8/
Eclipse新建JSP默认编码为ISO8859-1, 不支持中文; 调整方法:
Window/Preferences/JSP Files, Encoding设置为: ISO 10646/Unicode(UTF-8)
Myeclipse设置基本同上, 可参考: http://tmsoft.lsxy.com/index.php?load=read&id=922
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.