jspInit() 和_jspInit() 有什么区别?我能够覆盖 jspInit() 并在初始化 servlet 时调用它。但是 _jspInit() 是空方法,我无法覆盖它。为什么我们有两个不同的版本来实现相同的功能?与 jspDestroy 相同吗? JSP 版本为 2.2,Tomcat 7
更新: PFB的jsp文件:
<%@ page language="java"%>
<!DOCTYPE html>
<html>
<body>
<%! public void jspInit(){
System.out.println("In jspInit");
}
%>
<% System.out.println("Hello world"); %>
</body>
</html>
PFB 生成的 Servlet 文件。
public final class A_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
public void jspInit(){
System.out.println("In jspInit");
}
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
// some code
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
// some code
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
// some code
try {
//some code
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write("<body>\r\n");
out.write("\r\n");
out.write("\r\n");
System.out.println("Hello world");
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {//some code
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
注意:我已经用注释替换了一些代码。它有一个空的 _JspInit() 和覆盖的 jspInit()。我知道我不应该在服务器端代码上使用 System.out
。这是为了理解目的。
最佳答案
核心区别:
_jspInit()
方法由容器生成,如果在 JSP 中使用任何自定义标签。否则不会生成。
如果您尝试覆盖 _jspInit()
并使用自定义标记,容器将抛出编译错误,提示 -duplicate methods。 (将有两个具有相同签名的 _jspInit()
方法)
The difference between overriding jspInit() and jspService() is that - _jspService() will always be there in any JSP->java file and will take precedence and our jspService() method will not be used ever.
But _jspInit() method appears in jsp->java file conditionally. so, our jspInit() method will be invoked when there is no _jspInit() method and this is quite possible.
看看这个不错的article
关于java - jsp中_jspInit()和jspInit()的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34086996/