What exactly is a JSP

So what exactly is JSP? In the MVC Model composed of servlets,JSP represents the View,JSP controls the View display. After all the logic is solved in the Servlet(Controller) and Model, Forward to JSP to generate view file (HTML), we also know that writing HTML code in Java is very troublesome, because there are a lot of escape characters need to escape, so people want to write Java in HTML, so JSP was born. JSPS written by people are converted to.java files, compiled to.class, and loaded and initialized as a Servlet.

scriplet

Scriplet is the simplest JSP element, simply inserting a <% %> tag into the HTML, where you can type any Java code you want.

instruction

JSP has three directives, namely page,taglib,include.

1. The page directive

The page directive has a total of 13 attributes, but only a few are commonly used. Import attribute: This attribute is used to guide packages and is used in the Scriplet. ContentType property: If you do not set this property to UTF-8, you will have problems displaying Chinese.

<% @page import=”foo.,java.util.” contentType=” utF-8 “%>

2. The taglib directive

The taglib directive I’ve learned so far only serves one purpose: to import EL functions. This instruction is used when we want to call other Java classes from EL, as follows.

A. Create the class you want to call:

package foo;

public class DiceRoller
{
    public static int rollDice(a)
    {
        return (int) ((Math.random()*6) +1); }}Copy the code

B. Create TLD library description file:

<?xml version="1.0" encoding="UTF-8"? >  
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/j2ee/dtds/web-jsptaglibrary_2_0.xsd"  
        version="2.0">
<tlib-version>1.2</tlib-version>
<uri>DiceFunctions</uri>
    <function>
        <name>rollIt</name>
        <function-class>foo.DiceRoller</function-class>
        <function-signature>
            int rollDice()
        </function-signature>
    </function>
</taglib>
Copy the code

c.JSP:

<%@ taglib prefix="mine" uri="DiceFunctions" %>
<html>
<body>
Hello world
${mine:rollIt()}
</body>
</html>
Copy the code

The purpose of the TLD is to let the EL language find the function in the TLD, and the function must be static, The taglib directive is <% @taglib prefix=”mine” uri=”DiceFunctions” %>, and you can see that the URI attribute corresponds to the URI tag in the TLD, calling rollIt() on behalf of the mine namespace.

3. The include directive

What if we have multiple JSPS with overlapping areas, such as headers and footers, then we can extract those areas as common parts and reuse those pages using the include directive.

<%@ include file=”Header.jsp” %>

expression

An expression is a string of code of the form <%= out.println(“Hello World”) %>. The tag contains Java code, but it is important to note that this Java code must return a value, not void. And you can’t have a semicolon at the end.

The statement

As we said, JSPS still end up being converted to Java code, and the variables defined in Scriplet are local variables, so what if I want to define a global variable, which requires a declaration of the form <%! int i=0; %> Note that there must be a semicolon in this code. Tag classes can define not only variables, but also functions.

Implicit objects

First saw the implicit objects have a little don’t understand what is it, then see, namely we are creating a Servlet, we can get the request and the response, the ServletContext, ServletConfig, Session and so on, So JSPS will eventually become servlets, and how do we use these implicit objects in JSPS? The JSP was already created for us. For proof, see the source code for the container to convert JSPS into servlets:

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
Copy the code

As you can see, we can use implicit objects such as session, Application, config, out, pageContext without declaring them ourselves. Request and Response are also generated — arguments to the jspService() function. We also can be used directly, because in the Servlet requestDispatcher. Forward (request, response) parameters to be here.

 public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
Copy the code

JSP standard actions

JSP standard actions can do some programming without scripting, that is, without Java code. For example, we have a “person” property in our request that corresponds to a foo. person object, and if we want to get that object in our JSP, We can easily use scriptlet to write a Java code capture. But what about front-end people who don’t understand Java? We can then use the standard action:

<jsp:useBean id="person" class="foo.Person" scope="request"> <jsp:setProperty name="person" property="name" value="Fred"  /> </jsp:useBean> Person is <jsp:getProperty name="person" property="name" />Copy the code

The above code does the following:

< JSP :useBean > declares the use of the foo.Person class, which holds request and whose key is “Person”.

< JSP :setProperty > does that if the request doesn’t have this object, it creates its own, named person, and sets its name property to Fred by default.

< JSP :getProperty > prints the Name property of the Person object.

<jsp:include page="Header.jsp" >
  <jsp:param name="subTitle" value="This is a subtitle" />
</jsp:include>
Copy the code

The < JSP :include > tag is similar to the include directive in that it reuses a duplicate JSP page. The < param> tag can pass a parameter to the included JSP, which can be obtained in the included tag using the EL language ${param.subtttle}. Unlike include directives, include directives only apply to static pages, because using an include directive simply translates the included page code into the target JSP code, whereas the < JSP :include > tag applies to dynamic elements. Because it is dynamic, it places the page in response to the contained code in the target location.

EL language

The EL language is very powerful, it can do almost anything standard actions can do, and it’s much simpler, like if you have a Request that has a Person object, and the Person object has a dog object, and the dog object has a name property, So what if we want to print the name of this dog. ${perosn.dog.name} is very simple to do this. In the EL expression, we use the key of the request Attribute directly as the object of the EL. For example, in the Servlet request.setAttribute(“person”,xiaohong), we will simply replace xiaohong with the person object in EL. Similarly, If request.setAttribute(“map”,aHashMap) takes a map as an argument, ${map[“key”]} = ${map. Key} = ${map. Key} = ${map.

An implicit object of EL

The EL language is powerful enough to have its own implicit objects:

EL Implicit object role
pageScope Page scopedattribute
requestScope Request scopedattribute
sessionScope Session-scopedattribute
applicationScope Applied scopedattribute
param {param.id} is equivalent to request.getParameter(“id”)
paramValues This object should be used if the parameter value is a collection
header Equivalent to the request. GetHeader (“…” );
headerValues Applies when one of the header values is a collection
initParam Invoke context initial parameters in web.xml
cookie To get a cookie
pageContext All of the above objects are available via pageContext

Again, it is important to note the difference between requestScope and Param, namely the difference between properties and parameters. Parameters are the parameters of the form submitted by the user, and properties are the attributes set by the programmer himself.

Several ways to get context parameters

1. The script

<%= application.getInitParameter("mainEmail") % >Copy the code

2. Use initParam EL

${initParam.mainEmail}
Copy the code

# # # 3. EL use pageContext

${pageContext.request.getServletContext().getInitParameter("mainEmail")}
Copy the code

Several ways to get form parameters

1. The script

 <%= request.getParameter("foo") % >Copy the code

2. EL use param

${param['foo']}
Copy the code

3. Use pageContext EL

${pageContext.request.getParameter("foo")}
Copy the code