Hello, today for you children to share JSP, quickly take out a small book to write it down!

1. Introduction to the JSP

  1. JSP full name is Java Server Pages. JSP is a text-based program characterized by the co-existence of HTML and Java code!

  2. JSP itself is a Servlet, Tomcat access to any resource is accessing the Servlet!

JSPS are Java programs that encapsulate servlets

  • Compilation principle:

The first time the browser requests 1.jsp, Tomcat converts 1.jsp to a class like 1_jsp.java and

Compile this file into a class file. After compiling, run the class file in response to the browser’s request.

  • Life cycle:

There is only one instance at run time, and the init() and destroy() methods of the Servlet are also called when the JSP initializes and destroys

  • JSP scripts (Java code)

Enclose it in <% %>

Expression output (various types of variables) : <%=%>

  • JSP directive

<%@ Directive attribute name =” value “%>

  • The page directive

<%@ page contentType=”text/html; charset=UTF-8″ language=”java” %>

  • Chinese garbled characters

Specify contentType=”text/ HTML; charset=UTF-8″

  • Error page (404, NullPointerException)
<error-code>404</error-code>

<location>/error.jsp</location>
Copy the code
<exception-type>java.lang.NullPointerException</exception-type>

<location>/error.jsp</location>
Copy the code
  • The include directive, which statically includes pages

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

Include the code content of the file, and then compile

  • Include behavior, dynamic include

<jsp:include page=”head.jsp”/>

The included page is compiled, and the results of the page are written to the included page

  • Param behavior

When the JSP :include and JSP: Forward actions are used to introduce or forward requests to other resources

You can use the JSP :param behavior to pass parameters to this resource.

<jsp:include page=”head.jsp”> jsp:param</jsp:param> jsp:include

  • Forward behavior

<jsp:forward page=”head.jsp”>

<jsp:param name="username" value="lwclick"/>
Copy the code

</jsp:forward>

Go to the 1.jsp page and jump to the head.jsp page

The < %

String ss = request.getParameter("username");
Copy the code

% >

The obtained parameters are:

<%=ss%>

2. Scope of built-in objects and properties

2.1. Nine built-in objects:

  • pageContext

  • The pageContext. GetSession (), pageContext. Getpages ()… Gets the other eight built-in objects

  • Set /get/removeAttribute (add scope), add find

Page –> Request –> Session –> Application

page

  • Page is the HttpJasPage object

  • The Page object is equivalent to the normal Java class this

config

  • Config is actually ServletConfig

request

  • Request is essentially HttpServletRequest

  • set/get/removeAttribute

response

  • Response is essentially HttpServletResponse

session

  • A session is really just an HttpSession

  • <%@page session= “false” %>

  • set/get/removeAttribute

application

  • Application is actually a ServletContext object

  • set/get/removeAttribute

exception

  • Exception is an object of the java.lang. exception class

out

  • The out object is used to output data to the browser, and its counterpart is the PrintWriter object for the Servlet. (Out with cache)

  • All output in JSP pages is expressed (<%=%>)

2.2. Four attribute ranges (Set /get/removeAttribute)

  • Page [Save attributes in one page only, skipping pages does not work]

  • Requet [Save attributes in one request only, server redirect is valid, browser redirect is invalid]

It’s useless after the user reads it

  • Session [Save attributes in a session scope, regardless of the jump, not after closing the browser]

Users will use it later

  • Application [Save in the entire server, all users can use]

When a user runs out, he has to give it to another user

3. JavaBean

  1. Entity class
  2. A table uses a bean class

Rules:

  • Parameterless constructor

  • Privatization of member attributes

  • If encapsulated properties need to be manipulated externally, you must write setter and getter methods of public type

jsp:useBean

Finds the JavaBean object with the specified name in the specified domain scope

If it does, a reference to the JavaBean object is returned

If it does not exist, instantiate a new JavaBean object and store it in the specified domain scope with the specified name

< JSP :useBean id=” name of the instantiated object “class=” full name of the class” scope=” save scope “/>

<%@ page contentType=”text/html; charset=UTF-8″ language=”java” %>

<jsp:useBean id=”person” class=”domain.Person” scope=”page”/>

The < %

person.setName("lwclick");

System.out.println(person.getName());
Copy the code

% >

jsp:setProperty

Get the information for the form and import it into the javaBean object to set the value of the property

< JSP :setProperty name= “object name” property=”*”/> Automatic matching

< JSP :setProperty name= “object name” property= “property name” /> Specify the property

<input type="text" name="age"> <input type=" name" value=" submit" >Copy the code

<jsp:useBean id=”person” class=”domain.Person” scope=”page”/>

<%– specify the attribute name as age–%>

<jsp:setProperty name=”person” property=”age”/>

The < %

System.out.println(person.getAge());
Copy the code

% >

The JavaBean property name must match the name of the form’s name

jsp:getProperty

output

< JSP :getProperty name=” object name “property=” attribute name “/>

<%– output with JSP :getProperty –%>

<jsp:getProperty name=”person” property=”username”/>

<jsp:getProperty name=”person” property=”age”/>

