【Java learning summary】JavaWeb

I. Overview

  1. Static web: The data provided to everyone will never change. (html, css)
  2. Dynamic web: The data provided to everyone will always change. Everyone sees different information at different times and in different places!
  3. In Java, technologies for dynamic web resource development are collectively referred to as JavaWeb.

Disadvantages of static web:

  • Web pages cannot be updated dynamically, and all users see the same page.
  • It cannot interact with the database.

Dynamic web disadvantages:

  • There is an error in the dynamic web resource added to the server, we need to rewrite our background program and republish.

Dynamic web advantages:

  • Web pages can be updated dynamically, and all users see different pages.
  • It can interact with the database.

Two, http

1. what is http

HTTP stands for Hyper Text Transfer Protocol (Hypertext Transfer Protocol), which is a simple request-response protocol, which usually runs on top of TCP.

2. http request

The client sends a request to the server (Request)

  1. request line

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

Request method: Get, Post, HEAD, DELETE, PUT, TRACT

The difference between get and post request methods:

  • get: The request can carry relatively few parameters, the size is limited, and the data content will be displayed in the URL address bar of the browser, which is not safe but efficient
  • post: There is no limit to the parameters that the request can carry, and there is no limit to the size. The data content will not be displayed in the URL address bar of the browser. It is safe but not efficient
  1. header

Accept: Tell the browser the data type 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 Browser, whether to disconnect or keep the connection after the request is completed
HOST: host.../.

3. http response

The server responds to the client (Response)

  1. response body

Accept: Tell the browser the data type 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 Browser, whether to disconnect or keep the connection after the request is completed
HOST: host.../.
Refresh: Tell the client how often to refresh;
Location: Relocate the webpage;

  1. Response status?
    200: request response successful 200
    3xx: request redirection: you go to the new location I gave you;
    4xx: resource not found 404: resource does not exist;
    5xx: server code error 500 502: gateway error

3. Servlet (emphasis)

1. Introduction to Servlets

Servlet is Sun's technology for developing dynamic web. Sun provides an interface in these APIs called: Servlet. If you want to develop a Servlet program, you only need to complete two small steps: (1) Write a class to implement the Servlet
interface
(2) Deploy the developed Java class to the web server

2. The first Servlet program

(1) Write HelloServlet program

  1. Deploy tools such as Tomcat and Maven.
  2. Create a web project.
  3. Write an ordinary class and inherit HttpServlet.
public class HelloServlet extends HttpServlet {
    
    
 
  //由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样;
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    //ServletOutputStream outputStream = resp.getOutputStream();
    PrintWriter writer = resp.getWriter(); //响应流
    writer.print("HelloSerlvet");
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    doGet(req, resp);
 }
}
  1. Write the mapping of Servlet in web.xml
  <!--注册Servlet-->
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.carry.servlet.HelloServlet</servlet-class>
  </servlet>
  <!--Servlet的请求路径-->
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  1. Configure Tomcat and start the server.

(2) Mapping mapping problem

  1. A Servlet can specify multiple mapping paths
  2. A servlet can specify a generic mapping path
  3. You can customize the suffix to implement request mapping

3.ServletContext

When the web container starts, it will create a corresponding ServletContext object for each web program.

(1) Sharing data

Data sharing can be realized through the ServletContext object, and the data stored in one Servlet can be obtained in another Servlet.

  1. In the first Servlet, assign hello to name by calling the setAttribute method of the ServletContext object.
  2. In the second Servlet, get the data stored in the first Servlet by calling the getAttribute method of the ServletContext object, and output it.
  3. Configure the map.

The test example is as follows:

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    	//获取ServletContext对象
        ServletContext context = this.getServletContext();
        String username = "hello";//存入数据
        context.setAttribute("username",username);//将一个数据存在了ServletContent中,名字为:username,值username="hello"
        System.out.println("Hello");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = this.getServletContext();
        //通过ServletContext对象的getAttribute方法获得数据
        String username = (String)context.getAttribute("username");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字"+username);
    }
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.carry.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getContext</servlet-name>
        <servlet-class>com.carry.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getContext</servlet-name>
        <url-pattern>/getContext</url-pattern>
    </servlet-mapping>

(2) Obtain initialization parameters

Some parameters configured in web.xml can be obtained by the ServletContext object. The acquisition of initialization parameters can be completed by calling the getInitParameter method of the object.

  1. Configure some web initialization parameters in web.xml
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
  </context-param>
  1. In the Servlet, the initialization parameters are obtained by calling the getInitParameter() method of the ServletContext object.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
    
    
  ServletContext context = this.getServletContext();
  String url = context.getInitParameter("url");
  resp.getWriter().print(url);
}

(3) Request forwarding

