什么是JSP
JSP(Java Server Pages):Java服务器端页面,和Servlet一样,用于动态web技术!
写JSP就像在写HTML。它们之间不同的是,JSP页面里可以嵌入Java代码,提供动态数据。
JSP原理
IDEA使用tomcat服务器,会在tomcat中产生一个work目录;
C:\Users\winner\AppData\Local\JetBrains\IntelliJIdea2022.1\tomcat\e93bc8ad-ed5a-4d64-86d6-0a6e3ce05bf1\work\Catalina\localhost\ROOT\org\apache\jsp
从这儿可以发现JSP文件被转换成为了Java程序。由此得知:浏览器向服务器发送请求,无论是访问什么资源,实际上都是在访问Servlet。JSP的本质上就是一个Servlet。
主要方法
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 {
}
_jspService方法细节捕捉
判断请求方式
if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
final java.lang.String _jspx_method = request.getMethod();
if ("OPTIONS".equals(_jspx_method)) {
response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
return;
}
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP 只允许 GET、POST 或 HEAD。Jasper 还允许 OPTIONS");
return;
}
}
内置对象
final javax.servlet.jsp.PageContext pageContext;// 页面上下文
javax.servlet.http.HttpSession session = null;// session
final javax.servlet.ServletContext application;// applicationContext
final javax.servlet.ServletConfig config;// config
javax.servlet.jsp.JspWriter out = null;// out
final java.lang.Object page = this;// 当前页面
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
HttpServletRequest request;// 请求
HttpServletResponse response;// 响应
JSP文件里面的HTML代码会被转换为out.write("\n")这种格式之后再输出
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
try {
response.setContentType("text/html");
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("<html>\n");
out.write("<body>\n");
out.write("<h2>Hello World!</h2>\n");
out.write("</body>\n");
out.write("</html>\n");
}
JSP文件里面的Java代码不会被转换,会直接输出
<html>
<body>
<h2>Hello World!</h2>
<%
String feeling = "happy~";
%>
i am <%=feeling%>
</body>
</html>
out.write("<html>\n");
out.write("<body>\n");
out.write("<h2>Hello World!</h2>\n");
out.write("\n");
String feeling = "happy~";//原封不动输出
out.write("\n");
out.write("\n");
out.write("i am ");
out.print(feeling);//原封不动输出
out.write("\n");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
标签:Web,Java,write,JSP,jspx,servlet,javax,out
From: https://www.cnblogs.com/growingbambi/p/18004506