Java Web Learning Notes

Servlet

1, Differences between C/S and B/S architectures

C/S architecture (client / server)

  • Features: specific software must be installed on the client
  • Advantages: good graphic effect
  • Disadvantages: the software and functions of the server must be upgraded, and the client must also be upgraded, which is not conducive to maintenance
  • Common C/S architecture: QQ wechat

B/S architecture (Browser / server)

  • Features: without installing the client, any browser can directly access it
  • Advantages: when it comes to function upgrading, you only need to upgrade the server side
  • Disadvantages: the graphic display effect is not as good as C/S architecture
  • It needs to be accessed through HTTP protocol

2, Software configuration

(1)Tomcat

1.1 verify that Tomcat is installed successfully

  1. Enter the Tomcat installation directory bin, double-click startup.bat to start the program, and xx milliseconds will appear in the last line
  2. Open the browser and enter localhost:8080 to see the Tomcat page
  3. Under the installation directory bin, double-click shutdown.bat to close the Tomcat program

2.1 project deployment and access to static resources

Tomcat is a Web server. Our project application is deployed under webapps and accessed through a specific URL

2.1 create project
  1. Create a folder in the Tomcat installation directory webapps, such as myweb

  2. In the myweb folder, create a WEB-INF folder to store the core content of the project

  • Create a classes folder to store. class files
  • Create a lib folder to store jar files
  • Create web.xml and project configuration file (copy to WEB-INF under ROOT project)
  1. Copy the web page hello.html to the myweb folder and put it in the same level directory as WEB-INF
2.2 URL access resources

Start Tomcat and enter localhost:8080/myweb/hello.html

(2)Servlet

2.1 Servlet function

  • Receive the client request and complete the operation
  • Dynamically generate web pages (variable page data)
  • Respond the dynamic web page containing the operation results to the client

2.2 Servlet development steps

2.2.1 build development environment

Configure the Servlet related jar package (LIB \ Servlet API. Jar) under the tomcat path into the classpath,

This computer - advanced system settings - environment variable - classpath - add D:\Tomcat\apache-tomcat-9.0.20\lib\servlet-api.jar

2.2.2 writing servlets
  • Implement javax.servlet.Servlet
  • Rewrite five main methods
  • Write the output statement in the core service() method and print the access result
//Name the file MyServlet.java
import java.io.IOException;
import javax.servlet.*;
public class MyServlet implements Servlet {
    public void init(ServletConfig servletConfig) throws ServletException {
    }
    public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{
		System.out.println("My First Servlet");	
    }
	public void destroy(){	 
    }
	public ServletConfig getServletConfig(){	
		return null;
	}
	public String getServletInfo(){
		return null;
    }
}
2.2.3 deploying servlets

cmd command: javac MyServlet.java, and put the generated class file in the WEB-INF/classes file

2.2.4 configuring servlets

Write the project configuration file web.xml under WEB-INF

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

 <!-- to configure Servlet information -->
<servlet>
	<!-- to configure Servlet Name, name must be unique -->
	<servlet-name>my</servlet-name>
	<!-- to configure Servlet Full path (package name)+Class name) -->
	<servlet-class>MyServlet</servlet-class>
</servlet>
		
<!-- to configure Servlet Mapping (access path) -->
<servlet-mapping>
	<!-- to configure Servlet The name must be the same as above -->
	<servlet-name>my</servlet-name>
	<!-- Configure virtual path (access path) -->
	<url-pattern>/myservlet</url-pattern>
</servlet-mapping>


</web-app>

2.2.5 operation test

Start Tomcat, enter localhost:8080/myweb/myservlet in the browser address to access, and print My First Servlet in cmd to indicate success

(3) Create a web project using IDEA

3.1 creating a web project

First create a normal java project, then right-click the project name - Add FrameWork Support - select Web Application, and check create web xml java ee 7

3.2 IDEA development Servlet

Right click the WEB-INF to create a DIRECTORY lib folder, then import the servlet-api.jar package, copy it to the Lib folder, and right click add as library

3.3 writing servlets

For src, create package, com.tang.servlet, create a new class file named MyServlet, and add the following code

package com.tang.servlet;

import javax.servlet.*;
import java.io.IOException;

public class MyServlet implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("My First Web Project");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