The ServletContext object can realize the request forwarding function to the website.
Request forwarding: Servlet (source component) first performs some preprocessing operations on client requests, and then forwards the request to other Web components (target components) to complete follow-up operations including generating response results.
Proceed as follows:

  1. Get the ServletContext object.
  2. Call the getRequestDispatcher() method with the path to forward as a parameter. Objects of the RequestDispatcher type can be obtained.
  3. Call the foreard() method through the RequestDispatcher object to implement request forwarding.
    The test example is as follows:
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = this.getServletContext();
        System.out.println("进入了ServletDemo04的doGet方法");
        RequestDispatcher dispatcher = context.getRequestDispatcher("/getInitParameter");//转发的请求路径
        dispatcher.forward(req,resp);//调用forward() 实现请求转发
    }

(4) Read resource files

ServletContext objects can read resource files, but this process requires the help of streams.
Specific steps are as follows:

  1. Get the ServletContext object.
  2. The properties file is converted into a stream through the ServletContext object.
  3. Get a Properties object.
  4. Store the stream in a Properties object.
  5. Call the getProperty method to get the data in the properties resource file.
    The test instance is as follows:
username=root
password=123456
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = this.getServletContext();

        InputStream inputStream = context.getResourceAsStream("/WEB-INF/classes/db.properties");

        Properties properties = new Properties();
        properties.load(inputStream);
        String user = properties.getProperty("username");
        String pwd = properties.getProperty("password");
        resp.getWriter().print(user+":"+pwd);
    }

4.HttpServletResponse

(1) Download files

The specific steps to download files through response are as follows:

  1. To get the path of the downloaded file
  2. downloaded file name
  3. Set up to find a way for the browser to support downloading what we need
  4. Get the input stream of the downloaded file
  5. create buffer
  6. Get the OutputStream object
  7. Write the FileOutputStream stream to the buffer buffer
  8. Use OutputStream to output the data in the buffer to the client!
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        //1. 要获取下载文件的路径
        //String realPath = this.getServletContext().getRealPath("/helloWorld.jpg");
        String realPath = "D:\\Project\\JetBrains\\IntelliJ IDEA\\JavaWeb\\javaweb-02-servlet\\response\\src\\main\\resources\\helloWorld.jpg";
        System.out.println("下载文件的路径:"+realPath);
        //2. 下载的文件名
        String fileName = realPath.substring(realPath.indexOf("\\") + 10);
        System.out.println("下载的文件名"+fileName);
        //3. 设置想办法让浏览器能够支持下载我们需要的东西,中文文件名URLEncoder.encode编码,否则可能是乱码
        resp.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode(fileName,"UTF-8"));
        //4. 获取下载文件的输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        //5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6. 获取OutputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //7. 将FileOutputStream流写入到buffer缓冲区, 使用OutputStream将缓冲区中的数据输出到客户端
        while ((len=inputStream.read(buffer))>0){
    
    
            outputStream.write(buffer,0,len);
        }
        inputStream.close();
        outputStream.close();
    }

(2) Redirection (emphasis)

Redirection is to redirect various network requests to other locations through various methods.
insert image description here
After a web resource of B receives a request from client A, B will notify client A to access another web resource C. This process is called redirection.
Simply implement a redirection:

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

        /*
            实际上相当于做了一下两个步骤:
            resp.setHeader("Location","/response/image");
            resp.setStatus(302);
         */
        resp.sendRedirect("/response/image");//重定向
    }

5.HttpServletRequest

HttpServletRequest represents the request of the client. When the user accesses the server through the Http protocol, all the information in the HTTP request will be encapsulated into the HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained; the HttpServletRequest object realizes the acquisition of parameters and request forwarding
:

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {
    
    
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		System.out.println(username);
		System.out.println(password);
		System.out.println(req.getContextPath());
		//通过请求转发
		//这里的 / 代表当前的web应用
		req.getRequestDispatcher("/success.jsp").forward(req,resp);
 }

6. Cookie and Session

(1 Overview

  1. Session: The user opens a browser, clicks many hyperlinks, visits multiple web resources, and closes the browser. This process can be called a session;
  2. Stateful session: A classmate has been to the classroom, and next time we come to the classroom, we will know that this classmate has been there before, which is called a stateful session.
  3. How to prove that you have been to a website
    (1) The server sends a letter to the client, and the next time the client visits the server, just bring the letter (Cookie)
    (2) The server registers that you have been here, the next time you come I'll match you (Session)
  4. Two technologies for saving sessions
    (1) cookie: client technology (response, request)
    (2) session: server technology, using this technology, the user's session information can be saved. We can put information or data in Session!
  5. Common applications: After logging in to the website, you don't need to log in next time, and you will go directly to the website the second time you visit.

(2)Cookie

  1. Get the cookie information from the request
  2. The server responds to the client cookie
    The following test code contains common methods of Cookie.
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //服务器告诉你,你来的时间,并把这个时间封装成一个信件,你下次来,我就知道你来了
        //解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //Cookie,服务器从客户端获取
        Cookie[] cookies = req.getCookies();//获取cookie,返回数组,说明Cookie可能存在多个
        //判断Cookie是否存在
        if (cookies!=null){
    
    
            //如果存在怎么办
            out.write("你上一次访问的时间是:");
            for (int i = 0;i < cookies.length;i++){
    
    
                Cookie cookie = cookies[i];
                //获取Cookie的名字
                if(cookie.getName().equals("name")){
    
    
                    //获取Cookie的值
                    System.out.println(cookie.getValue());
                    //解码
                    out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));
                }
            }
        }else {
    
    
            out.write("这是你第一次访问本站");
        }
        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        //设置cookie的有效期为1天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);//响应给客户端一个cookie
    }

