JavaWeb-Servlet service connector (final)

Previous articleJavaWeb -Servlet Service Connector (3)_Alphamilk's Blog-CSDN Blog

Table of contents

1. Servlet Context Communication

Session Technology Cookie and Session

1.Cookie

2.Session


1. Servlet Context Communication

Concept: represents the entire web application and is used to communicate with the server

This object can be obtained by

method describe
request.getServletContext() Returns the Servlet context object associated with a given request.
this.getServletContext() Returns the context object of the current Servlet. It is a method inherited automatically by the servlet class and can be called directly in the current servlet.

The obtained object can realize the following functions

Get the MIME type (file type used in Internet communication)

method describe
request.getServletContext().getMimeType(String file) Returns the MIME type of a given file. Can be invoked with the request's Servlet context object, passing in a file path or file name as an argument.
this.getServletContext().getMimeType(String file) Returns the MIME type of a given file. It can be called directly in the current Servlet, passing in the file path or file name as a parameter.

Common MIME Types

MIME type describe
text/plain Plain Text
text/html HTML document
text/css css style sheet
application/json JSON data
application/xml XML data
application/pdf Adobe PDF documents
application/msword Microsoft Word document
image/jpeg JPEG image
image/png png images

Case code:

package com.company;

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

@WebServlet("/ContextDemo")
public class ServletContextdemo extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        定义文件名
        String filename = "javaWeb.jpg";

//      通过request创建对象
        ServletContext context = req.getServletContext();
//        通过HttpServlet本身的方法创建ServletContext
        ServletContext context1 = this.getServletContext();
//        获取文件名的mimeType类型
        String mimeType = context.getMimeType(filename);
        System.out.println("FileName:"+filename+" MIMEType:"+mimeType);
    }
//    方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

2. Domain objects (implementing shared data)

Achieved by

method describe
setAttribute(String name, Object obj) Bind the given name and object in the current scope (such as servlet context, session or request).
getAttribute(String name) Returns the object associated with the given name, or null if not found.
remove(String name) Removes the property with the given name from the current scope and returns the value of the removed property, or null if not found.

 Case code:

Set shared variable class

package com.company;

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

@WebServlet("/Contextdemo3")
public class Contextdemo3 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
//        创建共享变量
        context.setAttribute("msg","HelloWorld");
        System.out.println("访问ContextDemo3");
    }
//    方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Get shared variable class

package com.company;

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

@WebServlet("/Contextdemo4")
public class Contextdemo4 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
//        获取共享变量
        Object msg =context.getAttribute("msg");

        System.out.println("访问ContextDemo4");
//        如果消息可以进行转型字符串则转型为字符串
        if (msg instanceof String){
            System.out.println((String) msg);
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

 3. Get the real path of the file

method name describe
getRealPath(String path) Get the real path of the resource in the server file system under the specified path

Case code:

Just take javaWeb.jpg as an example to find its location in the server

package com.company;

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

@WebServlet("/ContextDemo2")
public class ContextDemo2 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        使用HttpServlet创建对象
        ServletContext context = this.getServletContext();
//        通过相对于部署的 Web 应用程序的根目录的路径来获取真实路径
        String realpath = context.getRealPath("/src/javaWeb.jpg");
        System.out.println("在服务器中存放的路径是:"+realpath);
    }
//        方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

 By comparison, it can be found that it is indeed in this position


Session Technology Cookie and Session

1.Cookie

The cookie is the session data of the client, and the data is saved to the client browser, which can save some unimportant information, such as the shopping cart website, if the browser is closed when the shopping item is selected, if there is no cookie technology, it will Lost purchase records, need to re-shopping.

Creation, setting and acquisition of cookies

method name describe
Cookie(String name, String value) Creates a new Cookie object with the given name and value
response.addCookie(Cookie cookie) Add the specified cookie to the response
response.getCookies() Get all the cookies contained in the response and return them as an array

Cookie lifecycle

Each cookie has a certain life cycle, and it will be invalid when it exceeds the valid time. By default, the cookie creation life cycle will be invalid until the client's browser is closed, and if there is no invalidation, too many cookies will be deleted. Saving it in the browser will cause a lot of resource usage. The life cycle can be controlled by the following methods

