JSP技巧集锦(一)
(Blueski整理编辑)
网页重定向
1 可以使用:
response.sendRedirect("http://www.foo.com/path/error.html");
2 你可以手工修改HTTP header的Location属性,如下:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
3 也可以使用forward:
<jsp:forward page="/newpage.jsp" />
请注意你只能在任何输出还没有发送到客户端之前使用这种方式。
在JSP页中如何设置cookie?
以下scriptlet在客户端设置了一个cookie "mycookie":
<%
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
%>
通常,cookies在JSP页的开始处进行设置,因为它们作为HTTP headers的一部分被送出。
如果你想在关闭浏览器后在cookie中保存数据,你还需要设置expiration date,例如,
cookie_name.setMaxAge( time_in_milisecs );
中途退出
<%
if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection
back to the input form after creating a memento
bean updated with the 'valid' form elements that were input.
this bean can now be used by the previous form to initialize
the input elements that were valid
then, return from the body of the _jspService() method to
terminate further processing */
return;
}
%>
在servlet和JSP之间共享session
这很简单。JSP可以比较简单地创建session对象并使之有效。
在servlet中你要手工做这些工作:
HttpSession session = request.getSession(true); //如果还没有则创建一个session
session.putValue("variable","value");//对session变量赋值。
在jsp中可以这样取得session值:
<%
session.getValue("varible");
%>
类似global.asa的做法
在JSP中没有global.asa的对应物。但你可以有一个workaround来运行。例如,如果你需要存储或存取
application scope变量,你总是可以创建一个javabean,并在页面中需要这些变量的地方将它包含进来。
<jsp:useBean id="globals" scope="application" class="com.xxx.GlobalBean"/>
但是,也有一些产品具有这样的对应:
Allaire公司的产品JRun 3.0将提供global.jsa。JRun 2.x也有global.jsa特性来
to aid the cross-over crowd from ASP.
JRun 2.3.3仍然给予支持,但只对JSP 0.92。当JRun 3.0最终推出时它将支持用于JSP 1.0和1.1的global.jsa。
你可以从http://beta.allaire.com/jrun30得到JRun 3.0 beta 5 (04/05/2000)。
另外,Oracle的JSP支持globals.jsa。
|