In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the example analysis of data and page response in SpringBoot2, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.
1 data response
data response is generally divided into two types: page response and data response. Generally speaking, the page response is used to develop some individual projects (that is, the front and back ends are all in the same development tool), while the data response is used for separate development of the front and back ends. The front end sends to request the corresponding data from the back end.
1.1 data response (JSON as an example)
if you want the SpringMVC response to return data of type JSON, you first need to import the initiator of the web scene in the pom.xml file of the project
Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-json 2.6.4 compile
's second step is to add @ ResponseBody annotations to controller, so that you can respond to data rather than page jumps, or replace @ Controller annotations on controller with @ RestController, which means that all methods under this controller are automatically annotated with @ ResponseBody annotations.
1.2 content negotiation of data response
Content negotiation: the server will return data of different media types according to the client's receiving capacity.
Principle: when the front end sends the request, the request header carries the Accept field, which is used for the server to declare the data type that it (the client) can receive.
Processing flow: first, determine whether the current response header already has the media type cached during the previous processing. If not, it is the first time to determine the media type to be processed, and obtain the content type supported by the customer (PostMan, browser) through the Accept field. After iterating through all the MessageConverter of the current system to see who supports manipulating this object (Person), find the converter that supports manipulating Person and count the media types it supports. In this way, we get the types that the client supports and the types that the server can return, and then through the content negotiation of the best matching media type, we use the support to convert the object to the best matching media type converter.
2 Page response
The default packaging method of SpringBoot is jar package, but JSP does not support compilation in jar package (a compressed package), so SpringBoot does not support JSP by default, so we need to introduce a third-party template engine technology-Thymeleaf to realize page rendering.
2.1 Thymeleaf of template engine
If wants to use Thymeleaf for page rendering, it first needs to introduce its scene initiator dependency in the pom.xml file.
Org.springframework.boot spring-boot-starter-thymeleaf
After imports the scene launcher, SpringBoot will configure all the relevant components in the ThymeleafAutoConfiguration automatic configuration class, and associate the relevant configuration items with ThymeleafProperties.class (the code is as follows) through the annotation @ EnableConfigurationProperties. The configuration class sets the default page jump prefix and suffix, that is, it specifies that the location of the page must be the templates folder and the file suffix of the page must be .html. We just need to develop the page directly.
Private String prefix = "classpath:/templates/"; private String suffix = ".html"
Entry-level case
Step 1: create a html file under the templates folder step 2: the tag introduces the templates namespace, which has the advantage that there will be relevant prompts when page numbering is written.
Xmlns:th= "http://www.thymeleaf.org"
Step 3: create a controller to jump to the page
@ Controllerpublic class ViewTestController {@ GetMapping ("/ jump") public String jumpTo (Model model) {/ / all the attribute values of model are stored in the request field, and use model.addAttribute ("msg", "Hello, Zhang San") directly when you need to use them; model.addAttribute ("link", "http://www.baidu.com"); return" seccess ";}})
Step 4: write the page code to get the values in the field
Title click to enter Baidu click to enter Baidu
The difference between the two symbols in the ⚠ page: ${} is to get the value of the link attribute directly as the link address, while @ {} is the value in the access path + symbol of the assembly project. In this case: the first link is to open Baidu, and the second is to send the request for http://localhost:8080/link.
2.2 interceptor
After the user has successfully logged in, there should be a login judgment process (to determine whether there is a correct user name and password in the session). This function can be judged by code in each controller, but this process is repeated and will greatly increase the redundancy of the code, so we can put the judgment function in the interceptor. All requests sent from the page after a successful login are intercepted for user judgment, and if the login fails, the login is returned. Take the above example as an example to illustrate the use of the interceptor: the first step: customize the interceptor (implement the HandlerInterceptor interface, rewrite the built-in method to write judgment logic in the corresponding method)
Public class LoginInterceptor implements HandlerInterceptor {/ / the method @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / implements login checking logic HttpSession session = request.getSession (); Object user = session.getAttribute ("loginUser"); if (user! = null) {/ / has logged in and released return true before the target method is executed } / / if you are not logged in, redirect to the login page request.setAttribute ("msg", "sign in first and then perform related operations"); request.getRequestDispatcher ("/") .forward (request, response); return false @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} / / methods executed after page rendering @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}
Step 2: the custom configuration class implements the WebMvcConfigurer interface, overrides the addInterceptors method to register the interceptor with the container, and specifies the interception rules
@ Configurationpublic class AdminWebConfig implements WebMvcConfigurer {@ Override public void addInterceptors (InterceptorRegistry registry) {/ / the problem is that interceptors intercept not only dynamic requests, but also static page resources and styles So also release static resources registry.addInterceptor (new LoginInterceptor ()) / / intercept all requests .addPathPatterns ("/ * *") / / requests for direct release. UplodePathPatterns ("/", "/ login", "/ css/**", "/ fonts/**", "/ js/**") "/ images/**") 2.3 File upload
file upload requires coordination between the front and back ends. The front end uses a form form to submit all the information, including single file upload and multiple file upload, and the back end uses annotations to obtain all the values in the form, and manipulates the front end form:
Email address userName headerImg image of yourself Check me out Submit
Backend controller:
@ PostMapping ("/ upload") public String upload (@ RequestParam ("email") String email, @ RequestParam ("userName") String userName, @ RequestPart ("headerImg") MultipartFile headerImg @ RequestPart ("photos") MultipartFile [] photos) throws IOException {/ / Save the avatar to the local disk if (! headerImg.isEmpty ()) {/ / create the corresponding folder File file1 = new File ("E:\\ bootTest\" + userName + "\\ headerImg") File1.mkdirs (); / / get the image name generation storage path headerImg.transferTo (new File ("E:\\ bootTest\" + userName + "\\ headerImg\\" + headerImg.getOriginalFilename () } / / Save your life photos to your local disk if (photos.length > 0) {/ / create the corresponding folder File file1 = new File ("E:\\ bootTest\\" + userName + "\\ photos"); file1.mkdirs () / / Storage for (MultipartFile photo:photos) {if (! photo.isEmpty ()) {/ / get the image name generation storage path photo.transferTo (new File ("E:\\ bootTest\" + userName + "\\ photos\" + photo.getOriginalFilename ());}} return "index";}
Configuration for file upload:
# setting of file upload size
Spring:
Servlet:
Multipart:
# maximum size of a single file
Max-file-size: 50MB
# maximum size of the total file
Max-request-size: 100MB
Thank you for reading this article carefully. I hope the article "sample Analysis of data and Page responses in SpringBoot2" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.