JSP全名为Java Server Pages,java服务器页面。JSP是一种基于文本的程序,其特点就是HTML和Java代码共同存在!
为什么需要JSP
JSP是为了简化Servlet的工作出现的替代品,Servlet输出HTML非常困难,JSP就是替代Servlet输出HTML的。
简单使用一下JSP
- 在idea下生成一个JSP,我们来看一下JSP长什么样子
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>简单使用JSP</title>
</head>
<body>
</body>
</html>
- 看起来就像一个HTML页面,前面也说了:JSP的特点就是HTML和Java代码共同存在
- 我们向浏览器输出一句HelloWorld,至于<%%>这个东西,我先不解释!
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>简单使用JSP</title>
</head>
<body>
<%
String s = "HelloWorld";
out.println(s);
%>
</body>
</html>
JSP的工作原理
- 在Tomcat博客中我提到过:Tomcat访问任何的资源都是在访问Servlet!,当然了,JSP也不例外!JSP本身就是一种Servlet。为什么我说JSP本身就是一种Servlet呢?其实JSP在第一次被访问的时候会被编译为HttpJspPage类(该类是HttpServlet的一个子类)
- 刚才我简单使用了一下JSP,它被编译成了这么一个Servlet:
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.Date;
public final class _1_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final HttpServletRequest request, final HttpServletResponse response)
throws java.io.IOException, ServletException {
final PageContext pageContext;
HttpSession session = null;
final ServletContext application;
final ServletConfig config;
JspWriter out = null;
final Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
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("<html>\r\n");
out.write("<head>\r\n");
out.write(" <title>简单使用JSP</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n