preface

Java Web refers to the Java language to solve the relevant Web domain technology sum, a Web application includes Web client and Web server two parts, namely based on B/S (browser/server) architecture of the application.

Both ends of a,

1.1 Web Client

A Web client usually refers to a browser on the user’s computer, such as Microsoft’s Internet Explorer or Firefox. The client does not need to develop any user interface, and the browser is used.

1.2 Web Server

A Web server is one or more computers that can run Web applications, usually the Web site address that we type in a browser, which is the address of the Web server. When the user enters a Web address in the browser’s address bar and presses enter, the request is sent to the Web server. Upon receiving the request, the server returns a response message to the user with the requested resources. The application of Java on the server side is very rich, such as servlets, JSPS, and third-party frameworks.

Second, the two stations

2.1 Static Website

The early Web applications were primarily static page browsing, or static websites. These sites are written in HTML and placed on a Web server. The user uses the browser to request the Web page on the server through HTTP. The Web server processes the received request and sends it to the client browser for display. The working principle is shown as follows:

2.2 Dynamic Website

The resources that users can access are no longer limited to static web pages stored on the server. More content needs to dynamically generate page information according to the user’s request, namely dynamic website. These sites are usually written in HTML and dynamic scripting languages such as JSP, ASP, or PHP, and the written programs are deployed to the Web server. The Web server processes the dynamic script code, converts it into HTML code that can be parsed by the browser, and finally returns it to the client browser for display to the user. The workflow is as follows:

Three, two structure

3.1 C/S structure

Special client software needs to be installed. As shown in the figure:

3.2 B/S structure

In B/S structure, the client does not need to develop any user interface, and unified Internet Explorer or Firefox and other browsers. The request is sent to the Web server through the Web browser, which processes the request and sends the result back to the client step by step, as shown in the figure.

Built-in objects

1. The Request object Request object is javax.mail. Servlet. HTTP. It the instance of the class. Represents the request object, which is used to accept the data transferred from the client to the server over THE HTTP connection. For example, data in a form, parameters after a web address, and so on. 2. The Response object Response object is javax.mail. Servlet. HTTP. HttpServletResponse class instances. Represents the response object and is used to send data to the client. 3. Out are Out object javax.mail. Servlet, JSP. The JspWriter instances of the class. Mainly used to output data to the client browser. 4. The session object session object is javax.mail servlet. HTTP. HttpSession class instances. It is used to maintain data that needs to be kept between the server and a client, such as the user's login information during the session. Session state maintenance is a problem that Web application developers must face. When the client closes all the pages of the site or closes the browser, the data stored in the session object is automatically cleared. Since THE Htp protocol is a stateless protocol and does not retain data between sessions, the session object extends the functionality of Htp. For example, after a user logs in to a website, the login information is temporarily saved in the session object. When different pages are opened, the login information can be shared. Once the user closes the browser or logs out, the login information stored in the session object will be cleared. 5. The Application the Application object is javax.mail servlet. The ServletContext class instances. Mainly used to save user information, code snippets of the running environment; It is a shared built-in object, that is, an Application object is shared by multiple users in a container, so its information is shared by all users. 6. The PageContext object PageContext object is javax.mail. Servlet. JSP. The PageContext instances of the class. It is used to manage web page properties, wrap page context for JSP pages, and manage access to named objects belonging to special visible parts of JSPS, which are created and initialized by the JSP container. 7. The Config object Config object is javax.mail. Servlet. The ServletConfig instances of the class. Is the snippet configuration object that represents the configuration of the Servlet. 8. Page (this) Page object is javax.mail servlet. JSP. The HttpJspPage instances of the class. Used to process JSP pages, this refers to the JSP page object itself, or the servlet object representing the compiled version, which is only legal within the scope of the JSP page. An Exception object is an instance of the Java.lang.Throwable class. You can only use the Exception object on this page if you specify isErrorPage= "true" in the PAGE directive of the JSP page.Copy the code

Four, JavaBean

4.1 Background of Javabeans

In the initial stage of JSP web page development, there is no framework and logic hierarchical concept. Java code needs to be embedded in the web page to deal with some business logic in JSP pages, such as string processing and database operation, and its development process is shown in the figure.

4.2 Functions of Javabeans