Delete cookies:

  1. If the validity period is not set, the browser will be closed and it will automatically expire;
  2. Set the validity period to 0;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //创建一个cookie,名字必须要和删除的名字一致,目的是覆盖掉之前的cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        //将cookie有效期设置为0,立马过期
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

(3) Session (emphasis)

What is a Session:
The server will create a Seesion object for each user (browser). A Seesion exclusively occupies a browser. As long as the browser is not closed, the Session exists.

Usage scenario:
save a logged-in user's information;
shopping cart information;
data that is often used throughout the website, we save it in the Session

Use Session:

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到session
        HttpSession session = req.getSession();
        //给session中存东西
        session.setAttribute("name",new Person("小明",1));
        //获取session的id
        String sessionId = session.getId();
        //判断session是不是新创建的
        if(session.isNew()){
    
    
            resp.getWriter().write("session是新创建的,id:"+sessionId);
        }else {
    
    
            resp.getWriter().write("session已经存在了,id:"+sessionId);
        }

        Person person = (Person)session.getAttribute("name");
        System.out.println(person.toString());

        //手动注销session
        session.removeAttribute("name");
        session.invalidate();
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req, resp);
    }

4. JSP

1. Brief description

Java Server Pages: Java server-side pages, like Servlets, are used for dynamic Web technology!
The biggest feature: writing JSP is like writing HTML
difference:

  1. HTML only provides static data to the user
  2. JAVA code can be embedded in JSP pages to provide users with dynamic data;

2. Basic grammar

(1) jsp script fragment

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

(2) Embed HTML elements in the code:


  <%--在代码中嵌入HTML--%>
  <%
    for (int i = 0; i < 5; i++){
    
    
  %>
      <h1>helloWorld <%= i%></h1>
  <%
    }
  %>

(3) jsp statement

<%!
  static {
    
    
   System.out.println("Loading Servlet!");
 }
  private int globalVar = 0;
  public void hello(){
    
    
   System.out.println("进入了方法hello!");
 }
%>

3. JSP instruction

The difference between @include and jsp:include

  • @include will combine multiple pages into one
  • jsp:include will splice pages together, essentially multiple pages
    <%--@include会将两个页面合二为一--%>
    <%@include file="common/header.jsp"%>
    <h1>网页主体</h1>
    <%@include file="common/footer.jsp"%>
    <hr>

    <%--jsp标签
    jsp:include:拼接页面,本质还是三个
    --%>
    <jsp:include page="common/header.jsp"/>
    <h1>网页主体</h1>
    <jsp:include page="common/footer.jsp"/>

4. Nine built-in objects

  • PageContext (save stuff)
  • Request (save something)
  • Response
  • Session (save things)
  • Application [SerlvetContext] (save things)
  • config 【SerlvetConfig】
  • out
  • page (no need to understand)
  • exception
object scope
PageContext The saved data is only valid in one page
Request The saved data is only valid in one request, and the request forwarding will carry this data
Session Saved data is only valid for one session, from opening the browser to closing the browser
Application The saved data is only valid in the server, from opening the server to closing the server
From bottom to top (scope): page->request–>session–>application
illustrate:
request: The client sends a request to the server, and the generated data is useless for the user after reading it. For example: news, it is useless for the user after reading it!
session: The client sends a request to the server, and the generated data is still useful after the user finishes using it, such as a shopping cart;
application: The client sends a request to the server, and the generated data, once used up by one user, may be used by other users, such as chat data.

Five, MVC architecture

MVC, that is, Model (model), view (view), Controller (controller).

1.Model

  • Business processing: business logic (Service)
  • Data persistence layer: CRUD (Dao)

2.View

  • display data
  • Provide a link to initiate a Servlet request (a, form, img...)

3.Controller (Servlet)

  • Receive user's request: (req: request parameters, Session information...)
  • Hand over the corresponding code to the business layer
  • Control view jump

4. MVC structure diagram

insert image description here

6. Summary

1. The difference between get and post

  • get: The request can carry relatively few parameters, the size is limited, and the data content will be displayed in the URL address bar of the browser, which is not safe but efficient
  • post: There is no limit to the parameters that the request can carry, and there is no limit to the size. The data content will not be displayed in the URL address bar of the browser. It is safe but not efficient

2. The difference between redirection and forwarding

  • The same point: the page will realize the jump
  • The difference: when the request is forwarded, the url will not change; when redirected, the url address bar will change.

3. The difference between Session and Cookie:

  • Cookie is to write the user's data to the user's browser, and the browser saves it (multiple can be saved)
  • Session writes the user's data to the user's exclusive Session, and saves it on the server side (saves important information and reduces the waste of server resources)
  • Session object is created by the service

Guess you like

Origin blog.csdn.net/qq_43647936/article/details/121106433