Cattle! Ali interviewer suspected that the interviewer had poor skills, so he was angry all night. JSP Interview Customs Manual

Cattle! Ali interviewer suspected that the interviewer had poor skills, so he was angry all night. JSP Interview Customs Manual

Hello, today I will share the JSP with you children's shoes, and quickly take out a small book and write it down!

1. Introduction to JSP

  1. The full name of JSP is Java Server Pages, java server page. JSP is a text-based program, its characteristic is that HTML and Java code coexist!

  2. JSP itself is a kind of Servlet. When Tomcat accesses any resource, it is accessing Servlet!

JSP is a java program that encapsulates Servlet

  • Compilation principle:

When the browser requests 1.jsp for the first time, Tomcat will convert 1.jsp into a class like 1_jsp.java, and

Compile the file into a class file. After the compilation is complete, run the class file to respond to the browser's request.

  • Life cycle:

There is only one instance during operation, and the init() and destroy() methods of Servlet are also called when JSP is initialized and destroyed.

  • JSP script (java code)

Use <% %> to enclose

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

  • JSP instructions

<%@Command attribute name="value" %>

  • page instruction

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

  • Chinese garbled problem

Specify contentType="text/html;charset=UTF-8" in the page command

  • Jump to the error page (404, NullPointerException)
<error-code>404</error-code> <location>/error.jsp</location> Copy code
<exception-type>java.lang.NullPointerException</exception-type> <location>/error.jsp</location> Copy code
  • include directive, statically include pages

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

Include the code content of the file and compile it

  • include behavior, dynamic include

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

Compile the included page first, and then write the result of the page to the included page

  • param behavior

When using jsp:include and jsp:forward to introduce or forward the request to other resources

You can use jsp:param 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 code

</jsp:forward>

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

<%

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

%>

The parameters obtained are:

<%=ss%>

2. Built-in objects, attribute range

2.1. 9.built-in objects:

  • pageContext

  • pageContext.getSession(), pageContext.getPage() Get other 8 built-in objects

  • set/get/removeAttribute (one more scope), one more find

page > request --> session --> application

page

  • page is the HttpJasPage object

  • The page object is equivalent to this of the ordinary java class

config

  • config is actually ServletConfig

request

  • request is actually HttpServletRequest

  • set/get/removeAttribute

response

  • response is actually HttpServletResponse

session

  • Session is actually HttpSession

  • The page command is configured with the following information, the session will not be available <%@page session= false %>

  • set/get/removeAttribute

application

  • Application is actually the ServletContext object

  • set/get/removeAttribute

exception

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

out

  • The out object is used to output data to the browser, which corresponds to the Servlet PrintWriter object. (Out with cache)

  • In the JSP page, the output is always with expressions (<%=%>)

2.2. 4.attribute ranges (set/get/removeAttribute)

  • page Only save the attributes in one page, the jump page is invalid

  • requet Only save attributes in one request, server jump is valid, browser jump is invalid

The user is useless after reading it

  • session Save attributes in a session range, no matter what kind of jump is valid, it will not work after closing the browser

The user runs out and waits for a while. There is still use

  • application Save in the entire server, all users can use

When the user runs out, it needs to be used by other users

3. JavaBean

  1. Entity class
  2. One table uses one bean class

rule:

  • Constructor with and without parameters

  • Privatization of member properties

  • If the encapsulated property needs to be manipulated by the outside, you must write public type setter and getter methods

jsp:useBean

Find the JavaBean object with the specified name in the specified domain

If it exists, it will directly return the reference of the JavaBean object

If it does not exist, instantiate a new JavaBean object and store it in the specified domain 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"/>

<%

person.setName("lwclick"); System.out.println(person.getName()); Copy code

%>

jsp:setProperty

Get the information of the form, and then import it into the javaBean object to set the value of the attribute

<jsp:setProperty name="object name" property="*"/> Automatic matching

<jsp:setProperty name="Object name" property="Property name"/> Specify the property