If you separate HTML from Java code, encapsulate the Java code as a class that handles some kind of business logic. This class is then invoked in a JSP page to reduce the coupling between HTML and Java code, simplify THE JSP page, and improve the reusability and flexibility of Java program code. This is separated from HTML code, and the class encapsulated in Java code is a JavaBean component. In Java Web development, this component can be used to complete the processing of business logic. The development mode of applying the combination of Javabeans and JSP is shown in the figure.

4.3 Application of Javabeans

Javabeans are reusable components written in the Java language that are widely used in many layers of a system, such as PO, VO, DTO, and POJO.

Five, the Servlet

Users access servlets by clicking on a link or by entering a URL directly into the browser’s address bar, and the Web server receives the request rather than passing it directly to the Servlet container. The Servlet container instantiates the Servlet, calling a specific method of the Servlet (service()) and generates a response. This response is returned by the Servlet container to the Web server, which wraps the response and sends it to the Web browser in the form of an HTTP response. The whole process is as follows:

How to let the server know you have come?

6.1 the Cookie technology

Cookie function: In popular culture is when a user through the HTTP protocol to access a server, the server will some Key/Value keys to return to the client browser, and add some constraints to the data, when the conditions meet the next time the user access to the server, the data was fully back to the server. This function is like when you go shopping in the supermarket, you get a gift card for the first time, this shopping card stores some of your personal information, the next time you come to the supermarket chain, the supermarket will recognize your gift card, the next time you shop directly. When the W3C designed cookies, they were actually designed to record the user’s path to a Web application over a period of time. Because HTTP is a stateless protocol, when a user access request after the end of the backend server will not be able to know the next time to visit or not last visited the user, the application in the design, we can easily think of access is the same man twice to visit with two different access for program design and performance are quite different. For example, if user-related data is frequently accessed over a short period of time, caching can greatly improve data access performance. This is where the Cookie is used. Since the request is made by the same client, each request will contain the information set by the server at the time of the first access, so that the server can divide the accessing users according to the Cookie value.

@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		Cookie[] cookies = request.getCookies();
		
		PrintWriter out = response.getWriter();
		
		if(cookies! =null){
			out.println("The last time I visited was:");
			for (Cookie cookie : cookies) {
				if("lastTime".equals(cookie.getName())){
					long lastTime = Long.parseLong(cookie.getValue());
					Date date = newDate(lastTime); out.println(date.toLocaleString()); }}}else{
			out.println("You're number one.");
		}
		
		Cookie cookie = new Cookie("lastTime", String.valueOf(System.currentTimeMillis()));
		// Set some information for the cookie
		//cookie.setMaxAge(500); / / the period of validity
		//cookie.setPath(uri);
		// The server sends a Cookie to the client
		response.addCookie(cookie);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

Decoding and encoding (nothing to do with cookies, just a way to solve garbled characters)

// Send Chinese to avoid garbled characters. You can code it
Cookie cookie = new Cookie("lastTime",URLEncoder.encode("It is"."utf-8"));
// Fetch the Cookie value, which needs decoding
URLDecoder.decode(cookie.getValue(),"utf-8");
Copy the code

6.2 the Session technology

Why do we need sessions?

You’ve already seen how cookies can enable a server programtrackingEach client accesses, but each time the client accesses, it must return these cookies. If there are many cookies, this will increase the amount of data transferred between the client and the server, and the Session is designed to solve this problem. The same client does not need to return all Cookie values each time it interacts with the server. Instead, it only needs to return an ID, which is unique to each client and is generated when the client first accesses the server. So each client has oneUnique ID, the client just returns the ID, which is usually NANEJSESIONIDA Cookie of.

A browser goes to the server to rent a house, and the server records the browser’s behavior and data, and then gives the browser a key to the room and then, every time, the browser can use its own key to open its own room, and use everything in the room. (Of course, you can’t open someone else’s room, and you can’t open it.)


Vii. Context

7.1 Origin of SeveletContext or ApplicationContext

Browsers want to exercise, happy mood. The server thought I can’t add a set of sports equipment to each of your rooms, how much pressure on my economy. The server thought about it and decided to build a public place, a stadium, where all browsers could use these shared resources.

