[Transfer] Detailed Explanation of JSP for Web Security

Script expression in JSP

JSP script expression (expression) for outputting the data to the client program
syntax: <% = variable or expression%>
<%=new java.util.Date() %>
JSP script expression in the translation engine, the program data will be transferred into a string, then the corresponding position out.print (…) sends data to the client.
The variable or expression in the JSP script expression cannot be followed by a semicolon (;).

Script snippet in JSP

JSP scriptlets are used to write multiple lines of Java code in JSP pages. grammar:

<% 
    多行java代码 
%> 

Note: Only the Java code can appear in the JSP script fragment, and no other template elements can appear. When the JSP engine translates the JSP page, the Java code in the JSP script fragment will be put intact into the Servlet's _jspService method.
The Java code in the JSP script snippet must strictly follow the Java syntax, for example, each execution statement must end with a semicolon (;).

There can be multiple script fragments in a JSP page, and text, HTML tags, and other JSP elements can be embedded between two or more script fragments. Example:
[html] view plaincopy View the code slice derived from CODE to my code slice on CODE

<%  
    int x = 10;  
    out.println(x);  
%>  
<p>这是JSP页面文本</p>  
<%  
    int y = 20;  
    out.println(y);  
%>  

The code in multiple script snippets can be accessed from each other, as if all the code was placed in a pair of <%%>. Such as:

out.println(x);

The Java statement in a single script fragment can be incomplete, but the result of combining multiple script fragments must be a complete Java statement, for example:

<%  
    for (int i=1; i<5; i++)   
    {  
%>  
    <H1>www.it315.org</H1>  
<%  
    }  
%>   

Jsp statement

All the code written in the JSP page will be translated into the servlet's service method by default, and the java code in the Jsp statement will be translated outside the _jspService method. grammar:

<%! 
java代码
%>

Therefore, the JSP declaration can be used to define the static code blocks, member variables, and methods of the Servlet program into which the JSP page is converted.
Multiple static code blocks, variables, and functions can be defined in one JSP declaration, or they can be separately defined in multiple JSP declarations.
The scope of JSP implicit objects is limited to the Servlet's _jspService method, so these implicit objects cannot be used in JSP declarations.

<%!  
static   
{   
    System.out.println("loading Servlet!");   
}  
private int globalVar = 0;  
public void jspInit()  
{  
    System.out.println("initializing jsp!");  
}  
%> 

Jsp comments

JSP comment format:

<%-- 注释信息 --%>

When the JSP engine translates the JSP page into a Servlet program, it ignores the annotated content in the JSP page.

Jsp instruction

JSP directives are designed for the JSP engine. They do not directly produce any visible output, but just tell the engine how to handle the rest of the JSP page. There are three instructions defined in the JSP2.0 specification:
page instruction
Include instruction
taglib instruction

The basic syntax format of the JSP instruction:

<%@ 指令 属性名="值" %>

First, let ’s look at the usage of the
page instruction. The page instruction is used to define various attributes of the JSP page. No matter where the page instruction appears in the JSP page, it acts on the entire JSP page. Following good programming habits, the page instruction is best placed at the beginning of the entire JSP page.
The complete syntax of the page directive defined in the JSP 2.0 specification:

<%@ page 
[ language="java" ] 
[ extends="package.class" ] 
[ import="{package.class | package.*}, ..." ] 
[ session="true | false" ] 
[ buffer="none | 8kb | sizekb" ] 
[ autoFlush="true | false" ] 
[ isThreadSafe="true | false" ] 
[ info="text" ] 
[ errorPage="relative_url" ] 
[ isErrorPage="true | false" ] 
[ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ] 
[ pageEncoding="characterSet | ISO-8859-1" ] 
[ isELIgnored="true | false" ] 
%>

1. Take a look at the page code set by the page command:
Example: <%@ page contentType="text/html;charset=gb2312"%>
The effect of this command is equivalent toresponse.setContentType("text/html;charset=gb2312");

2. Import the java package through the page command: The
JSP engine automatically imports the following packages:

java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*