User name: <input type="text" name="username"> Age: <input type="text "name="age"> <input type="submit" value="Submit"> Copy code

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

<%--Specify the attribute name as age--%>

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

<%

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

%>

The JavaBean property name must be the same as the name of the form

jsp:getProperty

Output content

<jsp:getProperty name="Object name" property="Property name"/>

<%--Use jsp:getProperty to output--%>

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

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

4. EL expression

  • EL expressions are scripts enclosed in "${}", which are mainly used to read data and display content!

  • If the corresponding object property cannot be found, the blank string "" is returned instead of null

demo1.jsp

<%

//Set an attribute to the session session.setAttribute("name", "aaa"); System.out.println("An attribute is set to the session"); Copy code

%>

demo2.jsp

${name}

  • Get the data of the domain object

application.setAttribute("name", "aaa");

${name}

  • Get properties of JavaBean

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

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

${person.age}

  • Get the data of the collection -list

<%

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 code

%>

${list[0].username}

  • Get the data of the collection-map

<%

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 code

%>

${map.aa.username}

${map["1"].username}

  • Simple calculation

<%

List <Person> list = null; duplicated code

%>

${list==null?"The list collection is empty":"The list collection is not empty"}

  • If the obtained data is null, the empty string "" is output! This feature allows us to perform data echo operations

<%

User user = new User(); user.setGender("male"); //Data echo request.setAttribute("user",user); Copy code

%>

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

${user.gender=='male'?'checked':'' }>Male

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

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

The fn method library is all related to strings

5. JSTL

JSP Standard Tag Library is the JSP standard tag library.

Collection traversal, data output, string processing, data formatting

5.1 core tag library

Process control, iterative output, the prefix is generally c

c:out

value attribute: specify the content to be output

escapeXml: encode special characters in HTML before outputting, the default is true

default: the default value output if the value of value is null

<%

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

%>

<c:out value="${name}" default="The data you want cannot be found" escapeXml="true"/>

c:set

value: Specify the attribute value

var: Specify the name of the web domain property to be set (data of Integer, Double, String, etc.)

scope: specify the web domain where the attribute is located

target: execute the object to set the attribute (data of JavaBean or Map object)

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

c:remove

Delete domain range

<%--Create a JavaBean object and set it as an attribute of the session scope--%>

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

<%--Get the person object, set the value of the age attribute to 32--%>

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

${person.age}

<%--Delete session attributes--%>

<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 as an attribute of the session scope--%>

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

<c:catch var="message">

The <%--target attribute can only be an EL expression, and it is now a string. If the object cannot be obtained, an exception will definitely be thrown--%> <c:set target="person" property="age" value="32"/> Copy code

</c:catch>

${message}

c:if

test: a conditional expression that determines whether to process the content in the tag body

var: Used to specify the name of a certain attribute in a web domain that the execution result of the test attribute is saved to

scope: Specify the web domain to save the execution result of the test attribute

<%--If the name brought over is lwclick, then you can log in--%>

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

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

</c:if>

<%--If the name brought over is ouzicheng, then it is registration--%>

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

User name: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="registration"> Copy code

</c:if>

c:choose (equivalent to if-else)

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

<c:choose>

<c:when test="${param.name=='lwclick'}"> Hello, lwclick </c:when> <c:when test="${param.name=='ouzicheng'}"> Hello, ouzicheng </c:when> <c:otherwise> who are you? Don't come here casually! </c:otherwise> Copy code

</c:choose>

c:forEach

var: Specify the attribute name to save the current iterated element to the web domain of page

items: the collection object to be iterated

begin: If the items attribute is specified, iterate from the beginning element of the collection (numbering from 0)

If not specified, iterate from the value specified by begin until the end value ends

end

step: the step size of the iteration

varStatus: information about the object currently being traversed

index returns the current object, counting from 0

count [how many objects have been traversed, counting from 1]

current Currently iterated object

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

${list}Your subscript is: ${varStatus.index}<br> Copy code