@WebServlet("/SessionTest1")
public class SessionTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("Session ID is:");
		/ / get the Session
		HttpSession session = request.getSession();
		out.write(session.getId());
		session.setAttribute("name"."shang");
		// Set how long the current session ends, in seconds. If the value is set to zero or negative, the session will never time out. This parameter is used to set the current session time.
// session.setMaxInactiveInterval(1);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code
@WebServlet("/SessionTest2")
public class SessionTest2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		HttpSession session = request.getSession();
		// Remove session data
		session.removeAttribute("name");
		// Log out of the current session manually
		session.invalidate();
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

7.2 Servlet Context

Every Web application running in the Java Virtual Machine has a Servlet context associated with it. The Java Servlet API provides a ServletContext interface for representing context. This interface defines a set of methods that a Servlet can use to communicate with its Servlet container, for example, to get the MIME type of a file, forward a request, or write a log message to a log file. The ServletContext object is the root of a known path in the Web server. For example, the Servlet context is positioned at http://localhost:8080/ch02. All requests starting with the/CH02 request path (called the context path) are sent to the Web application associated with this ServletContext. For example, we often use http://localhost:8080/. All requests starting with the/request path (called the context path) are sent to the Web application associated with this ServletContext.

ServletContext: This is a concept from the Servlet specification. It is a combination of interfaces that servlets use to interact with containers.These methods make it easy for servlets to interact with their own containers. In an application (a JVM), there can be more than one servlet container, all of which share a single ServletContext.

Eight, two eras

8.1 Model1 era

The original JSP development pattern was Model 1: JSP+JavaBean

8.2 Model2 era

It evolved into a Model 2 pattern: JSP+Servlet+ Javabeans

Model 2 conforms to the MVC architecture pattern, which is model-view-controller.

  • The model represents the application’s data and the business rules used to control access and modify that data. It notifies the view when the model changes and provides the view with the ability to query the relevant state of the model. It also provides the controller with the ability to access application functions encapsulated within the model.
  • Views are used to organize the content of the model. It takes data from the model and specifies how that data should behave. The view is responsible for maintaining the consistency of data presentation as the model changes. The view also notifies the controller of the user’s request.
  • The controller defines the behavior of the application. It is responsible for interpreting user requests from the view and mapping those requests to corresponding behaviors, which the model is responsible for implementing. On a standalone GUI client, a user’s request might be a few mouse clicks or menu selections. In a Web application, they might take the form of HTTP requests from GET or POST clients. The behavior implemented by the model includes processing the business and modifying the state of the model. Based on the user request and the results of the model’s behavior, the controller selects a view as a response to the user request. As shown in the figure:

9. Upload and download files

9.1 Uploading files

  1. Import the jar packagecommons-io.jarcommons-fileupload.jar
  2. Forms must be markedenctype="multipart/form-data"
< % - ${pageContext. Request. ContextPath} : sure I release in the project on the server can also be accessed -- % ><form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">Upload user:<input type="text" name="username"><br/>
    <input type="file" name="file1"><br/>
    <input type="submit" value="Submit"> | <input type="reset" value="Reset">
  </form>
Copy the code
  1. The ServletFileUpload is responsible for processing the uploaded file data and packaging each input item in the form into a FileItem object. The DiskFileItemFactory object is required when the request is resolved using the ServletFileUpload object. So, we need to construct the DiskFileItemFactory() object before we parse it, The fileItemFactory property of a ServletFileUpload object is set through the object’s constructor or setFileItemFactory() method.