3.4 configuring web.xml

Add the following code
    <!-- to configure Servlet information -->
    <servlet>
        <!-- to configure Servlet Name, name must be unique -->
        <servlet-name>my</servlet-name>
        <!-- to configure Servlet Full path (package name)+Class name) -->
        <servlet-class>com.tang.servlet.MyServlet</servlet-class>
    </servlet>

    <!-- to configure Servlet Mapping (access path) -->
    <servlet-mapping>
        <!-- to configure Servlet The name must be the same as above -->
        <servlet-name>my</servlet-name>
        <!-- Configure virtual path (access path) -->
        <url-pattern>/myservlet</url-pattern>
    </servlet-mapping>

3.5 IDEA integration Tomcat

IDEA, file settings in the upper left corner - Build Execution Deployment on the left, find Application Servers, click the plus sign, add Tomcat Server, select the tomcat directory, click OK, click Apply, and click OK

Add configuration in the upper right corner, click the plus sign to find tomcat server, click local, find Deployment, click the plus sign and Arifact. Click OK to start tomcat

Enter localhost: 8080 / myservlet from the browser_ war_ Expanded / myservlet idea console outputs My First Web Project successfully!

3.6 how to export war package (after the project is completed)

File project setting in the upper left corner of the IDEA - Artifact on the left, click the plus sign, Web Application Archive - select for webproject war expanded, and a non expanded one appears, click apply and click ok

Above the IDEA, build build artifact - select the war package, click build, and then in the idea out, find the war package in artifacts, copy it to the Tomcat webapps folder and paste it

Then start the bat file of tomcat and enter it in the browser http://localhost:8080/WebProject_war/myservlet, you will see the output in cmd, indicating success

3, Servlet details

3.1 three creation methods

3.1.1 implementation interface

Five methods

package com.tang.servlet;

import javax.servlet.*;
import java.io.IOException;

public class MyServlet implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("My First Web Project");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

3.1.2 GenericServlet without http protocol

Just rewrite the abstract service method

package com.tang.servlet;

import javax.servlet.*;
import java.io.IOException;

public class GenServlet extends GenericServlet{
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hey, hey, hey");
    }
}
 <!-- to configure Servlet information -->
    <servlet>
        <!-- to configure Servlet Name, name must be unique -->
        <servlet-name>gs</servlet-name>
        <!-- to configure Servlet Full path (package name)+Class name) -->
        <servlet-class>com.tang.servlet.GenServlet</servlet-class>
    </servlet>

    <!-- to configure Servlet Mapping (access path) -->
    <servlet-mapping>
        <!-- to configure Servlet The name must be the same as above -->
        <servlet-name>gs</servlet-name>
        <!-- Configure virtual path (access path) -->
        <url-pattern>/gs</url-pattern>
    </servlet-mapping>

3.1.3 httpservlet (recommended)

To further extend on the basis of inheriting GenericServlet, you must override a method. doGet doPost doPut doDelete

package com.tang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is get Asked to come");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is post Asked to come");
    }
}

  <!-- to configure Servlet information -->
    <servlet>
        <!-- to configure Servlet Name, name must be unique -->
        <servlet-name>hs</servlet-name>
        <!-- to configure Servlet Full path (package name)+Class name) -->
        <servlet-class>com.tang.servlet.HttpsServlet</servlet-class>
    </servlet>

    <!-- to configure Servlet Mapping (access path) -->
    <servlet-mapping>
        <!-- to configure Servlet The name must be the same as above -->
        <servlet-name>hs</servlet-name>
        <!-- Configure virtual path (access path) -->
        <url-pattern>/hs</url-pattern>
    </servlet-mapping>

3.2 two configuration modes

3.2.1 web.xml (general method before servlet 2.5)

