Java Learning Notes 9-1 - JavaWeb

HTTP

HTTP Request

Client - Request - Server
Baidu:

Request URL:https://www.baidu.com/Request Address
Request Method:GET    get Method/post Method
Status Code:200 OK    Status code: 200
Remote(Remote) Address:14.215.177.39:443

Accept:text/html  
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9    language
Cache-Control:max-age=0
Connection:keep-alive

1. Request line
Request in request line: GET
Request method: Get,Post,HEAD,DELETE,PUT,TRACT....

  • get: Requests can carry fewer parameters, are limited in size, display data content in the browser's URL address bar, are not secure, but are efficient
  • post: Requests can carry unlimited parameters, have unlimited size, and do not display data content in the browser's URL address bar. It is secure, but not efficient.

2. Message Header

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache Control
Connection: Tell the browser whether to disconnect or stay connected when the request is complete
HOST: Host..../.

HTTP Response

Server - Response.... Client
Baidu:

Cache-Control:private    Cache Control
Connection:Keep-Alive    Connect
Content-Encoding:gzip    Code
Content-Type:text/html   type  

1. Response Body

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache Control
Connection: Tell the browser whether to disconnect or stay connected when the request is complete
HOST: Host..../.
Refresh: Tell the client how often to refresh;
Location: Relocate the page;

2. Response Status Code
200: Successful request response 200
3xx: Request redirection. Redirect: You're back to my new location for you;
4xx: Resource 404 Not found. Resource does not exist;
5xx: Server code error 500 502: Gateway error

Servlet

Servlet is one of sun's technologies for developing dynamic web.

Sun provides an interface in these APIs called Servlet, and if you want to develop a Servlet program, you only need to complete two small steps:
1. Write a class to implement the Serlet interface
2. Deploy the developed java classes to the web server.

A Java program that implements a Servlet interface is called a Servlet

Servlet Principle

Servlet s are invoked by Web servers that receive browser requests:

Mapping Problem

A servlet can specify a mapping path

  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
  </servlet-mapping>

A servlet can specify multiple mapping paths

  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello2</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello3</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello4</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello5</url-pattern>
  </servlet-mapping>

