Preface

JSP It can be expressed in a simple and easy way as :Html+Java=JSP,JSP engineering service Java Programming language writing class XML Of tags and scriptlets, To encapsulate the processing logic for generating dynamic web pages . Web pages can also be accessed through tags and scriptlets Access the application logic of the resources existing in the server .JSP Separate web logic from web design and display , Support reusable component-based design , To base on Web The development of new applications becomes fast and easy .

official account :「 Shallow feathered IT hut 」

1、 conversation

「 Conversation in life :」

  • Let's discuss something

  • What's the matter

  • Borrow some money

  • feed ... feed ... I have a bad signal here ...

「 Conversation in software :」

  • Open the browser -> To access the application -> Close the browser

  • The user opens a browser , Click on multiple hyperlinks , Access multiple servers Web resources , Then close the browser , The whole process is called a conversation

「 Some problems to be solved during the conversation :」

  • Each user is in the process of using the browser to talk with the server , It's inevitable that each will generate some data , The server has to find a way to save the data for each user

  • for example : Multiple users click on a hyperlink through a servlet Each bought a product , The server should find a way to keep the goods purchased by each user in their own place , So that these users can check out servlet when , Settle accounts servlet You can get the goods purchased by each user and check out for the user

「 Conversational Technology :」

  • Cookie: The technology of saving data in the browser client

 The server takes each user's data as cookie It's written to the user's browser . When the user uses the browser to access the web Resource time , They will bring their own data to . such ,web What the resource deals with is the data of each user 

  • Session: The technology of saving data in the server

 At runtime, the server can create a unique browser for each user session object , because session Exclusive for user browser , So the user is accessing the server web Resource time , You can put your own data in your own session in , When the user goes to visit other servers web Resource time , Other web Resources from the user's own session Take out data to serve users 

2、Cookie

「 principle :」

  • Server creation cookie object

  • send out cookie Information to the browser  

 for example , Add... To the response header  Set-Cookie: name=zhangsan

  • The browser will get cookie The information is stored in the browser

  • Next time through the browser web When applied , The request data will carry cookie Information

 for example , Request header  Cookie: name=zhangsan

  • The server receives a message from the browser cookie Information

「 Use :」

Cookie(String name, String value)  establish cookie Object constructor ,value It's a string type , Cannot use Chinese
public String getName()  obtain Cookie Name
public String getValue()  obtain Cookie Value
public void setValue(String newValue) Set up Cookie Value
public void setMaxAge(int expiry) Set up Cookie Maximum storage time of , Unit second , namely cookie The validity of the , Default session end ,cookie invalid
public int getMaxAge() obtain Cookies The validity of the
public void setPath(String uri)  Set up cookie The effective path , For example cookie The valid path for is set to "/aaa", So browser access "aaa" Of web Resource time , I'll take it with me cookie
public String getPath()  obtain cookie The effective path 

  • Code demonstration :

