2020, still need to learn JSP?

Posted by Ricklord on Mon, 23 Mar 2020 07:58:48 +0100

Preface

2020, still need to learn JSP? I believe that the students who are still in university will have this question.

In fact, when I was 18 years old, I had already seen a similar question: "should JSP still learn?". In the past 18 years, I have published several JSP articles, and many developers have commented on "isn't this the thing of the last century", "dream back to a few years ago" and "how can anyone learn such an old thing?"

Now the question is, JSP in 2020, is it really old? Yeah, it's really old

Now the question comes again. Why is the technology that was defined as "old" a few years ago still hot by 2020? Every year, someone is still asking, "do you still need to learn jsp?". I think the reason is very simple: JSP is used in the past is really much!

When I first learned Java, I often heard that JSP and PHP can write dynamic web pages - "my teacher".

When we look for relevant learning materials, we find that JSP is everywhere, which gives me a feeling that if we don't understand JSP, we can't continue to learn at all.

If you are a novice, if you haven't yet learned JSP, I suggest that you can still learn about it. You don't need to go deep into JSP, but you can learn about it. At least when others talk about JSP, you can know what JSP is and understand JSP code.

Add another sentence: you may also see JSP code when you go to the company. Although JSP is "old stuff", we may go to the company to maintain old projects. JSP may not need to be written by yourself, but at least you can understand it, right.

The question is coming again. If JSP is "old stuff", what's the replacement? Or we can use the common template engine "freemarker", "Thymeleaf" and "Velocity". In fact, their usage is not much worse than "JSP", but their performance will be better. Either the front and back ends are separated, the back end only needs to return JSON to the front end, and the page does not need the back end pipe at all.

Having said so much, I would like to say: "JSP is still necessary to understand. It doesn't take a lot of time to know. This article will show you JSP."

What is JSP?

The full name of JSP is Java Server Pages. JSP is a text-based program, which is characterized by HTML and Java code! JSP is an alternative to simplify the work of Servlet. It is very difficult for Servlet to output HTML. JSP is the alternative to Servlet to output HTML.

I mentioned in Tomcat blog that Tomcat is accessing Servlet when accessing any resource! , of course, JSP is no exception! JSP itself is a kind of Servlet. Why do I say JSP itself is a Servlet? In fact, JSP will be compiled into HttpJspPage class (a subclass of HttpServlet) when it is accessed for the first time

