preface
2020, still need to learn JSP? I’m sure some of you who are still in college have this question.
In fact, I have seen similar questions in 18 years “JSP should be learned”. I have published several JSP articles in 2018, and many developers have commented “isn’t this something from the last century?” “Dream of a few years ago.” “How can anyone learn something so old?”
Now the question comes, JSP in 2020, is really old? Yes, it is
Now the question is why a technology that was defined as “old” a few years ago is still hot in 2020, and every year people ask, “Do I still need to learn JSP?” I think the reason is simple: JSP was really used a lot before!
When I first learned Java, I often heard: JSP and PHP is able to write dynamic web pages – “my teacher”.
When we go to find relevant learning materials, found everywhere JSP figure, will give me a feeling: as if do not understand JSP can not continue to learn.
If you’re new to JSP, if you haven’t learned JSP yet, I suggest you do. You don’t need to go into the details of JSP, but you can. At least when someone talks about JSP, you can know what JSP is, can understand the code of JSP.
As a bonus: if you go to the company, you’ll probably see the JSP code. Although JSP is “old stuff,” we may go to the company to maintain old projects. JSP may not have to be written by yourself, but at least you can read it, right?
The question comes again, that JSP if is “old thing”, that is replaced by what? Or use the usual template engines “freemarker”, “Thymeleaf”, “Velocity”, which are not much different from “JSP”, but are much better. Either the front and back ends are separated, and the back end only needs to return JSON to the front end, and the page doesn’t need the backend at all.
Having said that, I would like to say: “JSP is still necessary to know, it doesn’t take a lot of time, just know, this article I can take you to know JSP.”
What is a JSP?
JSP full name is Java Server Pages. JSP is a text-based program characterized by the co-existence of HTML and Java code! JSP is a replacement for servlets, which are very difficult to output HTML, to simplify their work.
As I mentioned in the Tomcat blog, Tomcat accesses any resource by accessing a Servlet! , of course, JSP is no exception! JSP is itself a kind of Servlet. Why do I say that JSP is itself a Servlet? The JSP is actually compiled into the HttpJspPage class (which is a subclass of HttpServlet) when it is first accessed.
For example, if I randomly select a JSP, the compiled JSP looks like this:
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(a) {
return _jspx_dependants;
}
public void _jspInit(a) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy(a) {}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( simply use JSP \r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
String s = "HelloWorda";
out.println(s);
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if(! (tinstanceof 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); }}finally{ _jspxFactory.releasePageContext(_jspx_page_context); }}}Copy the code
The compilation process looks like this: The first time the browser requests 1.jsp, Tomcat converts 1.jsp into a class called 1_jsp.java and compiles the file into a class file. After compiling, run the class file in response to the browser’s request.
After accessing 1.jsp, instead of recompiling the JSP file, call the class file directly in response to the browser. Of course, Tomcat will recompile if it detects any JSP page changes.
Since a JSP is a Servlet, how does the HTML layout tag in a JSP page get sent to the browser? Let’s look at the above 1_jsp. Java source code to know. Write (). After all, JSPS are Java programs that encapsulate servlets.
out.write("\r\n");
out.write("\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write( simply use JSP \r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
Copy the code
One might also ask: How does the JSP page code server perform? Looking back at the 1_jsp.java file, the Java code is directly in the service() of the class.
String s = "HelloWorda";
out.println(s);
Copy the code
**JSP has nine built-in objects! ** Built-in objects include: Out, Session, Response, Request, config, Page, Application, pageContext, exception.
It’s important to remember that JSPS are essentially servlets. It’s just that JSP was originally designed to simplify the HTML code that servlets output.
When to use JSP
Repeat: JSPS are essentially servlets. It’s just that JSP was originally designed to simplify the HTML code that servlets output.
Our Java code is still written on servlets, not JSPS. I once saw a question in Zhihu: “how to use JSP to connect JDBC”. Obviously, we could do that, but we don’t have to.
JSP looks like HTML, and adding a lot of Java code to it is not normal and easy to read.
So, our general pattern is: the Servlet handles the data and forwards it to the JSP, which handles the small portion of the data and the pages written by the JSP itself.
For example, the following Servlet processes the form’s data, puts it in the Request object, and forwards it to the JSP
// Verify that the form data is valid, if not, jump back to the registered page
if(formBean.validate()==false) {// Pass the FormBean object to the registration page before jumping
request.setAttribute("formbean", formBean);
request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
return;
}
Copy the code
JSP get Servlet processed data, do display use:
What do YOU need to learn about JSP
JSP we want to learn actually two enough: JSTL and EL expression
EL expression
** Expression Language (EL),EL expressions are scripts enclosed in ${}, used to read objects more easily! **EL expression is mainly used to read data, content display!
Why use an EL expression? Let’s first look at how to read object data without an EL expression. The Session property is set in 1.jsp
<% @page language=" Java "contentType="text/ HTML" pageEncoding="UTF-8"%> < HTML > <head> <title> Set a property to session </title> </head> <body> <% // Set an attribute to session session.setAttribute("name", "aaa"); System.out.println(" Set an attribute to session "); %> </body> </html>Copy the code
Get the Session setting properties in 2.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> <% String value = (String) session.getAttribute("name"); out.write(value); %> </body> </html>Copy the code
Effect:
Let’s try the EL expression.
Read the Session setting properties in 2.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> ${name} </body> </html>Copy the code
With just a few letters, you can print Session Settings. And output in the browser!
Using EL expressions makes it easy to read properties in objects, submitted parameters, Javabeans, and even collections!
JSTL
JSTL stands for JSP Standard Tag Library. As the most basic tag library, JSTL provides a series of JSP tags to achieve basic functions: collection traversal, data output, string processing, data formatting and so on!
Why use JSTL?
EL expressions are not perfect and need JSTL support! In JSP, we have used EL expression in front, realized the powerful function of EL expression: ** Using EL expression can be very convenient to reference some Javabeans and their attributes, will not throw NullPointerException and other errors! ** However, the EL expression is so limited that it cannot iterate over the set to do logical control. At this point, JSTL support is needed!
**Scriptlet readability, maintainability and reusability are very poor! **JSTL is very similar to HTML code, following the XML tag syntax, using JSTL to make JSP pages appear clean, very readable, very high reuse, can complete complex functions!
Before, we used EL expression to get the data of the collection and traversed the collection with scriptlet code loop. Now we can discard scriptlet code by learning forEach tag.
Set properties to Session. Properties of type List collection
<%
List list = new ArrayList<>();
list.add("zhongfucheng");
list.add("ouzicheng");
list.add("xiaoming");
session.setAttribute("list", list); % >Copy the code
Iterate through the List collection in the session property,items: the collection to be iterated over. Var: current iterated element
<c:forEach var="list" items="${list}" >
${list}<br>
</c:forEach>
Copy the code
Effect:
Put a dry
Now that I have been working for a while, why do I still write JSP? There are several reasons:
- I am a pairtypographyPeople who are pursuing if early following my classmates may find that MY GitHub, article navigation
read.me
It will be replaced frequently. Now,GitHubThe navigation wasn’t to my liking (it was too long), and the earlier article, to be honest, wasn’t very well formatted, so I decided to redo it. - My article will be distributed to several platforms, but no one will read the article after it is posted, and the graph bed may be suspended because of the anti-theft chain of the platform. And because so many readers ask me, “Can you convert your articles to PDF? “
- I’ve written a lot of serial-level articles that don’t change much and are perfect for persistence.
For the above reasons, I decided to put together my series of articles into a PDF/HTML/WORD document. To be honest, it took me a long time to create this document. In order to prevent white piao, concern my public number reply “888” can be obtained.
The PDF is very, very long, and the dry stuff is very, very hard, so if you are interested, you can browse it. Remember: JSP we only need to understand, do not need to go deep to learn every knowledge point, because in the real development is likely to not use.
The content of the document is typed by hand. If you don’t understand anything, you can ask me directly (the official number has my contact information).
The last issue of “sorting and data structure” PDF was well received by the public account, the target was 180 views, which exceeded expectations, so I updated it early.
If more than 180 likes are received this time, a series will be released next week. What do you want to see
Open source project (6 K STAR) :Github.com/ZhongFuChen…
If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.
The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).