4. EL expression

  • The EL expression is used in “${}” enclosed script, mainly used to read data, content display!

  • If the corresponding object attribute is not found, the blank string “” is returned instead of null

demo1.jsp

The < %

SetAttribute ("name", "aaa"); System.out.println(" Set an attribute to session ");Copy the code

% >

demo2.jsp

${name}

  • Gets the data of the domain object

application.setAttribute(“name”, “aaa”);

${name}

  • Gets the properties of the JavaBean

<jsp:useBean id=”person” class=”domain.Person” scope=”session”/>

<jsp:setProperty name=”person” property=”age” value=”22″/>

${person.age}

  • Get the data for the collection – list

The < %

List<Person> list = new ArrayList();



Person person1 = new Person();

person1.setUsername("lwclick");



Person person2 = new Person();

person2.setUsername("hello");



list.add(person1);

list.add(person2);



session.setAttribute("list",list);
Copy the code

% >

${list[0].username}

  • Get the data for the collection – map

The < %

   Map<String, Person> map = new HashMap<>();



   Person person1 = new Person();

   person1.setUsername("lwclick");



   Person person2 = new Person();

   person2.setUsername("hello");



   map.put("aa",person1);

   map.put(1,person2);



   session.setAttribute("map",map);
Copy the code

% >

${map.aa.username}

${map[“1”].username}

  • Simple operation

The < %

List<Person> list = null;
Copy the code

% >

${list==null?” List set is empty “:” List set is not empty “}

  • If the retrieved data is null, print a blank string “”! This feature allows us to perform data echo operations

The < %

User user = new User(); user.setGender("male"); // Request. setAttribute("user",user) is displayed;Copy the code

% >

<input type=”radio” name=”gender” value=”male”

${user.gender==’male’? ‘checked’ : ‘ ‘} > male

<input type=”radio” name=”gender” value=”female”

${user.gender==’female’? ‘checked’ : ‘ ‘} > female

The FN method library is all about strings

  • Import development packages (jstl.jar, standard.jar)

  • The < % @ taglib prefix = “fn” uri = “java.sun.com/jsp/jstl/fu…” % >

5. JSTL

JSP Standard Tag Library is the JSP Standard Tag Library.

Collection traversal, data output, string processing, data formatting

  • Import development packages (jstl.jar, standard.jar)

  • The < % @ taglib prefix = “fn” uri = “java.sun.com/jsp/jstl/fu… % >

5.1 Core Label Library

Process control, iterative output, usually prefixed with C

c:out

Value property: Specifies what to output

EscapeXml: Output special characters after HTML encoding. The default value is true

Default: output the default value if value is null

The < %

session.setAttribute("name", "zhongfucheng");
Copy the code

% >

<c: value=”${name}” default=” escapeXml=”true”/>

c:set

Value: Specifies the attribute value

Var: Specifies the name of the Web domain property to set (data of types Integer, Double, String, and so on)

Scope: Specifies the Web domain where the property resides

Target: The object on which the property is to be set (javabeans or Map object data)

Property: The name of the property to be set for the object

c:remove

Deleting a Domain Range

<%– Create a JavaBean object and set it to a session-scoped property –%>

<jsp:useBean id=”person” class=”domain.Person” scope=”session”/>

<%– get the person object, set the age property to 32–%>

<c:set target=”${person}” property=”age” value=”32″/>

${person.age}

<%– Delete session attribute –%>

<c:remove var=”person” scope=”session”></c:remove>

${person.age==null?” The person object in the session has been deleted!” “I’m still here!” }

c:catch

Handle exceptions generated in the program

<%– Create a JavaBean object and set it to a session-scoped property –%>

<jsp:useBean id=”person” class=”domain.Person” scope=”session”/>

<c:catch var=”message”>

--%> <c:set target="person" property="age" value="32"/>Copy the code

</c:catch>

${message}

c:if

Test: conditional expression that determines whether to process the contents of the tag body

Var: Specifies the name of a property to which the result of the test property execution is saved in a Web domain

Scope: Specifies which Web domain to save the execution results of the test attribute

<%– if the name is lwclick, you can log in –%>

<c:if test=”${param.name==’lwclick’}”>

<input type="text" name="username"><br> <input type="password" name="password"><br> <input type="submit" value=" login ">Copy the code

</c:if>

<%– If your name is Ouzicheng, register –%>

<c:if test=”${param.name==’ouzicheng’}”>

<input type="text" name="username"><br> <input type="password" name="password"><br> <input type="submit" value=" register ">Copy the code

</c:if>

C: Choose (equivalent to if-else)

The if else process needs to use the choose tag, which needs to be used in conjunction with the WHEN and otherwise tags

<c:choose>

<c:when test="${param.name=='lwclick'}">

	你好啊,lwclick

</c:when>



<c:when test="${param.name=='ouzicheng'}">

	你好啊,ouzicheng

</c:when>



<c:otherwise>

	你是谁啊?别随便过来!

</c:otherwise>
Copy the code

</c:choose>

c:forEach