You can introduce multiple classes or packages into the import attribute of a page instruction, and use <% @ page import = ”java.util.Date, java.sql. , Java.io. ”% Between each package or class > Can be rewritten to use the import attribute of multiple page instructions to import each package or class:

<%@ page import="java.util.Date"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>

3. Let's take a look at the buffer attribute:
<% @ page buffer = ”4kb”%>
Use this attribute to specify the cache size of the out object

4. Let's take a look at the isThreadSafe attribute:
This attribute is known by name and is set to be thread safe. When we discussed Servlet before, when we mentioned that Servlet is a singleton object, it is thread unsafe. We can then Thread safety is achieved by implementing an interface. Here, you only need to set this property value to control the thread safety of the Servlet after Jsp translation:
<% @ page isThreadSafe = ”true | false”%> The default value is true
isThreadSafe = false mode means It runs in Singleton mode.
This mode implements the interface SingleThreadMode.
This mode has only one instance at a time, and the concept of information synchronization does not appear.
If multiple users visit a page in this mode at the same time,
the visitor will execute the page after the visitor has completely executed the page.
isThreadSafe = true mode means it runs in multi-threaded mode.

5. Let's take a look at the session attribute:
<% @ page session = ”false | true”%> The default value is true,
which means that the session cannot be used on this page. That is, if the session
is disabled on this page, Jsp is translated into Servlet will not pass Session object.

6. Let's take a look at the errorPage attribute.
This attribute is used to set the error page after an error on the server side. For example, when we write server code, an exception is suddenly thrown, then a 500 will be returned, which makes the user feel sick. So what we need to do is to set a human error page through this attribute value. When an error occurs on the server, it will jump to this page, for example:
<% @ page errorPage = ”/ error.jsp”%>

7. At the same time there is an attribute isErrorPages:
<@ page isErrorPages = ”false | true”%> The default value is true
whether to open the error page, is to control the function switch of the above errorPage attribute

8. The attribute isELIgnored
<@ page isELIgnored = ”false | true”%> The default value is
whether the function of EL expression is ignored in this page, we generally do not set it, because we will definitely use it on the page EL expression

Note: If an instruction has multiple attributes, these multiple attributes can be written in one instruction or separately.

Include instruction The
include instruction is very simple, that is, the page is included. The code to achieve page inclusion is dynamic inclusion, and the use of the include instruction to achieve page inclusion is static inclusion.

taglib command
This command is also very simple, is to introduce tags

9 implicit objects built into Jsp

When each JSP page is accessed for the first time, the WEB container will hand over the request to the JSP engine (that is, a Java program) for processing. The JSP engine first translates the JSP into a _jspServlet (essentially a servlet), and then calls it according to the servlet calling method.
Because the JSP is translated into a servlet when it is accessed for the first time, the first access is usually slower, but for the second access, if the JSP engine finds that there is no change in the JSP, it is no longer translated, but called directly, so the execution of the program Efficiency will not be affected.
When the JSP engine calls the _jspServlet corresponding to the JSP, it will pass or create 9 objects related to web development for the _jspServlet. In order to facilitate developers to obtain references to these web objects when writing JSP pages, the designers of JSP technology have specifically defined nine corresponding variables. Developers can quickly obtain references to these nine major objects through these variables in JSP pages.
What are these 9 objects, and what are their functions?

request
response
config
application
exception
Session
page
out
pageContext

request:HttpServletRequest
response:HttpServletResponse
session: HttpSession
application: servletContext
config:servletConfig
out:JspWriter
exception
page:this
pageContext

In fact, we have touched many objects above. We introduced them before introducing servlets. About the exception is an exception object, this object will only be generated when an exception is thrown in our Jsp page, otherwise it is This object will not be passed. As for the page object, this is simply the current object, that is, the servlet object translated by jsp, so let's explain the out object and pageContext object in detail.

The out implicit object is used to send text data to the client.
The out object is returned by calling the getOut method of the pageContext object, and its role and usage are very similar to the PrintWriter object returned by the ServletResponse.getWriter method.
The type of the out implicit object in the JSP page is JspWriter. JspWriter is equivalent to a PrintWriter with a cache function. Setting the buffer attribute of the page instruction of the JSP page can adjust its cache size, and even close its cache.
Only when the content is written to the out object and any one of the following conditions is met, the out object calls the ServletResponse.getWriter method, and the PrintWriter object returned by this method actually writes the content of the out object's buffer to the Servlet In the buffer provided by the engine:

1. Set the buffer attribute of the page instruction to turn off the caching function of the out object 2. The buffer of the out object
is full
3. The end of the entire JSP page

The pageContext object is the most important object in the JSP technology. It represents the running environment of the JSP page. This object not only encapsulates references to other 8 implicit objects, it is also a domain object itself (previously we introduced three domain objects : ServletContext, Session, Request), this domain object has the shortest life cycle and the smallest scope. His scope is the current jsp page, and of course it can be used to save data. And, this object also encapsulates some common operations often involved in web development, such as introducing and jumping other resources, and retrieving attributes in other domain objects.

getException method returns exception implicit object
getPage method returns page implicit object
getRequest method returns request implicit object
getResponse method returns response implicit object
getServletConfig method returns config implicit object
getServletContext method returns application implicit object
getSession method returns session implicit object
getOut Method returns out implicit object

PageContext encapsulates the meaning of the other 8 built-in objects, thinking: If the pageContext object is passed to an ordinary java object during programming, what function will this java object have?
This will be reflected when we introduce custom tags later. We only need to pass a pageContext object to operate multiple other objects, which is very convenient.

The method of manipulating the data in the pageContext object
public void setAttribute (java.lang.String name, java.lang.Object value)
public java.lang.Object getAttribute (java.lang.String name)
public void removeAttribute (java.lang .String name)

The pageContext object also encapsulates the method of accessing other fields (the difference from the above method is that there is an additional parameter, which can directly specify the corresponding field)
public java.lang.Object getAttribute (java.lang.String name, int scope)
public void setAttribute (java.lang.String name, java.lang.Object value, int scope)
public void removeAttribute (java.lang.String name, int scope)
represents the constant
PageContext.APPLICATION_SCOPE
PageContext.SESSION_SCOPE
PageContext .REQUEST_SCOPE
PageContext.PAGE_SCOPE

The following method is very important, because this method is to search for data in all domains, the search order is: pageContext-> request-> session-> ServletContext, if the corresponding data cannot be found, an empty string is returned The function of this method is the same as the
findAttribute method of the el expression to be mentioned later (* emphasis, find the attribute in each field)

So far, web development has touched on four domain objects:
pageContext (called page domain)
request (called request domain)
session (called session domain)
servletContext (called application domain)
These four domain objects It is the focus of learning the web, and is also the point of knowledge frequently studied in the written test.
The following questions are clarified:
the life cycle of these 4 objects?
What is a domain? Why are these 4 objects called domain objects?
Which domain object is used in which case.

The PageContext class defines a forward method and two include methods to simplify and replace the RequestDispatcher.forward method and include method, respectively

The resource paths passed to these methods can only be relative paths. If the path starts with "/", it means relative to the root directory of the current WEB application, otherwise, it means relative to the access path to which the current JSP is mapped.

JSP tag library

Although we hope that the JSP page is only used as a data display module, do not nest any java code to introduce any business logic, but it is impossible to introduce a little business logic in actual development, but the introduction of business logic will cause unsightly java code on the page. How to do?
Sun allows users to develop custom tags to encapsulate the java code of the page so that there is no line of java code on the jsp page. Of course, sun company also built some tags in jsp pages (these tags are called jsp tags), developers can use these tags to complete some common business logic of the page.
JSP tags are also called Jsp Action (JSP Action) elements, which are used to provide business logic functions in JSP pages.

<jsp:include>标签  
<jsp:forward>标签  
<jsp:param>标签  
<jsp:useBean>标签
<jsp:setProperty>标签
<jsp:getProperty>标签