public void cookie1(HttpServletRequest request, HttpServletResponse response){
  // establish cookie object
    Cookie cookie = new Cookie("name", "zhangsan");
    
    // If there is the same name Worth cookie, The latter will replace the former cookie Content
    //Cookie cookie1 = new Cookie("name", "lisi");
    
    //cookie Medium name and value They're all string types
    //Cookie cookie1 = new Cookie("age", "10");
    
    //cookie Chinese... Cannot appear in
    //Cookie cookie1 = new Cookie("name", " Zhang San ");
    
    // By responding, we will cookie The data is sent to the browser
    response.addCookie(cookie);
    //response.addCookie(cookie1);
    
    // Get... In the request cookie data
    //ctrl + 1,Enter
    //ctrl + 2, l
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
     for (Cookie cookie2 : cookies) {
      //  obtain cookie Of name And corresponding value
      System.out.println(cookie2.getName());
      System.out.println(cookie2.getValue());
     }
    }
 }
 
 public void cookieTime(HttpServletRequest request, HttpServletResponse response){
  
  Cookie cookie = new Cookie("name", "zhangsan");
  // Set up cookie The expiration time of
  // Unit second
//  cookie.setMaxAge(60 * 60);
  
  // You can delete the existing cookie
//  cookie.setMaxAge(0);
  
  // Expiration time : At the end of the conversation
  cookie.setMaxAge(-1);
  
  response.addCookie(cookie);
  
 }
 
 public void cookiePath(HttpServletRequest request, HttpServletResponse response){
  Cookie cookie = new Cookie("name", "lisi");
  
  // The path is different ,name identical , It won't cover the original cookie
  // The implementation will cookie Pass it on to another web application
  // Set up cookie The path of
  cookie.setPath("/W08_3_T");
  
  cookie.setMaxAge(60 * 60);
  
  response.addCookie(cookie);
  
 }public void cookie1(HttpServletRequest request, HttpServletResponse response){
  // establish cookie object
    Cookie cookie = new Cookie("name", "zhangsan");
    
    // If there is the same name Worth cookie, The latter will replace the former cookie Content
    //Cookie cookie1 = new Cookie("name", "lisi");
    
    //cookie Medium name and value They're all string types
    //Cookie cookie1 = new Cookie("age", "10");
    
    //cookie Chinese... Cannot appear in
    //Cookie cookie1 = new Cookie("name", " Zhang San ");
    
    // By responding, we will cookie The data is sent to the browser
    response.addCookie(cookie);
    //response.addCookie(cookie1);
    
    // Get... In the request cookie data
    //ctrl + 1,Enter
    //ctrl + 2, l
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
     for (Cookie cookie2 : cookies) {
      //  obtain cookie Of name And corresponding value
      System.out.println(cookie2.getName());
      System.out.println(cookie2.getValue());
     }
    }
 }
 
 public void cookieTime(HttpServletRequest request, HttpServletResponse response){
  
  Cookie cookie = new Cookie("name", "zhangsan");
  // Set up cookie The expiration time of
  // Unit second
//  cookie.setMaxAge(60 * 60);
  
  // You can delete the existing cookie
//  cookie.setMaxAge(0);
  
  // Expiration time : At the end of the conversation
  cookie.setMaxAge(-1);
  
  response.addCookie(cookie);
  
 }
 
 public void cookiePath(HttpServletRequest request, HttpServletResponse response){
  Cookie cookie = new Cookie("name", "lisi");
  
  // The path is different ,name identical , It won't cover the original cookie
  // The implementation will cookie Pass it on to another web application
  // Set up cookie The path of
  cookie.setPath("/W08_3_T");
  
  cookie.setMaxAge(60 * 60);
  
  response.addCookie(cookie);
  
 } for example , Request header  Cookie: name=zhangsan

「 characteristic :」

  • One cookie No more than 4k;

  • A browser can save up to 300 individual cookie;

  • A site can save up to 20 individual cookie;

  • cookie Can only store string data , No Chinese support

3、Session

「 brief introduction :」

  • stay Web In development , The server can create a session object for each user browser (session object ), Can be used to save the access status of client users .

  • Be careful : One browser owns one session object ( By default )

  • Session Depend on cookie

  • Session Also belongs to domain objects

「 principle :」

1) When accessing the app , If you create session, Every session Object will be assigned a id, be called JSESSIONID
2) The server will session Of id With cookie Send to the browser in the form of , The browser will store the id
3) When you visit the app later , The browser will session Of id Send it to the server
4) Server received session Of id after , Will be based on id Find the corresponding session object , If not found , Create a new session object 

「 Use :」

  • Common methods :

request.getSession()  obtain session object , If it doesn't exist , establish
public void setAttribute(String name,String value) Sets the value of the property with the specified name , And add it to session Within the scope of conversation
public Object getAttribute(String name) Gets the value of the property with the specified name in the context of the session , The return value type is object, If the attribute does not exist , Then return to null.
public void removeAttribute(String name), Delete... With the specified name session attribute   
public void invalidate(), send session invalid . The current session can be invalidated immediately , All objects stored in the original session can no longer be accessed .
public String getId( ), Get the current session ID. Each session has a unique identifier on the server side sessionID,session The only data object sends to the browser is sessionID, It's usually stored in cookie in .
public void setMaxInactiveInterval(int interval)  Set the maximum duration of the session , The unit is seconds , A negative number means that the conversation never fails .
public int getMaxInActiveInterval(), Gets the maximum duration of the session .

  • Code demonstration :