A servlet can specify a common mapping path

  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello/*</url-pattern>
  </servlet-mapping>

Default Request Path

   <!--Default Request Path-->
   <servlet-mapping>
       <servlet-name>hello</servlet-name>
       <url-pattern>/*</url-pattern>
   </servlet-mapping>

Specify some suffixes or prefixes, etc. (For example, some subsequent frameworks use *.do or *.action, etc.)

  <!--You can customize suffixes to implement request mapping
      Notice,*Path that cannot be preceded by item mapping
      hello/sajdlkajda.qinjiang
      -->
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>*.qinjiang</url-pattern>
  </servlet-mapping>

Priority issues:
An intrinsic mapping path is specified with the highest priority and will follow the default processing request if it is not found

  <!--404-->
  <servlet>
      <servlet-name>error</servlet-name>
      <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>error</servlet-name>
      <url-pattern>/*</url-pattern>
  </servlet-mapping>

ServletContext

When the web container starts, it creates a corresponding ServletContext object for each web program, which represents the current web application

Get the ServletContext object

Shared data (typically implemented later with session or request)
The data I save in this Servlet can be retrieved in another Servlet
HelloServlet

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //this.getInitParameter() Initialization parameter
        //This. GetServletConfig() Servlet Configuration
        //This. GetServletContext() Servlet context
        ServletContext context = this.getServletContext();

        String username = "Bicycle"; //data
        context.setAttribute("username",username); //Save a data in the ServletContext named username. Value username

    }

}

GetServlet

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("Name"+username);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml Mapping

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

ServletContext Application

Get initialization parameters (hardly necessary, just understand)

    <!--Configure some web Apply Initialization Parameters-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
}
 <servlet>
        <servlet-name>gp</servlet-name>
        <servlet-class>com.cheng.servlet.ServletDemo03</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>gp</servlet-name>
        <url-pattern>/gp</url-pattern>
    </servlet-mapping>

Request Forwarding (this is typically done with request)

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    System.out.println("Enter ServletDemo04");
    //RequestDispatcher requestDispatcher = context. GetRequestDispatcher ('/gp'); // Forwarded Request Path
    //requestDispatcher.forward(req,resp); // Call forward to implement request forwarding;
    context.getRequestDispatcher("/gp").forward(req,resp);
}

Read resource files (this can generally be done with class loading or reflection)

Properties

Create new properties in the java directory
Create new properties in the resources directory
Discovery: All packaged under the same path: classes, which we commonly call classpath:
Idea: A file stream is required

username=root12312
password=zxczxczxc
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user+":"+pwd);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

HttpServletResponse

The web server receives an http request from the client and, for this request, creates a HttpServletRequest object representing the request and a HttpServletResponse representing the response.

  • If you want to get the parameters requested by the client: Find HttpServletRequest
  • If you want to give the client some information to respond: Find HttpServletResponse

The method responsible for sending data to the browser:

servletOutputstream getOutputstream() throws IOException;

Printwriter getwriter() throws IOException;

Responsible for sending response headers to browsers:

void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String varl,long var2)
void addDateHeader(String var1,long var2)
void setHeader(String var1,String var2);
void addHeader(String var1,String var2);
void setIntHeader(String var1,int var2);
void addIntHeader(String varl,int var2);

Download Files

  1. To get the path to the downloaded file
  2. What is the downloaded file name?
  3. Set up ways for browsers to support downloading what we need
  4. Get the input stream of the downloaded file
  5. Create Buffers
  6. Get OutputStream object
  7. Write FileOutputStream stream to bufer buffer
  8. Use OutputStream to output data from the buffer to the client!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. To get the path to the downloaded file
    String realPath = "D:\Users\Administrator\IdeaProjects\kuangshen\javaweb-05-servlet\servlet3\src\img\Tianhong.jpg";
    System.out.println("Path to download file:"+realPath);
    // 2. What is the downloaded file name?
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 3. Set up ways for browsers to support (Content-Disposition) downloading what we need, the Chinese file name URLEncoder. Encoding, otherwise it may be garbled
    resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
    // 4. Get the input stream of the downloaded file
    FileInputStream in = new FileInputStream(realPath);
    // 5. Create Buffers
    int len = 0;
    byte[] buffer = new byte[1024];
    // 6. Get the OutputStream object
    ServletOutputStream out = resp.getOutputStream();
    // 7. Write the FileOutputStream stream to the buffer and use OutputStream to output the data in the buffer to the client!
    while ((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }

    in.close();
    out.close();
}

Authentication Code Function

How did verification come about?

  1. Front End Implementation
  2. Backend implementation, requires a Java picture class to generate a picture
public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //Let the browser refresh automatically in 3 seconds;
        resp.setHeader("refresh","3");

        //Create a picture in memory
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //Get pictures
        Graphics2D g = (Graphics2D) image.getGraphics(); //pen
        //Set the background color of the picture
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //Write data to pictures
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //Tell the browser that the request is opened as a picture
        resp.setContentType("image/jpeg");
        //Site has cache, browser does not cache
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //Write pictures to your browser
        ImageIO.write(image,"jpg", resp.getOutputStream());

    }

    //Generate Random Numbers
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Implement redirection

void sendRedirect(String var1) throws IOException;


The difference between redirection and request forwarding:
Same:

  • Pages will jump
    Difference:
  • The URL address bar does not change when a request is forwarded (status code 307)
  • The URL address bar changes when redirecting (302)

Common scenarios: user login
index.jsp

<html>
<body>
<h2>Hel1o World!</h2>
<%@ page contentType="text/html; charset=UTF-8"%>

<%--The overrun path here,Need to find a path to the project--%>
<%--${pageContext. request, contextPath}Represents the current project--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    User name: <input type="text" name="username"> <br>
    Password: <input type="password" name="password"> <br>
    <input type="submit">
</form>

</body>
</html>

Redirect.java

public class Redirect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //Processor's Request
    String username = req.getParameter( s: "username");
    String password  rea.getParameter( s: "password");

    System.out.println(username+":"+password);

    resp.sendRedirect(s: "/success.jsp");
	}
}

HttpServletRequest

HttpServletRequest represents the client's request. Users access the server through the Http protocol. All the information in the HTTP request is encapsulated into the HttpServletRequest. With this HttpServletRequest method, all the information of the client is obtained.


Get parameters, request forwarding

Example
index.jsp

<html>
<body>
<h2>Hel1o World!</h2>
<%@ page contentType="text/html; charset=UTF-8"%>

<%--Path submitted here,Need to find a path to the project--%>
<%--${pageContext. request, contextPath}Represents the current project--%>
<div style="text-align: center">
    <form action="${pageContext.request.contextPath}/login" method="post">
        User name: <input type="text" name="username"> <br>
        Password: <input type="password" name="password"> <br>
        Hobbies:
        <input type="checkbox" name="hobbys" value="girl">girl
        <input type="checkbox" name="hobbys" value="Code">Code
        <input type="checkbox" name="hobbys" value="ok">ok
        <br>
        <input type="submit">
    </form>

</div>
</body>
</html>
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");


        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        System.out.println("==========");
        //Chinese scrambling in background reception
        System. out.println(username);
        System. out.println(password);
        System.out.println(Arrays.toString(hobbys));
        System. out.println("============");
        System. out.println(req.getContextPath());
        //Forwarding by Request
        //Here / represents the current web application
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

Cookie s and Ession

Conversation

Conversation:
Users open a browser, click on many hyperlinks, access multiple web resources, and close the browser. This process can be called a session.

Stateful Sessions:
A classmate has come to the classroom. Next time he comes to the classroom, we will know that this classmate has been there, called stateful conversation.

How can you prove that you are a student in a training class?

You (Client), School (Server)

  • Invoice. School invoices you
  • School registration. The school marked that you were there

A website, how can I prove you've been there?

Client Server

  • The server sends a letter to the client, and the next time the client visits the service, he can bring the letter with him. Cookies
  • Server registered you, next time you come I will match you; Seeion

Two techniques for saving sessions:

  • cookie
    Client Technology (Response, Request)
  • session
    Server technology, which allows you to save user session information? We can put information or data in Session!

Common Scenarios: After you log in to the website, you don't need to log in next time. The second visit goes straight up!

Cookie

  1. Get cookie information from the request
  2. Server responds to client cookie s

common method

Cookie[] cookies = req.getCookies(); //Get Cookie s
cookie.getName(); //Get the key in the cookie
cookie.getValue(); //Get vlaue from cookie
new Cookie("xxx(name)", value); //Create a new cookie
cookie.setMaxAge(x); //Set cookie validity seconds
resp.addCookie(cookie); //Respond to a cookie for the client

Demonstration examples

public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Example: The server tells you when you're coming, encapsulates this time into a letter, and the next time you bring it, the server knows you're here

        //Solve Chinese garbles
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");

        PrintWriter out = resp.getWriter();

        // Cookies, obtained by the server from the client
        Cookie[] cookies = req.getCookies();    //This returns an array indicating that there may be multiple cookie s

        //Determine if a cookie exists
        if(cookies!=null){
            //If it exists
            out.write("Your last visit was:");
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastLoginTime")){
                    //Get the value in the cookie
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("This is your first visit to this site");

        }

        //The server responds to a cookie to the client
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        resp.addCookie(cookie);
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Delete Cookie Method:

Do not set validity period, close browser, invalidate automatically;
Set validity period to 0;

public class CookieDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // To create a cookie, the name must match the name you want to delete
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");

        //Set cookie validity period to 0 and expire immediately
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

If you want to set the cookie value in Chinese, encode and decode it

URLEncoder.encode("Hello","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
  • Cookies are typically stored in appdata in the local user directory;
  • A Cookie can only store one message;
  • A web site can send more than 20 cookie s to a browser.
  • Cookie size is limited to 4kb;
  • 300 cookie s are the browser limit

Session (Key)

What is Session:

  • The server creates a Session object for each user (browser);
  • A Session exclusively has a browser that exists as long as the browser is not closed;
  • After the user logs in, the whole site is accessible! -> Save user information; Save the shopping cart information...

Differences between Session and Cookie:

  • Cookie s are browsers that write the user's data to the user and save it (you can save more than one)
  • Session writes user data to user-exclusive Sessions, and server-side saves (saves important information, reduces waste of server resources)
  • Session objects are created by services;

Use scenarios:

  • Save the information of a logged-in user;
  • Shopping cart information;
  • Data that is often used throughout the Web site, and we keep it in Session;

Demonstration examples

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve garbled problems
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //Get session
        HttpSession session = req.getSession();

        //Store something in session
        session.setAttribute("name",new Person("Hello",1));
        //Get Session ID
        String sessionId = session.getId();

        //Determine if Session is newly created
        if (session.isNew()){
            resp.getWriter().write("session Created successfully,ID:"+sessionId);
        }else {
            resp.getWriter().write("session Already exists on the server,ID:"+sessionId);
        }

        //See what Session did when it was created;
        Cookie cookie1 = new Cookie("JSESSIONID",sessionId);
        resp.addCookie(cookie1);

        Cookie cookie2 = new Cookie("test",sessionId);
        resp.addCookie(cookie2);
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Manual session logoff

session.invalidate();

Session automatic expiration: web.xml configuration

<!--Set up Session Default Invalidation Time-->
<session-config>
    <!--15 Minutes later Session Automatic Invalidation in Minutes-->
    <session-timeout>15</session-timeout>
</session-config>

Compare ServletContext

JSP

Java Server Pages: Java server-side pages for dynamic Web technology, just like Servlet s!

The biggest features:
Writing JSP s is like writing HTML

Difference:
HTML only provides users with static data
Java code can be embedded in JSP pages to provide users with dynamic data;

JSP Principle

Browsers send requests to servers, no matter what resources they access, they are actually accessing Servlet s!

The JSP will eventually be converted to a Java class

JSP is essentially a Servlet

//Initialization
  public void _jspInit() {
      
  }
//Destroy
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response)

Some built-in objects

final javax.servlet.jsp.PageContext pageContext;  //Page Context
javax.servlet.http.HttpSession session = null;    //session
final javax.servlet.ServletContext application;   //applicationContext
final javax.servlet.ServletConfig config;         //config
javax.servlet.jsp.JspWriter out = null;           //out
final java.lang.Object page = this;               //page: current
HttpServletRequest request                        //request
HttpServletResponse response                      //response

Code added before the output page

response.setContentType("text/html");       //Set Page Type for Response
pageContext = _jspxFactory.getPageContext(this, request, response,
       null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;

These objects can be used directly in JSP pages

Schematic diagram

In the JSP page;
The output will remain intact as long as the JAVA code is present;
If it is HTML code, it will be converted to something like the following:

out.write("<html>\r\n");

This format, output to the front!

JSP Basic Syntax

Any language has its own grammar, as does Java. As an application of Java technology, JSP has its own extended grammar (just know it!). All Java grammars are supported!

JSP expression

  <%--JSP Expression
  Role: Used to output the program to the client
  <%= Variable or expression%> That is<%= %>It can be written directly inside java Code
  --%>
  <%= new java.util.Date()%>

JSP script fragment

  <%--jsp Script Fragment--%>
  <%
    int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>");
  %>

JSP declaration

  <%!
    static {
      System.out.println("Loading Servlet!");
    }

    private int globalVar = 0;

    public void method(){
      System.out.println("Enter Method method");
    }
  %>

JSP declaration: will be compiled into JSP generated Java class! Others will be generated to _ jspService method!

In JSP, just embed Java code!

<%%>
<%=%>
<%!%>

<%--Notes--%>

JSP comments will not be displayed on the client, HTML will

JSP Directive

<%@page args.... %>
<%-- For example: Customize error pages, different errors to go to different pages web.xml To configure --%>
<%@page errorPage="..." %>
<%@include file=""%>

<%--@include Will combine two pages into one--%>

<%@include file="common/header.jsp"%>
<h1>Page Body</h1>

<%@include file="common/footer.jsp"%>

<hr>


<%--jSP Label
    jsp:include: Stitching pages, essentially three
    --%>
<jsp:include page="/common/header.jsp"/>
<h1>Page Body</h1>
<jsp:include page="/common/footer.jsp"/>

Output:

9 large built-in objects

  • PageContext Stores
  • Request Stores
  • Response
  • Session Stores
  • Application [SerlvetContext] Stores things
  • config [SerlvetConfig]
  • out
  • page, don't know
  • exception
<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8"%>
<html>
<body>
<%--Built-in Objects--%>
<%
    pageContext.setAttribute("name1","1 Number"); //Saved data is only valid in one page (lowest scope) (disappears after forwarding)
    request.setAttribute("name2","2 Number"); //Saved data is valid only in one request, request forwarding carries this data
    session.setAttribute("name3","3 Number"); //Saved data only works in one session, from opening browser to closing browser
    application.setAttribute("name4","4 Number");  //Saved data is valid on the server, from opening the server to closing it (highest scope)

    //Or you can
//    PageContext. SetAttribute ("name1", "number 1", 3);
//    Follow session. SetAttribute ("name3", "No. 3"); equivalence

//    PAGE_SCOPE = 1;
//    REQUEST_SCOPE = 2;
//    SESSION_SCOPE = 3;
//    APPLICATION_SCOPE = 4;
%>
<%--The code in the script snippet is generated intact to.jsp.java--%>
<%--Requires that the code in this section conform to java Grammatical Correctness--%>
<%
    // Take it out of the pageContext and get it by looking for it
    // Scope from bottom to top: page < request < session < application
    // (From the lower level to the higher level, the higher level will be found with the higher level, even if the lower level is not needed, it will return to null if it is not found)
    // JVM: Parent Delegation Mechanism
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");// Non-existent
%>

<%--Use EL Expression ${ } output--%>
<h1>The output value is:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>

<h3>${name5}</h3>
<%--For nonexistent, use EL The expression will not output anything on the page and will be displayed on the page using null,Impact Experience--%>
<h3><%=name5%></h3>

</body>
</html>

<%
    pageContext.forward("/index.jsp");  // Page-level forwarding
    request.getRequestDispatcher("/index.jsp").forward(request,response);   // Background Level Transfer
%>

request:
When a client sends a request to a server, the data it generates will be useless if the user finishes reading it, for example, news or user finishes reading it.

session:
Clients send requests to servers that generate data that users can use up later, such as shopping carts;

application:
Clients send requests to the server, resulting data, one user is exhausted, other users may also use, such as: chat data;

JSP tags, JSTL tags, EL expressions

<!-- JSTL Expression Dependency -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard Label Library -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

EL expression: ${}

  • get data
  • Perform operations
  • Get Common Objects for web Development

JSP Tag Library

jsptag.jsp

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="cheng"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>
<%--
http://localhost:8080/jsptag.jsp?name=cheng&age=12
--%>

jsptag2.jsp

<%=request.getParameter("name")%>
<%=request.getParameter("age")%>

JSTL expression

The JSTL tag library is used to make up for HTML tags. It customizes many tags for us to use, and tags function like Java code.

JSTL Label Library Kinds:
Format Label
SQL Label
XML Tags
Core Tags (Mastery)

Steps for using JSTL tag library
Introduce the corresponding taglib (sometimes in Tomcat you also need to import JSTL packages, otherwise you will get an error: JSTL parsing error)
Use the method

<%--Introduce JSTL Core Label Library so that it can be used JSTL Core Tags--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


c:if

<form action="coreif.jsp" method="get">
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="Sign in">

<%--  Decide if you are logged in admin,Then log in successfully--%>

    <c:if test="${param.username=='admin'}" var="isAdmin">
        <c:out value="Welcome to Administrator!"/>
    </c:if>
    <%--Self-closing label--%>
    <c:out value="${isAdmin}"/>

</form>

c:choose and c:when

<%--Define a variable score,Value 85--%>
<c:set var="score" value="85"/>

<c:choose>
    <c:when test="${score>=90}">
        Your results are excellent
    </c:when>
    <c:when test="${score>=80}">
        Your results are average
    </c:when>
    <c:when test="${score>=70}">
        Your results are good
    </c:when>
    <c:when test="${score<=60}">
        You failed in the grade
    </c:when>
</c:choose>

c:forEach

<%

    ArrayList<String> people = new ArrayList<>();
    people.add(0,"Zhang San");
    people.add(1,"Li Si");
    people.add(2,"King Five");
    people.add(3,"Zhao Six");
    people.add(4,"Tien Six");
    request.setAttribute("list",people);
%>


<%--
var , Variables traversed each time
items, Objects to traverse
begin,   Where to start
end,     Where to go?
step,   step
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

Output:

Zhang San
Li Si
King Five
Zhao Six
Tien Six
---------
Li Si
King Five
Zhao Six

Keywords: Java http

Added by cyrixware on Tue, 15 Feb 2022 20:33:50 +0200