1. Tag The
tag is used to insert the output content of another resource into the output content of the current JSP page. This way of introducing the JSP page during execution is called dynamic import.
grammar:

 <jsp:include page="relativeURL | <%=expression%>" flush="true|false" />

The page attribute is used to specify the relative path of the introduced resource, it can also be obtained by executing an expression.
The flush attribute specifies whether to refresh the output content of the current JSP page to the client when inserting the output content of other resources.

<jsp:include>The tags are introduced dynamically (same as using code for include), <jsp:include>and the 2 JSP pages involved in the tags are translated into 2 servlets, and the contents of these 2 servlets are merged during execution. The include instruction is statically imported (introduced at compile time), and the two JSP pages involved are translated into a servlet whose content is merged at the source file level. Regardless of <jsp:include>tags or include directives, they will merge and output the contents of the two JSP pages, so these two pages should not have duplicate HTML global schema tags, otherwise the content output to the client will be a confusingly formatted HTML document.

Example: Use <jsp:include>tags to implement include pages:

<jsp:include page="/head.jsp"></jsp:include>  
<jsp:include page="/foot.jsp"></jsp:include>

Head.jsp and foot.jsp will be translated into servlet separately, this is dynamic inclusion.

Use the include instruction to achieve page inclusion:

<%@ include file="/head.jsp" %>

There is no separate translation of the head.jsp page, because the static code block is used in the code to implement the static page inclusion

2. Tag The
<jsp:forward> tag is used to forward the request to another resource.
grammar:

<jsp:forward page="relativeURL | <%=expression%>" /> 

The page attribute is used to specify the relative path of the resource to which the request is forwarded. It can also be obtained by executing an expression.

3. Or tags
When using and tag introduction or forwarding requests to other resources, you can use tags to pass parameters to this resource.
Syntax 1:

<jsp:include page="relativeURL | <%=expression%>">
<jsp:param name="parameterName" value="parameterValue|<%= expression %>" />
</jsp:include>

Syntax 2:

<jsp:forward page="relativeURL | <%=expression%>">
<jsp:param name="parameterName" value="parameterValue|<%= expression %>" />
</jsp:include>

<jsp:param>The name attribute of the tag is used to specify the parameter name, and the value attribute is used to specify the parameter value. <jsp:forward>You can use multiple <jsp:param>tags in the and tags to pass multiple parameters.

4. Tags, tags, tags
These three tags are used to operate the bean object together, <jsp:useBean>is used to initialize the bean object, the <jsp:setProperty>tag is used to set the attribute value in the bean object, the <jsp:getProperty>tag is used to obtain the attribute in the bean object Value, examples:

<body>  
    <!-- 找到就直接用,找不到实例化 scope默认是page域-->  
    <jsp:useBean id="person" class="com.weijia.domain.Person" scope="page"/>  

    <!-- 直接设置属性值(8种基本类型的转换) -->  
    <jsp:setProperty name="person" property="name" value="xxx"/>  

    <!-- 用请求参数给属性赋值(8中基本类型的转换) -->  
    <jsp:setProperty name="person" property="name" param="name"/>  

    <!-- 获取Person中的属性name的值 -->  
    <jsp:getProperty name="person" property="name"/>  
  </body>  

How to troubleshoot errors in Jsp
The JSP syntax format in the JSP page is incorrect , which cannot be translated into the Servlet source file. The JSP engine will prompt the location (row and column) and related information of the type of error that occurred in the JSP page.
There is no problem with the JSP syntax format in the JSP page, but there is a Java syntax problem in the translated Servlet source file, which causes the Servlet source file translated from the JSP page to fail to compile. The JSP engine will also prompt that such errors occur on the JSP page Position (rows and columns) and related information.
The Servlet program translated from the JSP page has an exception at runtime. This is exactly the same as the runtime error of a normal Java program. The Java virtual machine will prompt the bit (row and column) and related information that the error occurred in the Servlet source file.

Content source:
JavaWeb learning articles-Jsp detailed explanation

Published 30 original articles · Like 13 · Visits 100,000+

Guess you like

Origin blog.csdn.net/u013224189/article/details/49589659