</c:forEach>

c:forTokens

Similar to a collection of split() and for loops of the String class, the items attribute is a string , which will be split into multiple strings by the content of the delims attribute

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

${name}

</c:forTokens>

c:import

JSP jsp:include/ JSP <%include>

url Internet url

context web "/"

var String

socpe page

charEncoding

varReader Save the content of the imported file and store it in Reader type

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

c:param

The c:param tag can be nested inside the c:import, c:url or c:redirect tags, and add parameters to the URL addresses used by these tags.

c:url

value: Specify the URL to be constructed

var: Specify the name of the attribute to save the URL result to be constructed in the web domain

scope: Specify which web domain to save the constructed URL result

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

<c:param name="name" value="China!"> </c:param> Copy code

</c:url>

I went through URL address rewriting!

c:redirect

Used to implement the Redirect function, of course, this tag can also be used with the param tag!

Redirected to 2.jsp, with a parameter:

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

<c:param name="name" value="zhongfucheng"> </c:param> Copy code

</c:redirect>

5.2 Custom label

For some complex type conversions or logic processing, the JSTL tag library can't complete it, you need to define your own tags!

  1. Write a Java class that implements Tag interface [Tag processor class]

  2. Create a tld (Tag Library Descriptor) 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 label

A tag that implements SimpeTag interface

6. Interview questions

6.1. The difference between jsp static inclusion and dynamic inclusion

The include directive is statically included. Static inclusion means: include all the code content of the file, and then compile!

Include is dynamically included. In fact, include is to encapsulate request.getRequestDispatcher(String url).include(request,response), first compile the included page, and then write the result of the page to the included page

6.2. What are the built-in objects of jsp? What are their functions?

  1. request The client request, this request will contain the parameters from the GET/POST request
  2. response page returns the user's response
  3. The properties of the pageContext page are managed here, representing the compiled JSP content
  4. session The session period associated with the request
  5. What the application servlet is executing
  6. out used to send the output of the response
  7. The architectural components of config servlet
  8. page JSP itself
  9. exception for the error page, uncaught exception

6.3. What is the difference between jsp and servlet, what are they in common, and the scope of each application?

JSP is an extension of Servlet technology, and is essentially a simple way of Servlet. After JSP is compiled, it is a "servlet-like".

The main difference between Servlet and JSP is that the application logic of Servlet is in the Java file and is 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.

JSP focuses on the view, and Servlet is mainly used for control logic.

6.4. Attribute scope

page Only save the attributes in one page, the jump page is invalid

requet Only save attributes in one request, server jump is valid, browser jump is invalid

session Save attributes in a session range, no matter what kind of jump is valid, it will not work after closing the browser

application Save in the entire server, all users can use

6.5. 5.commonly used JSTL tags

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

6.6. How is JSP implemented? Is the execution efficiency lower than SERVLET?

When the client sends a request to a jsp page, the Web Container converts the jsp into the source code of the servlet (only at the first request), and then compiles the converted servlet and loads it into the memory for execution. Result response to the client

Jsp will only be converted into a servlet when it is executed for the first time. After each execution, the web container directly executes the compiled servlet, so jsp and servlet are different only when they are executed for the first time. jsp is a bit slower, the subsequent executions are the same

6.7. Tell the difference between Servlet and CGI?

Servlet is in the server process, there will be only one servlet instance, and each request will generate a new thread, and the servlet instance will generally not be destroyed

CGI: Create a process with one request, and destroy it when it is used up, which is less efficient than a servlet

6.8. Avoid automatic session generation on jsp pages

<%@ page session="false" %>

6.9. The design pattern of jsp

Mode: Refers to unifying the operations of the display layer, control layer, and data layer to JSP or JavaBean for processing during development!

Ineffective]

session Save attributes in a session range, no matter what kind of jump is valid, it will not work after closing the browser

application Save in the entire server, all users can use

Okay, that s all for today s article, I hope it can help you who are confused in front of the screen