// Will be based on session Of id  Find whether the server has a corresponding session object , If there is , return session object ; If not created session object
  // establish session After the object , Will JSESSIONID With cookie In the form of browser side
  HttpSession session = request.getSession();
  //session Of id, Unique    JSESSIONID
  String id = session.getId();
  System.out.println(id);
  
  // By default ,JSESSIONID The expiration time of is at the end of the session , In order to be able to access session object , Need to manually JSESSIONID Store in cookie in , And set an appropriate expiration time
  Cookie cookie = new Cookie("JSESSIONID", id);
  cookie.setMaxAge(30 * 60);
  response.addCookie(cookie);
  
  // Set up session The expiration time of , Unit second , Default 30 minute
  session.setMaxInactiveInterval(10 * 60);
  
  // towards session Data is stored in the domain
  session.setAttribute("name", " Zhang San ");
-----------------------  
// according to JSESSIONID look for session object , If there is , return ; If it doesn't exist , return null
  HttpSession session = request.getSession(false);
  if(session != null){
   // Get the data in the domain
   System.out.println(session.getAttribute("name"));
   
   // Get all the attribute values in the domain
   //session.getAttributeNames();
  } stay Web In development , The server can create a session object for each user browser (session object ), Can be used to save the access status of client users 

  • When accessing a resource , If you haven't logged in , Jump to the login screen . If you've logged in , In a certain amount of time , You can access the resource directly

「 Ban cookie To deal with :」

  • session rely on cookie, Because the server needs to be based on sessionId, Then find the client's session object , If the browser is disabled cookie, You need to be right about URL Rewrite , In this way, the server will receive the request with sessionId

  • Usage method :

response.encodeURL(String url)

  • It will determine if the client browser is disabled cookie, If disabled , So this method will be in URL Back up jsessionId, Otherwise, it will not add

4、JSP

「 What is? JSP:」

  • Java Server Pages, It and servlet The technology is the same , yes Java For developing dynamic Web Technology of resources

Jsp amount to Java + html
JSP The most important feature of the game is , Write jsp It's like writing html. comparison html for ,html Only static data can be provided to users , and Jsp Technology allows you to nest java Code , Provide users with dynamic data . comparison servlet for ,servlet It's hard to typeset the data , and jsp Except that it can be used java Code generates dynamic data at the same time , It's also easy to typeset the data .
Whether it's JSP still Servlet, Although both can be used to develop dynamic web resources . But because of this 2 Gate technology has its own characteristics , In long-term software practice , People gradually put servlet As web Controller components in the application to use , But the JSP Technology is used as a data display template .
The reason lies in , Program data is usually beautified before output , Give Way jsp Existing java Code generates dynamic data , Beautifying the page will make it difficult to maintain ; Give Way servlet Both generate data , Nested in it again html Code beautifies data , It also leads to poor program readability , Difficult to maintain .
So the best way is based on the characteristics of these two technologies , Let them be responsible for their own ,servlet Only responsible for generating data in response to requests , And bring data to jsp, Data display jsp To do it .

「JSP Execution process :」

  • JSP It's essentially servlet

  • First visit jsp file , Will be in tomcat Of work Generate corresponding java file , And then compile it into a bytecode file , perform jsp when , In fact, it is the implementation of the corresponding class file , And implement the relevant methods

  • Visit the... Again jsp when , Directly from work Next find the corresponding class file , And implement

5、JSP grammar

「JSP Script :」

<% 
Java sentence
%>
Be careful :JSP Only... Can appear in the script java Code , No other template elements can appear (html Related labels ), JSP The engine is translating JSP On the page , Will JSP Script Java The code will be placed intact in Servlet Of _jspService In the method .
JSP In the script fragment Java The code has to strictly follow Java grammar 

  • Code demonstration :

<!-- jsp Script , The variables declared in the script are placed in _jspService In the method  -->
<%
 int num = 10;
 String name = "zhangsan";
 
 System.out.println(name);
 
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String dateStr = sdf.format(date);
 System.out.println(dateStr);
%>
In a single script Java Statements can be incomplete , however , The result of the combination of multiple script fragments must be complete Java sentence , for example :
<%
 for (int i=1; i<5; i++) 
 {
%>
 <H1>hahahaha</H1>
<%
 }
%>
<%
 for(int i = 1; i <= 6; i++){
  response.getWriter().write("<h" + i + "> title " + i + "<h" + i + "/>");
 }
%>
<%
 for(int i = 1; i <= 6; i++){ 
%>
<h<%=i %>> title <%=i %></h<%=i %>>
<%
 }
%>

「JSP expression :」

<%=java The expression of  %>
current time :<%= new java.util.Date() %> 
JSP When the engine translates script expressions , Will convert the program data to a string , Then use... In the corresponding position out.write(…)  Input data to client .
Be careful :JSP Variables or expressions in script expressions cannot be followed by semicolons (;).

  • Code demonstration :

<!-- jsp expression  -->
<!--   amount to out.print(name.length() ); -->
<%=name %>
<%=name.length() %>

「JSP Statement :」

<%! 
Defining variables 、 Such method
%>
Jsp Statement java The code is translated into _jspService Outside of the method , It becomes an instance variable .JSP A declaration can be used to define JSP Page converted to Servlet Static code block of a program 、 Member variables and methods  .

  • Code demonstration :

<!-- jsp Statement  -->
<%!
 // Equivalent to a member variable
 private int aaa = 10;
 // Defines a method
 public int add(int a, int b){
  return a + b;
 }
 
 int sum = add(10, 12);
 //System.out.println(sum);
%>

「JSP notes :」

<%--   Content of notes   --%>

6、JSP Three major instructions

「 brief introduction :」

  • JSP The instruction does not directly produce any visible output , Just tell the engine what to do with it JSP The rest of the page

  • JSP The basic syntax format of the instruction :

<%@  Instructions   Property name =" value " %>

「include Instructions understand :」

include Instructions are used to introduce other JSP page , If you use include Instruction introduced other JSP page ,JSP The engine will put these two JSP Translate into a servlet. therefore include Instruction introduction is also known as static introduction .
grammar :
  <%@ include file="relativeURL"%>
   Among them file Property is used to specify the relative path of the imported file .file Property must be set using relative path , If the “/” start , Means relative to the present WEB The root directory of the application , otherwise , Represents relative to the current file .
Be careful :
The introduced file must follow JSP grammar .
The imported file can use any extension , Even if its extension is html,JSP The engine will follow suit jsp The way the page handles its contents .
Due to the use include The instructions will relate to 2 individual JSP page , And will 2 individual JSP Translate into a servlet, So this 2 individual JSP Page instructions cannot conflict (pageEncoding Except for the guide bag ).

  • Code demonstration :

<!-- include Instructions  , It is equivalent to combining multiple files into one file , Convert to a java file -->
<%@ include file="header.jsp" %>

「page Instructions understand :」

 Used for definition JSP Various properties of the page , No matter what page The command appears in JSP Where in the page , It's all about JSP page , In order to keep the program readable and follow good programming habits ,page It's better to put the instructions in the whole JSP Start of page .

  • page The complete syntax of the instruction :