method name describe
setMaxAge(int seconds) Set the maximum time to live (in seconds) for the cookie.
- When secondsis 0, it means that the cookie will expire immediately and be deleted from the client.
- When secondsis a negative number, it means that the cookie is a session cookie, which is only valid during the user session and will be deleted after closing the browser.
- When secondsgreater than 0, it means that the cookie will expire after the specified number of seconds.

Example code for creating cookies:

Set the cookie class (case scenario: when you successfully log in to some websites, grant cookies to record user operations)

package com.company;

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

@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建一个Cookie表示购物袋中有一辆兰博基尼,并且传入多个cookie
        Cookie cookie = new Cookie("shoppingMap","Lamborghini");
        Cookie cookie1 = new Cookie("login-id","1234");
//        第一个保留七天数据,第二个默认处理
        cookie.setMaxAge(60*60*7);
        resp.addCookie(cookie);
        resp.addCookie(cookie1);
    }
//    方法统一处理
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Access the Cookie class

package com.company;

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

@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookies[] = req.getCookies();
//        输出所有的Cookie数据
        for (Cookie c:cookies) {
            String name = c.getName();
            String value = c.getValue();
            System.out.println("CookieName:"+name+" CookieValue:"+value);
        }
    }
//    统一方法处理
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

View sent packets:

The characteristics and functions of cookies

Features:

  1. The content of the cookie is stored on the client's browser
  2. The browser has a limit on the size of a single cookie, and there is also a limit on the number of cookies on the same domain name

effect:

  1. Cookies are often used to store small amounts of less sensitive data
  2. In the case of not logging in, the server can identify the user

Note: cookies should not be used to record the unique identifier of the user's login, because if someone logs in to the relevant website by forging the cookie (such as sql injection, or external csrf bypass) and illegally modifies the user's information, cause loss


2.Session

Seesion is also a server session technology, but compared with Cookie, its data is saved in the server. Generally used to identify and track user status information.

Session creation and use

method describe
HttpSession session = request.getSession() Create or get the HttpSession object of the current request, or create a new one if it does not exist.
session.getAttribute(String name) Get the property value of the specified name and return a value of type Object.
session.setAttribute(String name, Object value) Set the attribute value of the specified name, and store the value of Object type in the Session.
session.removeAttribute(String name) Removes the property value with the specified name.

Case code: create session object and assign value

create class

package com.company;

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

@WebServlet("/SessionDemo1")
public class SessionDemo1 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建Session
        HttpSession session = req.getSession();
        session.setAttribute("用户name","AlphaMilk");
        System.out.println("设置session成功");
    }
//    方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Get the session class:

package com.company;

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

@WebServlet("/SessionDemo2")
public class SessionDemo2 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        告诉浏览器服务器的编码方式是utf-8
        resp.setHeader("content-type","text/html;charset=utf-8");
//        获取请求头的session对象
        HttpSession session = req.getSession();
//        创建输出流,将session内容输出到浏览器中
        PrintWriter writer = resp.getWriter();
        writer.write("<h1>欢迎用户"+session.getAttribute("用户id")+"</h1>");
    }

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

 The problem arises: If the client browser is accidentally closed, the session obtained by opening the browser again will be a different object. So how to solve this problem?

The implementation of Session usually relies on Cookie. Every time a Session is created, a corresponding Cookie is generated, which contains an identifier called JSESSIONID, which is used to uniquely identify the Session object.

When the client initiates a request, the browser will automatically carry the cookie to the server, and the server can find the corresponding Session object by parsing the JSESSIONID in the cookie, thereby realizing state maintenance and user identity identification.

 Implement session persistence

The essence of the solution is to create an identical cookie with JSESSIONID and value

Case code:

package com.company;

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

@WebServlet("/SessionDemo3")
public class SessionDemo3 extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建session对象
        HttpSession session = req.getSession();
//        创建对应的cookie对象
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
//        设置生命周期
        cookie.setMaxAge(60*60);
        resp.addCookie(cookie);
//        获取session对象的id
        System.out.println(req.getSession().getId());
    }
//    实现方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Get it for the first time and then close the browser to get the id again

Session destruction

  • server down
  • session calls invalidate()
  • Session modifies the default expiration time

        The default expiration time of the session is 30 minutes. If you want to modify it, you need to set it in the total web.xml configuration of the project 

<session-config>
    <session-timeout>30</session-timeout>
</session-config>


Next article:

JavaWeb-Filter filter_Alphamilk's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132232645