Do you want to learn JSP in 2020?

Preface

In 2020, do I need to learn JSP?I believe that students who are still in college will certainly have this question.

In fact, I have seen a similar question in 18 years, "Should JSP still learn?"I sent several JSP articles in 18 years, and many developers have commented on "Is this not something of the last century", "Dream back a few years ago" and "How can anyone learn such an old thing?"

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

Now the question has come again. Why is the technology that was defined as "old" a few years ago still hot by 2020? Every year, someone still asks, "Do you still need to learn JSP?"I think the reason is also simple: JSP used really much before!

When I first learned Java, I often heard that JSP and PHP are capable of writing dynamic web pages - "My Teacher".

When we look for relevant learning materials and find JSP everywhere, it gives me the feeling that I can't continue learning without knowing JSP at all.

If you're new to JSP, and if you haven't already done so, I recommend that you know about it. You don't need to go into it, but you can.At least when people talk about JSP, you know what it is and you can understand the code of JSP.

One more thing: If you go to the company, you may also see the JSP code.Although JSP is "old stuff", going to the company may mean maintaining old projects.JSP may not use you to write, but at least it can read, right.

The question arises again. If JSP is an "old thing", what has replaced it?Or use the common template engine "freemarker" Thymeleaf "Velocity", which is not much worse than "JSP", but will perform better.Either the front and back end are separated, and the back end only needs to return the JSON to the front end, and the page does not need the back end pipe at all.

So much said, I would like to say: "JSP is still necessary to understand, it does not take a lot of time to know, I can take you to know JSP in this article"

What is JSP?

The full name of the JSP is Java Server Pages, a java server page.JSP is a text-based program characterized by the coexistence of HTML and Java code!JSP is an alternative to simplifying the work of Servlets. Servlet output HTML is very difficult. JSP is an alternative to Servlet output HTML.

I mentioned in the Tomcat blog that any resource Tomcat accesses is a Servlet!Of course, JSP is no exception!JSP itself is a Servlet.Why do I say that JSP itself is a Servlet?JSPs are actually compiled as HttpJspPage classes when they are first accessed (this class is a subclass of HttpServlet)

For example, if I randomly find a JSP, the compiled JSP will look 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,
      			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>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 works like this: When the browser first requests 1.jsp, Tomcat converts 1.jsp into a class like 1_jsp.java and compiles the file into a class file.After compiling, run the class file to respond to the browser's request.

If you access 1.jsp later, you will no longer recompile the JSP file and call the class file directly in response to the browser.Of course, if Tomcat detects a change in the JSP page, it will recompile.

Since JSP is a Servlet, how do HTML typesetting tags on JSP pages get sent to browsers?Let's look at the source code for 1_jsp.java above.I just went out with write().After all, JSP is just a java program that encapsulates a 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");

One might also ask: How does the code server for JSP pages perform?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 has 9 built-in objects!** Built-in objects are: out, session, response, request, config, page, application, pageContext, exception.

It is important to remember that JSP is essentially a Servlet.JSP was originally designed to simplify Servlet output HTML code.

When to use JSP

Repeat one sentence: JSP is essentially a Servlet.JSP was originally designed to simplify Servlet output HTML code.

Our Java code is written on the Servlet, not on the JSP.You know you've seen the question "How to connect to JDBC using JSP".Obviously, we can do this, but it's not necessary.

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

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

For example, the following Servlet handles the form's data, places it in the request object, and forwards it to the JSP

//Verify that the form's data is valid and 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;
}

JSP gets the data processed by Servlet for display:

What does JSP need to learn

There are only two things we need to learn about JSP: JSTL and EL expressions

EL expression

** Expression Language (EL), which is a script enclosed in ${} to make it easier to read objects!**EL expression is mainly used to read data and display content!

Why use an EL expression?Let's first see how to read object data without an EL expression.Session property 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 A property was set");
%>

</body>
</html>

Get the properties of the 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 looks like it's not too complicated. Let's try EL expression!

Read the properties of the Session settings in 2.jsp

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

${name}

</body>
</html>


It takes only a few simple letters to output the properties set by Session!And output on browser!

EL expressions make it easy to read attributes in objects, submitted parameters, JavaBean s, and even collections!

JSTL

JSTL is called JSP Standard Tag Library, or JSP Standard Tag Library.As the most basic label library, JSTL provides a series of JSP tags, which implement basic functions: traversal of collections, output of data, processing of strings, formatting of data, and so on.

Why use JSTL?

EL expression is not perfect, need JSTL support!In JSP, we have used EL expressions before, and we have learned the power of EL expressions: ** Using EL expressions makes it easy to reference some JavaBean s and their properties without throwing errors like NullPointerException!**However, EL expressions are very limited and cannot traverse collections for logical control.At this point, you need JSTL support!

**The readability, maintainability and reusability of scriptlets are poor!**JSTL is very similar to HTML code, follows the XML tag syntax, uses JSTL to make JSP pages look clean, readable, reusable and complex!

Previously, we used EL expressions to get data from collections, traversing collections was looped through scriptlet code, now we can discard scriptlet code by learning the forEach tag.

Sets a property to Session whose type is a List collection

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

Iterate through the List collection in the session property, items: the collection to iterate over.var: Element to which the current iteration occurs

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

Effect:

Release dry goods

Now I have been working for a while, why do I write JSP for the following reasons:

  • I am a person who has a passion for typesetting. If my classmates pay attention to me early on, they may find that my GitHub and read.me for article navigation change frequently.Current GitHub Navigation wasn't what I wanted (it was too long), and early articles weren't typesetting very well, so I decided to get back on track.
  • My article will be distributed on several platforms, but once it's finished, no one will see it, and the graph bed will probably hang up because of the anti-theft chain of the platform.There are many readers asking me, "Can you turn your article into a PDF?""
  • I've written a lot of series-level articles, and they hardly change much, so they're perfect for persistence.

For these 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.To prevent whoring, follow my public number reply "888" is available.

PDF content is very long, dry goods are very hard, interested students can browse a wave.Keep in mind that JSP only needs to be understood, not every knowledge point in depth, as it is likely not to be used in real-world development.

Documents are hand-beaten and can be asked directly if you don't understand them (public number has my contact number).

The PDF from the previous issue of Sort and Data Structure responded well on the public numbers, with a target of 180 views that exceeded expectations, so I updated it earlier.

If this time it's over 180, we'll have another series of liver next week.What do you want to see? Tell me in a message

Open source project covering all Java backend knowledge points (6K star already): https://github.com/ZhongFuCheng3y/3y

WeChat searches Java3y if you want to keep an eye on my updated articles and shared dried goods in real time.

PDF documents are hand-typed and can be asked directly if you don't understand them (public number has my contact number).

Tags: Java JSP Session Tomcat

Posted on Sun, 22 Mar 2020 22:00:05 -0400 by serenade2