Exact match/Specific nameThe servlet is triggered only if the url path is a concrete name
Suffix matching*.xxxAs long as it is connected with xxx, the servlet will be triggered
Wildcard matching/*Match all requests, including all resources of the server
Wildcard matching/Match all requests, including all resources of the server, excluding jsp

Load on startup indicates the loading sequence. Starting from 0, the smaller the value, the first to be loaded. If it is not set, it will be loaded when accessing

3.2.2 using annotations (recommended after servlet 3.0)

nameservlet name, optional
valueYou can configure multiple url paths
urlPatternsConfigure the url path, which is the same as value. It cannot be used at the same time
loadOnstartupWhen configuring servlet creation, the smaller the value, the higher the priority
package com.tang.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value ={"/bs","/bss"},loadOnStartup = 0)
public class BasicServlet extends HttpsServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is get");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is post");
    }
}

4, request object

4.1 difference between get and post

get requestpost request
The data submitted by get will be placed after the url in the form of "get"? Separate url and transmission data, and connect parameters with &The post method is to put the submitted data into the body of the http package
get mode is transmitted in clear text, with small amount of data and unsafeCiphertext transmits data, which is large and safe
High efficiency. The default request mode of the browser is get requestThe efficiency is not so high
The corresponding Servlet method is doGetThe corresponding Servlet method is doPost

4.2 get and post applications (send data and solve coding)

//The java project project name is MyServlet
//Facing the web, right-click to create a new html file, register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration page</title>
</head>
<body>
<form action="/MyServlet_war_exploded/rs" method="post">

    user name:<input type="text" name="username"/> <br/>
    password:<input type="password" name="password"/> <br/>
    <input type="submit" value="register"/>
    </form>
</body>
</html>
//Under src package, create a new class file, RegisterServlet.class
package com.tang.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/rs")
public class RegisterServlet extends HttpsServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String username=req.getParameter("username");
       String password=req.getParameter("password");
        System.out.println("Data submitted:"+username+"\t"+password);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set a unified code for the request object
        req.setCharacterEncoding("utf-8");
        //Get the data requested by the user
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        System.out.println("Data submitted:"+username+"\t"+password);

      
        resp.setCharacterEncoding("utf-8"); // Specifies the encoding format to be output to the client, and the computer will display??
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter printWriter= resp.getWriter();
        printWriter.println("Registration succeeded!");
    }
}
//http://localhost:8080/MyServlet_ war_ Expanded / register.html test

4.3 forwarding and redirection

4.3.1 the forwarded page jumps to req.getRequestDispatcher

The server jumps internally, the url address does not change, and the request can only be forwarded to components in the same web application

When the business logic is separated from the display result, you need to jump to the Servlet that displays the result, and you need to jump to the page

req.getRequestDispatcher("/b").forward(req,resp); Jump from a to B

4.3.2 forwarding data transfer req.setAttribute

How to transfer the data results obtained by the business logic to the Servlet displaying the results to cooperate with the page Jump

In a, req.setAttribute("username", "gavin"); Save data

req.getRequestDispatcher("/b").forward(req,resp); Forward to B

In b, String s=(String)req.getAttribute("username"); Fetch data

4.3.3 redirect page to resp.sendRedirect

Resources that can point to other sites

resp.sendRedirect("/MyServlet_war_exploded/b")

When jumping, the address bar changes, indicating that the request is sent twice, the response has no scope, and the data in the two request requests cannot be shared

4.3.4 redirected data transmission (only string type can be transmitted, plaintext transmission and splicing are required)

resp.sendRedirect("/MyServlet_war_exploded/b?username=tom") ; Transfer data

String username=req.getParameter(“username”); Fetch data

4.3 lifecycle and thread safety

4.3.1 four stages

instantiation load-on-startupSet the number to execute once
initializationinit()Execute once
serviceservice()Execute multiple times
Destroydestroy()Execute once

4.3.2 thread safety

synchronized is not recommended. Locking efficiency is low

Implementation of singlethreadmodel interface is outdated

Use local variables in doget dopost as much as possible (recommended)

5, State management

Existing problemshttp protocol cannot save the information submitted each time. If a user sends a new request, the server cannot know whether he is connected with the last request. For web operations that require multiple data submissions, such as login, it becomes a problem
State managementThe multiple interactions between the browser and the web server are treated as a whole, and the data involved in the multiple interactions are saved
Client state management technologySave the state to the client, typically Cookie technology
Server state management technologySave the state to the server, typically Session technology

5.1 Cookie

It is mainly composed of the name and value identifying the information

View cookies: 360 browser, settings - Advanced Settings - Web content advanced settings - all cookies and website data - enter localhost

5.1.1 setting cookie access path and validity period

 //1. The server creates a cookie object
Cookie cookie=new Cookie("username","gavin");
Cookie cookie2=new Cookie("password","123456");
 //1.1 set cookie access path
cookie.setPath("MyServlet_war_exploded/get");
cookie.setPath("MyServlet_war_exploded");
//1.2 set the cookie life cycle. There are three values, > 0, the validity period is in seconds, = 0, the browser is closed, and < 0, the browser memory is temporarily stored
cookie.setMaxAge(60*60);
cookie2.setMaxAge(60*60);
//2. Respond the cookie to the client
resp.addCookie(cookie);
resp.addCookie(cookie2);

5.1.2 loop traversal to obtain cookie s

 //1 get all cookie s through the request object
Cookie[] cookies=req.getCookies();
//2 iterate through cookie s
 if (cookies!=null){
     for (Cookie cookie:cookies) {
        System.out.println(cookie.getName()+":"+cookie.getValue());
     }
   }

5.1.3 cookie modification

You only need to ensure that the name and path of the cookie are consistent. The principle is to replace the original cookie

//Create a new cookie class. The path name is the same as before, and the previous cookie will be automatically replaced
Cookie cookie=new Cookie("username","gavin");
cookie.setPath("MyServlet_war_exploded/get");  

5.1.4 cookie encoding and decoding

Cookies do not support Chinese by default, so they need to be encoded

import java.net.*;
//When creating an object, the code is created directly
Cookie cookie=new Cookie(URLEncoder.encode("full name","UTF-8"),URLEncoder.encode("Zhang San","UTF-8"));
//Decode, iterate through the loop, get the cookie, and change foreach to output this
System.out.println(URLDecoder.decode(cookie.getName(),"UTF-8")+":"+URLDecoder.decode(cookie.getValue(),"UTF-8"));
           

5.2 Session

Session is used to record the status of users. Session refers to a series of related interaction processes between a single client and the Web server over a period of time

The session is created by the server. The server will allocate a session object for each session. When a session is used for the first time, the server will automatically create a session and create a Cookie to store the Session id and send it back to the client

5.2.1 basic operation

  //1 get the Session object through the request object
HttpSession session= req.getSession();
System.out.println(session.getId());

//2.session save data
session.setAttribute("key",value);  //Stored in the session scope as key value pairs

//3.session get data
session.getAttribute("key");  //Access the value of Object type through the key of String type

//4.session remove data
session.removeAttribute("key");  //Remove the value from the session scope with the key

//5. Life cycle
//5.1 when the browser is closed, it ends
//5.2 set the session life cycle to 10 seconds, and the session will end if it times out
 session.setMaxInactiveInterval(10);
//5.3 manual destruction ends
 session.invalidate();

5.2.2 disable cookie s in the browser (not recommended, later use EL expression)

By default, the server will send the session ID to the browser by cookie. If the user prohibits cookies, the session ID will not be saved by the browser. At this time, the server can send the session ID by URL rewriting, that is, adding the session ID after it

//Splice the session id first, and then jump the page to ensure that the page jumps twice, or the same session
String newUrl= resp.encodeRedirectURL("/MyServlet_war_exploded/gets");
resp.sendRedirect(newUrl);

5.3 ServletContext

  • The global object also has a scope, corresponding to a Web application in Tomcat
  • When the web server starts, a shared storage area is created for each web application
  • ServletContext is created when the web server starts and destroyed when it closes

5.3.1 obtaining ServletContext object

  		 //1 through this.getServletContext()
        ServletContext servletContext1=this.getServletContext();
        //2 get through the request object
        ServletContext servletContext2=req.getServletContext();
        //3 get through the session object
        HttpSession session= req.getSession();
        ServletContext servletContext3=session.getServletContext();

5.3.2 role of ServletContext

 //Get the real path of the current project published on the server
 System.out.println(servletContext1.getRealPath("/"));
 
 //Get the context path of the project. The two sentences are the same
  System.out.println(servletContext2.getContextPath());
	System.out.println(req.getContextPath()); //Like the two sentences, output / MyServlet_war_exploded

	//Global container
	servletContext1.setAttribute("name",value);  //Store data
        servletContext1.getAttribute("name");   //get data
        servletContext1.removeAttribute("name");   //Remove data

5.3.3 scope summary

  • HttpServletRequest: a request that is valid before the request response
  • HttpSession: valid until a session starts and the browser does not close or time out
  • ServletContext: the server starts and is valid until the server stops

6, Filter

The Filter execution status is before the Servlet. When the client sends a request, it will first pass through the Filter and then reach the target Servlet; when responding, it will execute the Filter in reverse again according to the execution process.

The Servlet API provides a Filter interface. Developers can write a Java class to implement this interface. This class is called Filter

Import package: import javax.servlet. *;

6.1 basic realization of filter

//filter
package com.tang.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(value = "/t")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("---MyFilter---");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("---End---");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
======================================================================================
   //Target Servlet
    package com.tang.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/t")
public class TargetServlet extends HttpsServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("---target---");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
=====================================================================================
   The output execution result shows the execution order from the client to the filter reach Servlet,Return again filter,Then return to the client
---MyFilter---
---target---
---End---

6.2 two configuration modes

6.2.1 annotation configuration

@WebFilter(value = "/ filter target resource")

6.2.2 xml configuration

<filter>
    <filter-name>xml</filter-name>
    <filter-class>
            com.tang.servlet.XmlFilter
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>xml</filter-name>
    <url-pattern>/t</url-pattern>
  </filter-mapping>

6.3 filter priority

In a Web application, you can develop and write multiple filters, which are combined to be called a filter chain

Priority:

  1. If it is an annotation, it is sorted alphabetically
  2. If web.xml, it is in top-down order
  3. web.xml configuration is higher than annotation mode
  4. If the annotation and web.xml are configured at the same time, multiple filter objects will be created, resulting in multiple filtering

6.4 configure interception path

Exact intercept match: / index.jsp

Suffix interception match: *. jpg

Wildcard intercept match:/*

6.5 typical application of filter garbled code processing

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login page</title>
</head>
<body>
    <form action="/MyServlet_war_exploded/login" method="post">
        user name:<input type="text" name="username"/><br/>
        password:<input type="password" name="password"><br/>
        <input type="submit" value="Sign in"/>
    </form>
</body>
</html>
//Writing servlets
package com.tang.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/login")
public class LoginServlet extends HttpsServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username= req.getParameter("username");
        String password= req.getParameter("password");
        System.out.println(username+"\t"+password);
    }

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

//filter
package com.tang.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(value = "/login")
public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Uniformly handle the garbled code of request and response
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;charset=UTF-8");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

JSP

The function is to replace the Servlet that displays part of the page

1, JSP development

1.1 create JSP

  1. First, create a common Java project named Web_JSP, right-click the project name - Add FrameWork Support - select Web Application, and check create web xml
  2. Right click the WEB-INF to create a DIRECTORY lib folder, then import the servlet-api.jar package, copy it to the Lib folder, and right click add as library
  3. (optional) IDEA integrates Tomcat. File settings in the upper left corner - Build Execution Deployment on the left find Application Servers, click the plus sign, add Tomcat Server, select the directory of tomcat, click OK, click Apply, and click OK
  4. Add configuration in the upper right corner, click the plus sign to find tomcat server, click local, find Deployment, click the plus sign and Arifact. Click OK,
  5. Change the url and context of the web page to web page_ jsp,,
  6. on update action=redeploy,,, on frame deactivation=update classes and resources
  7. Right click on the web to create a new JSP file, and then write the following code. The web page can be refreshed directly. Visit http://localhost:8080/web_jsp/first.jsp
  8. The following code prints the current time of the system
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    Now:<%=new java.util.Date() %>
</body>
</html>

1.2 implementation principle

Tomcat converts. jsp into Java code, then compiles it into. class file for operation, and finally responds to the client through response

2, Integrated development of JSP and HTML

2.1 script

Scripts can write Java statements, variables, methods, or expressions

2.1.1 common script

Syntax: <% java code% >

Normal scripts can use java syntax, except for defining functions

Scripts cannot be nested between scripts, and scripts and HTML tags cannot be nested


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Use of scripts</title>
</head>
<body>
    <%
        int a=10;
        System.out.println(a); //Output in console
        out.println(a);//Output on page
    %>
</body>
</html>

2.1.2 declaration script

Syntax: <%! Define variables and functions% >

The variables declared by the declaration script are global variables

The contents of the declaration script must be invoked in the normal script%% >.

If the function in the declaration script has a return value, use the output script to call <% =% >

2.1.2 output script

Syntax: <% = Java expression% >

The output script can output a function with a return value

Output script cannot be added; semicolon

2.2 JSP comments

Main functions: annotate script code and html content

grammardescribe
<% -- JSP comment --% >JSP annotation content, which will not be sent to the browser or even compiled
HTML comment, you can see the comment content when viewing the web page source code through the browser

2.3 JSP instruction

JSP instructions are used to set attributes related to the entire JSP page

instructionsdescribe
<%@ page %>Define the dependent properties of the page
<%@ include %>Include other files
<%@ taglib %>The definition of the imported label library can be a custom label

2.3.1 Page instruction

The page instruction provides instructions for the container to use the current page. A JSP page can contain multiple page instructions

attributedescribe
errorPageSpecify the error handling page to turn to when an exception occurs on the jsp page
isErrorPageSpecifies whether the current page can be used as an error handling page for another jsp page
pageEncodingSpecifies the decoding format of the jsp page

2.3.2 include instruction

With this instruction, other jsp pages are included

There may be conflicts of duplicate names, which is not recommended

2.3.3 taglib instruction

Standard tag library of jsp

2.4 action label

The action tag refers to the command of the jsp page at run time

2.4.1 include (recommended)

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

The include instruction copies the output code of the external file into the current JSP file. Unlike the jsp: include action here, it imports the output result of the external file into the current JSP file

2.4.2 useBean setProperty getProperty(JavaBean)

	<jsp:useBean id="user" class="com.tang.entity.User" />
	Used to load a JSP Used in the page JavaBean
    <jsp:setProperty name="user" property="name" value="gavin" />
	Assign attributes
    <jsp:getProperty name="user" property="name"/>
	Extract assignment Bean Property, convert it into a string, and then output it to the page

2.4.3 forward param

<jsp:forward page="index.jsp" />
Transfer the request to another page
param Get parameters

2.5 built in objects

2.5.1 four domain objects

JSP has four scope objects. The way to store data is the same as to obtain data. The difference is that the range of values is different

  • pageContext: current JSP page scope
  • Request: a valid request
  • Session: one session is valid, and the browser is invalid when it is closed
  • Application: the whole web application is valid, and the server restart or shutdown fails
 <%
        pageContext.setAttribute("name",value);//The current page scope is valid
    %>

2.5.2 pageContext obtaining other built-in objects

 <%
        pageContext.getRequest();//Return Request built-in object
        pageContext.getResponse();//Return Response built-in object
        pageContext.getSession();//Return Session built-in object
        pageContext.getServletContext();
        pageContext.getOut();
        pageContext.getException();
        pageContext.getPage();
        pageContext.getServletConfig();
    %>

2.5.3 pageContext operation scope of other built-in objects

<%
    pageContext.setAttribute("page","123");//The current jsp is valid
    pageContext.setAttribute("req","aaa",PageContext.REQUEST_SCOPE);
    pageContext.setAttribute("sess","bbb",PageContext.SESSION_SCOPE);
    pageContext.setAttribute("app","ccc",PageContext.APPLICATION_SCOPE);

    String req=(String) request.getAttribute("req");
    String sess=(String) session.getAttribute("sess");
    String app=(String) application.getAttribute("app");

%>
   request:<%=req%>
    session:<%=sess%>
    application:<%=app%>

3, EL expression

EL makes JSP easier to write. It is mainly used to obtain data in the scope and replace the scope object. getAttribute("name")

3.1 scope basic operations

The difference between EL and script is that EL returns null and script returns null

<%
   request.setAttribute("key1","value1");//The current jsp is valid
    session.setAttribute("key2","value2");
    application.setAttribute("key3","value3");
%>

    <h1>Get from scope object:</h1>
<%--Get data from scope object--%>                      //The difference between EL and script is that EL returns null and script returns null
   <%=request.getAttribute("key1")%>
    <%=request.getAttribute("key1")%>
    <%=request.getAttribute("key1")%>
    <hr/>
<%--adopt EL There are two ways to obtain data by expression:--%>
<h1>adopt EL Expression get:</h1>
    ${requestScope.key1}
    ${sessionScope.key2}
    ${applicationScope.key3}
<hr/>
	${key1}
	${key2}
	${key3}  <%--This abbreviation needs to be distinguished key In different cases, if key Same corresponding value Different, not suitable--%>

3.2 operating common objects

${user.username}
${user.password}

3.3 operation array, collection object

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL Operation array, collection element</title>
</head>
<body>
<%
    int[] array=new int[]{1,2,3,4,5};
    request.setAttribute("array",array);

    List<String> nums=new ArrayList<>();
    nums.add("A");
    nums.add("B");
    nums.add("C");
    request.setAttribute("nums",nums);

    Map<String,String> maps=new HashMap<>();
    maps.put("CN","China");
    maps.put("US","U.S.A");
    maps.put("IT","Italy");
    request.setAttribute("maps",maps);
%>

${array[1]}
${array[2]}
${array[3]}

${nums[0]}
${nums[1]}
${nums.get(2)}

${maps["CN"]}
${maps.IT}



</body>
</html>

3.4 EL built-in objects

${pageContext.request.contextPath}  Get application context
${cookie.username.value}   get username
${cookie.password.value}   get password

4, JSTL standard tag library

Is a set of JSP tags, which can logically operate the data obtained by EL and cooperate with EL to display the data

4.1 preparation of JSTL

  1. Copy standard.jar and jstl.jar to / WEB-INF/lib
  2. Introduce tag library <% @ taglib URI in JSP page=“ http://java.sun.com/jsp/jstl/core ” prefix=“c” %>

4.2 core labels

4.2.1 if condition judgment

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    request.setAttribute("username","tom");
  %>

<c:if test="${username eq 'tom'}">
  <h1>Welcome, ${username} </h1>
</c:if>

  <c:if test="${username ne 'tom'}">
    <h1>Please log in again </h1>
  </c:if>
</body>
</html>

4.2.2 choose multi condition judgment

Equivalent to if else structure

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    request.setAttribute("age",38);
  %>

<c:choose>
  <c:when test="${age<18}"> juvenile </c:when>
  <c:when test="${age>=18&&age<30}"> youth </c:when>
  <c:when test="${age>=30&&age<50}"> middle age </c:when>
  <c:otherwise>old age</c:otherwise>
</c:choose>

</body>
</html>

4.2.3 iterative foreach label

<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    List<String> list=new ArrayList<>();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    request.setAttribute("list",list);
  %>

<c:forEach var="s" items="${list}" begin="0" end="3" step="1">
  ${s}
</c:forEach>



</body>
</html>

4.2.4 rewrite URL

When the cookie is disabled, the id value is passed by rewriting the URL to splice the session id, so that the previous Session object can still be found in the next visit. All page jumps or redirect jumps should be rewritten by URL

<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    
  <c:url context="${pageContext.request.contextPath}" value="/jstl/jstl1.jsp">
  </c:url>
  <a href="<c:url context="${pageContext.request.contextPath}" value="/jstl/jstl1.jsp">">Jump</a>

</body>
</html>

5, MVC framework

5.1 concept

MVC, also known as programming mode, is a software design idea. It divides data operation, page display and business logic into three modules, which are completed independently and called each other.

view, which is the interface that users see and interact with, such as html

The controller is the processing logic of the control request, receives the information sent by the view, processes the request, and is responsible for the process jump

The Model layer, Model, is service+dao+entity

5.2 advantages

Low coupling: the direct correlation between modules is not strong, and there is no inseparable correlation with a specific implementation

High maintainability: Based on low coupling, functional modules at different levels can be replaced flexibly

High reusability: the same database operation can serve different business processes, and take the data as an independent module to improve reusability

5.3 three tier architecture and MVC

Three tier architecture: view service dao

MVC is a framework, and architecture is under the framework

MVC emphasizes the separation of view and business. View is only responsible for data display, while data is encapsulated into model, and controller is responsible for transmission between V and M.

Three tier architecture refers to the decoupling between codes, which is convenient for maintenance and reuse

Tags: Java

Posted on Sun, 26 Sep 2021 23:41:38 -0400 by Optimo