package com.shang.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class FileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Determine whether the uploaded form is a normal form or a file form
        if(! ServletFileUpload.isMultipartContent(request)){return;
        }
        You are advised to save the uploaded file in the WEB-INF directory, which is secure. Users cannot directly access the uploaded file
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if(! uploadFile.exists()){ uploadFile.mkdir(); }// Cache, temporary files
        // Temporary path. If the file exceeds the expected size, we will put it in a temporary file and automatically delete it after a few days, or remind the user to save it permanently
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
        File tmpFile = new File(tmpPath);
        if(! tmpFile.exists()){ tmpFile.mkdir(); }Request.getinputstream (); // You can use request.getinputStream () to get the original file. But we all recommend using the fileupload component of Apache, common-fileupload, which relies on the commons-io component:
        //1. Create a DiskFileItemFactory object to handle file upload path or size limit
        DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile);
        / / 2. Obtain ServletFileUpload
        ServletFileUpload upload = getServletFileUpload(factory);
        //3. Process the uploaded file
        String msg = null;
        try {
            msg = uploadParseRequest(upload, request, response, uploadPath);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        // The servlet requests to forward the message
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("info.jsp").forward(request, response);

    }

    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {}public  static DiskFileItemFactory getDiskFileItemFactory(File file){
        // Set a buffer through the factory. When the uploaded file is larger than the buffer, put it into a temporary file
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);// The buffer size is 1 MB
        factory.setRepository(file);// Temporary directory save directory, need a File
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Listen to the file upload progress
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead: size of the file that has been read
            //pContentLength: file size
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("Total size:"+pContentLength+"Uploaded:"+pBytesRead); }});// Handle garbled characters
        upload.setHeaderEncoding("UTF-8");
        // Set the maximum value for a single file
        upload.setFileSizeMax(1024 * 1024 * 10);
        // Set the total size of files that can be uploaded
        //1024 = 1kb * 1024 =1M * 10 =10M
        upload.setSizeMax(1024 * 1024 * 10);
        return upload;
    }

    public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest request,HttpServletResponse response,String uploadPath) throws FileUploadException, IOException {
        String msg = "";

        // Parse the front-end request and wrap it as a FileItem object
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            if(fileItem.isFormField()){ // Determine whether the uploaded file is a normal form or a form with files
                //getFiledName refers to the name of the front end form control
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8"); // Handle garbled characters
                System.out.println(name+":"+value);
            }else {// Verify that it is an upload file
                //======== Processing file ======
                String uploadFileName = fileItem.getName();
                System.out.println("Upload file name:"+uploadFileName);

                if(uploadFileName.trim().equals("")||uploadFileName==null) {continue;
                }
                // Get the file name /images/boy/cool.jpg
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // Get the suffix of the file
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                /* * If fileExtName is not what we want, return the file name, and tell the user that the file type is wrong
                System.out.println("File information [file name:"+fileName+"---- File Type"+fileExtName+"]");

                // You can use a UUID (a common code that is uniquely identified) to ensure that the file is unique
                //, UUID. RandomUUID (), which randomly generates a unique universal code
                String uuidPath = UUID.randomUUID().toString();

                //=========================== File processing is complete ========
                // Where should I deposit it? uploadPath
                // realPath of the file
                String realPath = uploadPath +"/"+uuidPath;
                // Create a folder for each file
                File realPathFile = new File(realPath);
                if(! realPathFile.exists()){ realPathFile.mkdir(); }// The address is stored

                //======= File transfer =====
                // Get the file stream
                InputStream inputStream = fileItem.getInputStream();
                // Create a file output stream
                //realPath Specifies the real folder
                // One file is missing; Add the output name +"/"+uuidFileName
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                // Check whether the read is complete
                int len = 0;
                // Create a buffer
                byte[] buffer = new byte[1024*1024];
                // If the value is not -1, data still exists
                while((len = buffer.length)! = -1){
                    fos.write(buffer, 0, len);
                }

                / / close the flow
                fos.close();
                inputStream.close();
                msg = "File uploaded successfully!";
                fileItem.delete();// The temporary file is cleared}}returnmsg; }}Copy the code

9.2 Downloading files

public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Obtain the path for downloading the file
        //String path = this.getServletContext().getRealPath("/1.jpg");
        String path = "G:\\MyIDEProject\\JavaWeb\\UploadFile\\resources\\1.jpg";
        System.out.println("File path to download"+path);
        //2. File name to download
        String filename = path.substring(path.lastIndexOf("\ \") + 1);
        //3. Set the browser to support what we want to download
        response.setHeader("Content-Disposition"."attachment; filename="+filename);
        //4. Obtain the input stream of the downloaded file
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        //5. Create a buffer
        byte[] buffer = new byte[1024];
        int len = 0;
        //6. Get the OutputStream object
        ServletOutputStream fos = response.getOutputStream();
        //7. Write the FileOutputStream to the buffer
        while((len = buffer.length)! = -1) {//8. Use OutputStream to input data from the buffer to the client
            fos.write(buffer, 0, len);
        }
        / / 9. Close the flowfos.close(); fis.close(); }}Copy the code