servlet向浏览器输出内容太繁琐:
需要写大量的html
修改后,需要重新编译,部署
想要调整布局,似比登天
新建一个JSP,名为HelloWorld.jsp,只是输出一行HelloWorld
HelloWorld.jsp
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<%
out.println("HelloWorld");
%>
</body>
</html>
处理流程
JspServlet编译Jsp
从tomcat的web.xml中可以得到确认:编译jsp之前,tomcat调用JspServlet
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
进入E:\Environment\apache-tomcat-6.0.36\work\Catalina\localhost\DRP2.4\org\apache\jsp发现
其中HelloWorld_jsp.java中的_jspService()方法
publicvoid _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException,ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=GB18030");
pageContext =_jspxFactory.getPageContext(this, request, response,
null,true, 8192, true);
_jspx_page_context = pageContext;
application =pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE HTML PUBLIC\"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>HelloWorld</title>\r\n");
out.write(" </head>\r\n");
out.write(" \r\n");
out.write(" <body>\r\n");
out.write(" ");
out.println("HelloWorld");
out.write("\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null &&out.getBufferSize() != 0)
try { out.clearBuffer(); } catch(java.io.IOException e) {}
if (_jspx_page_context != null)_jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
发现什么没有?这个函数的参数为HttpServletRequest和HttpServletResponse,可能的异常为ServletException;可见此处是把jsp当做了Servlet处理。
扩展名,只是个标识
把tomcat的web.xml中的*.jsp改成*.test
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
依然可以访问网站http://127.0.0.1:8080/JspTest/HelloWorld.test,得到相同结果。
可见,java这种映射机制可以完美的进行解耦。通过<servlet-name>这个中间变量,将<url-pattern>和<servlet-class>形成映射。
同时,JSP只是Servlet的一个表现形式而已。