因为jsp最后会转换成servlet,这就有可能会覆盖init和destory方法,但是在tomcat 6.0.29,如果要覆写的话,如下:
<%! //覆盖jspInit方法 public void jspInit(){ ServletConfig cfg = getServletConfig(); String name = cfg.getInitParameter("name"); ServletContext context = getServletContext(); context.setAttribute("jsptest","hello"); context.setAttribute("jsptesttwo",name); } public void jspDestroy(){ //TODO } %>
不能覆写_jspInit()和_jspDestory()方法,会hit duplicate error. "_"的意思就是说不要覆写。
在jspInit()中可以像servlet中的init方法一样拿到ServletConfig和ServletContext.给jsp配置初始化参数如下:
<servlet> <servlet-name>testjsp</servlet-name> <jsp-file>/index.jsp</jsp-file> <init-param> <description>name</description> <param-name>name</param-name> <param-value>Rose</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>testjsp</servlet-name> <url-pattern>/index.jsp</url-pattern> </servlet-mapping>
pageContext可以通过下面方式访问其他作用域的属性:
pageContext.getAttribute("foo","name",PageContext.APPLICATION_SCOPE);
pageContext.getAttribute("foo","name",PageContext.SESSION_SCOPE);
pageContext.getAttribute("foo","name",PageContext.REQUEST_SCOPE);
如果没有设置范围,则会从page-->request-->session-->application由小到大顺序查找。
JSP的三个指令:
<%@page import="javax.servlet.jsp.jstl.core.Config"%> <%@ taglib tagdir="" prefix="" %> <%@ include file="" %>
jsp中禁用scriptlet,java表达式和声明。
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </jsp-config>
如果仍旧使用scriptlet或者java表达式这些,会hit error.
org.apache.jasper.JasperException: /index.jsp(5,2) Scripting elements ( <%!, <jsp:declaration, <%=, <jsp:expression, <%, <jsp:scriptlet ) are disallowed here.
在JSP中忽略EL:
<%@ page isELIgnored="true" %>
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <!-- <scripting-invalid>true</scripting-invalid> --> <el-ignored>true</el-ignored> </jsp-property-group> </jsp-config>
页面上的优先级要高些。