[Java Basics]-[SpringMVC]

What is MVC?

MVC is a design pattern in which software is divided into three layers, namely Model, View, and Controller.

  1. M: Model, model layer, refers to JavaBean in the project, its function is to process data
  2. V: View, view layer, refers to the html or jsp pages in the project. Its function is to interact with users and display data.
  3. C: Controller, control layer, refers to the servlet in the project. Its function is to receive requests and respond to browsers. The advantage of layering software is that it can reduce the coupling between objects and facilitate code maintenance.

What does the DAO layer do?

dao is specially used to access databases. There are many specific implementation technologies. Commonly used ones include Spring JDBC, Hibernate, JPA, MyBatis, etc.

Spring MVC execution process

  1. The user initiates an HttpRequest request to the front-end controller (DispatcherServlet) through the browser.
  2. DispatcherServlet sends user requests to the handler mapper (HandlerMapping).
  3. The processor mapper (HandlerMapping) will find the processor responsible for processing the request based on the request, and encapsulate it as a processor execution chain (HandlerExecutionChain) and return it to DispatcherServlet
  4. DispatcherServlet will find the processor adapter (HandlerAdaptor) that can execute the processor based on the processor in the processor execution chain - Note, there are multiple processor adapters
  5. The handler adapter (HandlerAdaptoer) will call the corresponding specific Controller
  6. The Controller encapsulates the processing results and the view to be jumped into an object ModelAndView and returns it to the HandlerAdaptor
  7. HandlerAdaptor directly hands ModelAndView to DispatcherServlet. At this point, the business processing is completed.
  8. After the business is processed, we need to display the processing results to the user. So DisptcherServlet calls ViewResolver to encapsulate the view name in ModelAndView into a view object
  9. ViewResolver returns the encapsulated view (View) object to DIspatcherServlet
  10. DispatcherServlet calls the view object to render itself (View) (fill model data into the view) to form a response object (HttpResponse)
  11. The front-end controller (DispatcherServlet) responds (HttpResponse) to the browser and displays it on the page.

The user sends a request to the server through the view layer, and the request is received by the Controller in the server. The Controller calls the corresponding Model layer to process the request (the Controller calls the service to process the business logic, the service calls the DAO to operate the database, and the DAO returns the database processing result to the service, and the service then Return to the Controller), and after processing, the result is returned to the Controller. The Controller then finds the corresponding View based on the result of the request processing, and finally responds to the browser after rendering the data.

Spring MVC common annotations

@RequestMapping:

  1. effect:Handle request address mapping, that is, map the processor method to the url path.
  2. Attributes:
    (1) method: allows you to specify the request method, such as get and post.
    (2) value: refers to the actual address of the request. If there are multiple addresses, use {} to specify it.
    (3) Produces: Specify the content type to be returned. It can only be returned when the Accept type in the request header contains the specified type.
    (4) consumes: Specify the content type submitted for processing the request, such as some json, html, text, etc. types.
    (5) headers: When you specify the header values ​​that must be included in the request, it will use this method to process the request.
    (6) params: Specify the parameter values ​​that must be present in the request before it will use this method to process the request.

@RequestParam:

  1. Function: Bind request parameters to the method parameters of your controller. It is an annotation for receiving ordinary parameters in Spring MVC.
  2. Attributes:
    (1) value is the name in the request parameter.
    (2) required is whether the request parameter must be provided. Its default is true, which means that it must be provided.

@RequestBody:

  1. Function: If it is applied to a method, it means that the return result of the method is directly written into the Http responsebody (an annotation generally used when obtaining data asynchronously).
  2. Attributes:
    (1) required: whether there must be a request body. Its default value is true. When using this annotation, it is worth noting that when it is true, the get request method will report an error. If you set the value to false, the get request will be null.

@PathVaribale: Used to bind placeholders in URLs, but after spring 3.0, URLs began to support placeholders. It is an important sign of the rest-style URLs supported by Spring MVC.

Spring MVC interceptor

The interceptor intercepts the processor to enhance the functionality of the processor. In Spring MVC, all interceptors need to implement HandlerInterceptorthe interface, which contains the following three methods: preHandle(), postHandle(), afterCompletion(). The execution flow of these methods is as follows:
Please add image description
As can be seen from the above figure, the execution flow of the Spring MVC interceptor is as follows:

  1. Execute the preHandle method, which will return a Boolean value. If false, end all processes, if true, proceed to the next step.
  2. Execute the processor logic, which contains the functionality of the controller.
  3. Execute the postHandle method.
  4. Perform view parsing and view rendering.
  5. Execute the afterCompletion method.

The development steps of Spring MVC interceptor are as follows:

  1. Develop an interceptor: implement the handlerInterceptor interface, select the appropriate method from the three methods, and implement the specific business logic to be executed when intercepting.
  2. Register the interceptor: Define the configuration class and let it implement the WebMvcConfigurer interface, register the interceptor in the addInterceptors method of the interface, and define which request paths the interceptor matches.

How to do request interception?

If you want to intercept all requests (such as requests to access static resources), you can use Filter.
If you are intercepting the Controller, you can use Spring MVC's interceptor.
If you are intercepting requests from beans other than Controller, you can use Spring AOP.

other