For example, I randomly find a JSP, and 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() {
    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,
                  nulltrue8192true);
      _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>Simple use JSP</title>\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 (!(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);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

The compilation process is like this: when the browser requests 1.jsp for the first time, Tomcat will convert 1.jsp into a class such as 1.jsp. Java, and compile the file into a class file. Run the class file after the compilation to respond to the browser's request.

After visiting 1.jsp, we will not recompile the JSP file, and directly call the class file to respond to the browser. Of course, if Tomcat detects that the JSP page has changed, it will recompile.

Since JSP is a Servlet, how is the HTML layout tag in JSP page sent to browser? Let's take a look at the source code of 1_jsp.java above. It turns out that I just used write(). After all, JSP is just a java program that encapsulates Servlet.

out.write("\r\n");
out.write("\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("    <title>Simple use JSP</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");

Some people may also ask: how does the JSP page code server execute? Looking back at the 1_jsp.java file, the Java code is directly in the service() in the class.

String s = "HelloWorda";
out.println(s);

JSP built in 9 objects! Built in objects include: out, session, response, request, config, page, application, pageContext and exception.

It is important to remember that the essence of JSP is actually Servlet. Only JSP was designed to simplify the Servlet output HTML code.

When to use JSP

Repeat: the essence of JSP is actually Servlet. Only JSP was designed to simplify the Servlet output HTML code.

Our Java code is still written on Servlet, not JSP. We have seen a problem in Zhihu: "how to use JSP to connect to JDBC". Obviously, we can, but not necessarily.

JSP looks like HTML, and adds a lot of Java code to it, which is abnormal and not easy to read.

Therefore, our general pattern is: the data processed in Servlet is forwarded to JSP, JSP only deals with a small part of the data and the pages written by JSP itself.

For example, the following Servlet processes the data of the form, places it in the request object, and forwards it to the JSP

//Verify whether the data of the form is legal. If not, go back to the registered page
if(formBean.validate()==false){

  //Pass the formbean object to the registration page before jump
  request.setAttribute("formbean", formBean);
  request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
  return;
}

JSP obtains the data processed by Servlet for display:

What JSP needs to learn

JSP, we need to learn two parts: JSTL and EL expression

EL expression

Expression Language (EL), El expression is a script enclosed by ${}, which is used to read objects more conveniently! El expression is mainly used to read data and display content!

Why use EL expressions? Let's take a look at how to read object data without EL expression! Session property is set in 1.jsp

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
    <title>towards session Set a property</title>
</head>
<body>

<%
    //Set a property to session
    session.setAttribute("name""aaa");
    System.out.println("towards session Set a property");
%>

</body>
</html>

Get the properties of Session setting 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>

Effect:

It seems that it's not too complicated. Let's try the EL expression!

Read the properties of Session setting in 2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>

${name}

</body>
</html>

Only a few letters can output the properties set by Session! And output on the browser!

Using EL expressions can easily read properties, submitted parameters, JavaBean s, and even collections in an object!

JSTL

The full name of JSTL is JSP Standard Tag Library. JSTL, as the most basic tag library, provides a series of JSP tags and realizes the basic functions: Collection traversal, data output, string processing, data format, etc!

Why use JSTL?

The EL expression is not perfect. It needs JSTL support! In JSP, we have used EL expression and realized the powerful function of EL expression: using EL expression can easily reference some JavaBean s and their properties, and will not throw NullPointerException and other errors! However, the EL expression is very limited, it can not traverse the set and do logical control. At this time, JSTL support is needed!

Scriptlet's readability, maintainability and reusability are very poor! JSTL is very similar to HTML code, following XML tag syntax, using JSTL to make JSP pages neat, readable, reusable, and can complete complex functions!

Before we used EL expression to get the data of the collection. We used scriptlet code to loop through the collection. Now we can discard the scriptlet code after learning the forEach tag.

Set the property to the Session. The type of the property is List collection

    <%
        List list = new ArrayList<>();
        list.add("zhongfucheng");
        list.add("ouzicheng");
        list.add("xiaoming");

        session.setAttribute("list", list);
    %>

Traverse the List collection in the session property, items: the collection to be iterated. var: the element that the current iteration is to

    <c:forEach  var="list" items="${list}" >
        ${list}<br>
    </c:forEach>

Effect:

Result of generation

Dry cargo

Now it has been working for some time, why write JSP? There are several reasons:

  • I am a person who pursues typesetting. If you pay attention to my classmates in the early stage, you may find that my GitHub and read.me of article navigation will be changed frequently. Current GitHub Navigation didn't work for me (it was too long), and the early articles, to be honest, didn't work very well, so I decided to start over.
  • My article will be distributed to several platforms, but no one may read the article after it is distributed, and the drawing bed is likely to hang up because of the anti-theft chain of the platform. And because a lot of readers asked me, "can you turn your article into PDF?"? "
  • I've written a lot of series level articles, and these articles will hardly change much, so they are very suitable for "persistence".

For the above reasons, I decided to summarize my series of articles into a PDF/HTML/WORD document. To be honest, it took me a lot of time to create such a document. In order to prevent whoring, I will pay attention to my official account reply "888".

PDF content is very long, dry goods are very hard, interested students can browse a wave. Remember: we just need to understand JSP, not need to learn every knowledge point in depth, because it is likely to not be used in real development.

The contents of the document are all hand beaten, and you can ask me directly if you don't understand anything. Official account has my contact information.

The official account of the PDF in the last phase of the "sorting and data structure" is pretty good. The goal is 180, which is beyond expectation, so I updated it earlier.

If you like more than 180 this time, you can have another series next week. What do you want to see, please leave a message and let me know

img

Open source project covering all knowledge points of Java back-end (6 K star already exists): https://github.com/ZhongFuCheng3y/3y

If you want to follow my updated articles and shared dry goods in real time, wechat search java 3Y.

The contents of PDF documents are all hand beaten. You can directly ask me if you don't know anything. Official account has my contact information.

Topics: Programming JSP Java Session Tomcat