<%@ page 
  [ language="java" ] 
  [ 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" ]

  • Code demonstration :

<%--
page in
session The value is defaults to true, Indicates that a session object . When not needed , It can be set to false
pageEncoding jsp The encoding of the file itself
contentType  The encoding of the content that the server sends to the browser
--%>
<%@ page language="java" 
 import="java.util.*"
 contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    session="false" 
%>

「taglib Instructions understand :」

 Used in JSP Page to import the tag library 

7、 Built-in objects

「 principle :」

 Every JSP  The first time the page is visited ,WEB The container will give the request to JSP engine ( That is, a Java Program ) To deal with .JSP The engine will first JSP Translate into a _jspServlet( In essence, it's also a servlet) , And then according to servlet Call method of .
because JSP I will translate it into my first visit servlet, So the first visit is usually slow , But the second visit ,JSP If the engine finds out JSP There is no change , No more translation , It's called directly , So the execution efficiency of the program will not be affected .
JSP The engine is calling JSP Corresponding _jspService when , Will pass or create 9 One and web Develop related objects for _jspService Use .JSP Technology designers are writing for the convenience of developers JSP Get these on the page web References to objects , Specifically defined 9 A corresponding variable , Developers in JSP You can quickly get this through these variables on the page 9 References to large objects .

「 Nine built-in objects understand :」

request   HttpServletRequest
response  HttpServletResponse
application  ServletContext
session    HttpSession
out     JspWriter
pageContext  PageContext 
exception  Throwable
config    ServletConfig
page  Object(this)   Use fewer 

「pageContext:」

pageContext The object is JSP The most important object in technology , It represents the current JSP The running environment of the page , This object not only encapsulates other 8 References to large implicit objects , It itself is also a domain object , Can be used to save data . also , This object also encapsulates web Some common operations often involved in development , For example, include and jump to other resources 、 Retrieve properties in other domain objects, etc 

  • Basic grammar :

<%
  // You can get other built-in objects
  pageContext.getRequest();
  pageContext.getResponse();
  pageContext.getServletContext();
  pageContext.getSession();
  pageContext.getServletConfig();
  pageContext.getException();
  pageContext.getOut();
  pageContext.getPage();
%>

  • Code demonstration :

<%
 //pageContext  Domain object
 //pageContext.setAttribute("msg", "page_msg");
 // The third parameter , Specify to which domain to set data
 // Four domain objects
 pageContext.setAttribute("msg", "page_msg", PageContext.PAGE_SCOPE);
 pageContext.setAttribute("msg", "request_msg", PageContext.REQUEST_SCOPE);
 pageContext.setAttribute("msg", "session_msg", PageContext.SESSION_SCOPE);
 pageContext.setAttribute("msg", "application_msg", PageContext.APPLICATION_SCOPE);
%>

「 Four domain objects :」

request
session
application
pageContext

  • Basic grammar :

<%
  System.out.println(pageContext.getAttribute("msg"));
  System.out.println(request.getAttribute("msg"));
  System.out.println(session.getAttribute("msg"));
  System.out.println(application.getAttribute("msg"));
  
  // Find properties from the domain
  //pageContext->reqeust->session->application
  System.out.println(pageContext.findAttribute("msg"));
%>

8、EL(Expression Language) expression

「 get data :」

EL Expressions are mainly used to replace JSP Script expressions in the page , To retrieve... From various types of domains java object 、 get data .
Use EL Expressions get data syntax :${ identifier }

  • Get data from the specified domain

  • Get object properties

  • Get the value of the set

「 Expression operation :」

  • utilize El The expression can be in JSP Some basic relational operations are performed in the page 】 Logical transport and arithmetic operations , In the JSP Complete some simple logic operations in the page

「 Built-in objects :」

  • EL Expressions define some built-in ( Implicit ) object , Using these implicit objects , Developers can get access to web References to common objects in , So we can get the data in these objects

9、jsp label

「 Built in action tags understand :」

  • as follows :

<jsp:useBean>  Create objects , Objects will be placed in the domain , among :
id  The name of the object created
class  Class name
<jsp:setProperty> Sets the property value of the object , among :
name  Represents the name of the object
  property  Property name
 value  Corresponding value
<jsp:getProperty>  Get attribute value
<jsp:forward page="WEB-INF/aaa.jsp"></jsp:forward>  forward 

「jstl label :」

  • JSTL(JSP Standard Tag Library,JSP Standard label library ) It's a continuous improvement of open source JSP Tag library , Yes, there is apache Of jakarta The team is here to maintain .

  • It mainly includes :

 Core tags (c:) 
JSTL function (fn:)
Format label (fmt:)
Database label
XML label 

  • Core tag library

<c:set>  Set the value , Data is added to the domain
<c:out> stay jsp Display values in
<c:if>  conditional
<c:choose>  Multi condition judgment
  <c:when>
  <c:otherwise>
<c:forEach>  Loop traversal 

  • Use steps :

1) Import jstl-1.2.jar file
2) stay jsp Import the relevant tag library in the
    <!--  Introduce the core tag library , The prefix must use  "c" -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2) Format label
<fmt:formatNumber>  Number formatting
<fmt:formatDate>  Date formatting 

Conclusion

This article is about JSP This is the end of the introduction , There will be more about JSP More articles in series , Thank you for your support !

If you think that asamura's article will help you , Please search and follow on wechat 「 Shallow feathered IT hut 」 WeChat official account , I'll share my computer information knowledge here 、 Theoretical Technology 、 Tool resources 、 The software is introduced 、 The backend development 、 interview 、 A series of articles, such as thoughts on work and some thoughts on life . What you see and what you get , It's all about life . take your time , Work harder , You and I grew up together ...

Previous recommendation

 

「 Ten thousand words and pictures 」 The most auntie in history Java Inherit the details

Whether can food | The technology is more and more new , I love my old friends jQuery Or love it as always

Farewell to praying programming | Unit test the correct landing position in the project

Notes | Millions of high concurrency systems are launched in a week

Component must know must know | The wheels we used for years —Filter and Proxy

【 CV plus points 】hexo Framework to build personal blog site , Teaching by hand .

ES Development of guidelines | How to get started quickly ElasticSearch

Get along well with Redis| Learn this 10 I'll let you take it every minute Redis, Satisfy all your doubts

Dot , One button and three companies are here !