The difference between cookies and sessions

  1. The storage locations are different: cookies are stored on the client side; sessions are stored on the server side.
  2. The storage capacity is different: the data saved by a single cookie is <=4KB, and a website can save up to 20 cookies; there is no upper limit for sessions.
  3. Storage methods are different: cookies can only store ASCII strings and need to be encoded and stored as Unicode characters or binary data; sessions can store any type of data, such as strings, integers, sets, etc.
  4. The privacy policy is different: cookies are visible to the client, and people with ulterior motives can analyze the cookies stored locally and conduct cookie spoofing, so it is unsafe; the session is stored on the server, transparent to the client, and there is no sensitivity Risk of information leakage.
  5. The life cycle is different: you can achieve long-term validity of the cookie by setting the cookie attributes; the session depends on the cookie named JSESSIONID, and the default expiration time of this cookie is -1. Just close the window and the session will expire, so the session It cannot be effective for a long time.
  6. The server pressure is different: the cookie is stored on the client and does not occupy server resources; the session is stored on the server, and each user will generate a session. If the concurrency is large, a large amount of server memory will be consumed.
  7. Browser support is different: cookies need to be supported by the browser. If the client disables cookies, session tracking will be invalid; when using session, you need to use URL rewriting, and all URLs that use session must be rewritten. Otherwise session session tracking will also be invalid.
  8. Cross-domain support is different: cookie supports cross-domain access, but session does not support cross-domain access.

Scenarios suitable for cookies and sessions

  1. Sensitive data should be stored in the session because cookies are not secure.
  2. For ordinary data, priority is given to storing it in cookies, which will reduce the occupation of server resources.

How session works

Session relies on cookies. When a client accesses the server for the first time, the server creates a session object for it, which has a unique identifier SESSIONID. And during the response phase, the server will create a cookie and store the SESSIONID in it. The client holds the SESSIONID through the response cookie, so when it accesses the server again, it will carry the SESSIONID through the cookie. After the server obtains the SESSIONID, it can find the session object corresponding to it, and then obtain the client's status from this session.

The difference between get request and post request

  1. GET is harmless when the browser rolls back, while POST submits the request again.
  2. The URL address generated by GET can be Bookmarked, but POST cannot.
  3. GET requests will be actively cached by the browser, but POST will not unless manually set.
  4. GET requests can only be URL encoded, while POST supports multiple encoding methods.
  5. GET request parameters will be completely retained in the browser history, while parameters in POST will not be retained.
  6. The parameters transmitted in the URL of the GET request are limited in length, while the POST request does not.
  7. Regarding the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.
  8. GET is less secure than POST because the parameters are exposed directly on the URL, so it cannot be used to pass sensitive information.
  9. GET parameters are passed through the URL, and POST is placed in the Request body.

Can the parameters of the get request be placed in the body?

GET requests can put parameters in the BODY. The official does not explicitly prohibit it, but the suggestions given are that this does not comply with the specifications and cannot be guaranteed to be supported by all implementations. This means that if you try to do this, various unknown problems may arise, so it should be avoided.

Why is post not idempotent?

The idempotence of HTTP methods means that one and multiple requests for a resource should have the same side effects. Idempotence belongs to the category of semantics. Just as the compiler can only help check for syntax errors, the HTTP specification has no way to define it through syntax means such as message format.
The URI corresponding to POST is not the created resource itself, but the recipient of the resource. For example: The semantics of POST http://www.forum.com/articles is to create a post under http://www.forum.com/articles. The HTTP response should contain the creation status of the post and the URI of the post. Two identical POST requests will create two resources on the server side, with different URIs. Therefore, the POST method is not idempotent.

What does it mean when the page reports a 400 error?

The 400 status code indicates that the semantics of the request are incorrect and the current request cannot be understood by the server. The client should not resubmit this request unless modified. Usually, this request contains incorrect parameters. At this time, the parameters passed by the front end should be checked.

What should I do if the request data is garbled?

The reason why the request is garbled on the server is that the client encoding is inconsistent with the server decoding scheme. There are several solutions:

  1. Convert the obtained data into BYTE according to the client encoding, and then convert the BYTE into a string according to the server encoding. This solution is effective for various request methods, but it is very troublesome.
  2. Before accepting the request data, the encoding of the content of the display declaration entity is consistent with that of the server. This method is only valid for POST requests.
  3. Modify the server's configuration file to show that the encoding of the request path is consistent with the server. This method is only valid for GET requests.

How to implement a scheduled task under the SpringBoot framework?

Spring provides us with a thread pool ThreadPoolTaskScheduler that can execute scheduled tasks. The thread pool provides multiple methods for executing scheduled tasks, as shown below. In Spring Boot, you only need to enable the thread pool annotation in the configuration class to use this thread pool directly.
Please add image description

How to design a log when calling an interface?

You can define a logging component and weave it into the call of this interface through AOP.

Spring Boot JPA

JPA is Java Persistence API, which is a standard specification based on O/R mapping. That is to say, it specifies standard rules and does not provide implementation. Software providers can implement it according to standard specifications, and users only need to use it in the way defined in the specifications without having to deal with software providers. The main implementations of JPA include Hibernate, EclipseLink, OpenJPA, etc. We use JPA for development, no matter which implementation method is used.

Guess you like

Origin blog.csdn.net/CaraYQ/article/details/130045611