Var: Specifies the name of the property that will save the current iterated element to the Page Web domain

Items: Collection object to iterate over

Begin: If the items attribute is specified, iterates from the begin element of the collection (numbered from 0)

If not specified, the iteration begins with the value specified by begin and ends with the end value

end

Step: indicates the step of the iteration

VarStatus: information about the object being traversed

Index [returns the current number of objects, counting from 0]

Count how many objects have been traversed, counting from 1

Current the object currently being iterated over

<c:forEach var=”list” items=”${list}” varStatus=”varStatus” >

${varstatus.index}<br>Copy the code

</c:forEach>

c:forTokens

Similar to a collection of the String class’s split() and for loops, the items property contains a String that is split into multiple strings by the contents of the Delims property

<c:forTokens items=”lwclick,lw,lr,xiaoming” var=”name” delims=”,” >

${name}
Copy the code

</c:forTokens>

c:import

Similar to JSP behavior JSP :include/ and JSP directives <%include>

Url [Specify the path to include, all urls on the Internet can be used]

Context [To access other resources in the same Web container, starting with a “/”]

Var [save the contents of the imported file as String]

Socpe [save range, default is page]

CharEncoding [character coding]

VarReader save the contents of the imported file as Reader

<c:out value=”${net}” escapeXml=”true”></c:out>

c:param

The C: Param tag can be nested within the C :import, C: URL, or C: Redirect tag, with additional parameters for the URL address used by these tags.

c:url

Value: Specifies the URL to construct

Var: Specifies the name of the property to save the result of the URL to be constructed to the Web domain

Scope: Specifies which Web domain to save the result of the constructed URL

<c:url value=”2.jsp” var=”url”>

<c:param name="name" value="中 文" > </c:param>Copy the code

</c:url>

I went through the URL rewrite!

c:redirect

This tag can also be used with param tags!

Redirect to 2.jsp with one parameter:

<c:redirect url=”2.jsp” >

<c:param name="name" value="zhongfucheng">

</c:param>
Copy the code

</c:redirect>

5.2 Customizing Labels

Some complex type conversions, or logical processing, JSTL tag library can not complete, need to custom tags!

  1. Write a Java class that implements the Tag interface.

  2. Create a Tag Library Descriptor (TLD) file in the WEB-INF directory, and describe the Tag processing class (Java class that implements the Tag interface) in the TLD file

5.3 Simple Labels

The SimpeTag interface realizes the tag

6. The interview questions

6.1. JSP static and dynamic inclusion differences

The include directive is a static include. Static inclusion means: include the code content of the file and compile it!

The include behavior is dynamic include. Include behavior is actually encapsulates the request. GetRequestDispatcher (String url). The include (request, response), compile included page first, then the result of the page written to include in the page

6.2. What built-in objects does JSP have? What are the effects?

  1. Request A client request that contains parameters from a GET/POST request
  2. Response A response that the web page returns to the client
  3. The pageContext page property is managed here, representing the compiled JSP content
  4. Session Duration of the session related to the request
  5. What the Application Servlet is executing
  6. Out is used to transmit the output of the response
  7. Config framework for the servlet
  8. Page THE JSP page itself
  9. Exception An uncaught exception to an error page

6.3. JSP and servlet differences, common ground, the scope of their respective applications?

JSP is an extension of Servlet technology, essentially a simple way of Servlet. JSP is compiled to be servlet-like.

The main difference between servlets and JSPS is that the application logic of servlets is in Java files and completely separated from the HTML in the presentation layer. In the case of JSP, Java and HTML can be combined into a file with a.jsp extension.

JSPS focus on views, while servlets focus on controlling logic.

6.4. Property scope scope

Page [Save attributes in one page only, skipping pages does not work]

Requet [Save attributes in one request only, server redirect is valid, browser redirect is invalid]

Session [Save attributes in a session scope, regardless of the jump, not after closing the browser]

Application [Save in the entire server, all users can use]

6.5. Five common JSTL labels

<c:if>, <c:item>, <c:foreach>, <c:out>, <c:set>

6.6. How is JSP executed? Is it less efficient than servlets?

When a client sends a request to a JSP page, the Web Container converts the JSP into the source code for the servlet (only on the first request), then compiles the transformed servlet and loads it into memory for execution, which responds to the client

JSPS are converted to servlets only on their first execution. Each subsequent execution, the Web container executes the compiled servlet directly, so JSPS and servlets are just different on their first execution. JSPS are slower, and subsequent executions are the same

6.7. Tell the difference between servlets and CGI?

Servlets live in a server process, there is only one instance of a Servlet, a new thread is created for each request, and Servlet instances are generally not destroyed

CGI: A process is created on a request and destroyed on completion, which is less efficient than a servlet

6.8. Avoid automatic session generation for JSP pages

<%@ page session=”false” %>

6.9. JSP design pattern

Mode: refers to the development of the display layer, control layer, data layer operation unified to JSP or JavaBean to process!

Invalid 】

Session [Save attributes in a session scope, regardless of the jump, not after closing the browser]

Application [Save in the entire server, all users can use]

Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen