In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to achieve the common functions of WEB by SpringBoot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
SpringMVC integration support
In order to implement and simplify Web development, Spring Boot provides integration support for some commonly used Web development frameworks, such as Spring MVC, Spring WebFlux and so on. When using Spring Boot for Web development, you only need to introduce the dependent initiator of the corresponding Web development framework into the project.
Spring MVC automatic configuration
In the SpringBoot project, once the Web dependent initiator spring-boot-starter-web is introduced, some of the xxxAutoConfiguration autoconfiguration classes implemented by default in the SpringBoot integrated Spring MVC framework will automatically take effect, and Web development can be done almost without any additional configuration. Spring Boot integrates the Spring MVC framework to achieve Web development, which mainly provides the following features of automatic configuration.
(1) built-in two view parsers: ContentNegotatingViewResolver and BeanNameViewReso
(2) support static resources and WebJars.
(3) the converter and formatter are automatically registered.
(4) support Http message converter.
(5) the message code parser is automatically registered.
(6) support static project home page index.html.
(7) support customized application icon favicon.ico.
(8) initialize Web data binder ConfigurableWebBindinglnitializer automatically.
Many default configurations are provided when Spring Boot integrates Spring MVC for Web development, and most of the time the default configuration can be used to meet the development needs. For example, when Spring Boot integrates Spring MVC for Web development, there is no need to configure a view parser.
Implementation of Spring MVC function extension
When Spring Boot integrates Spring MVC for Web development, it provides a lot of automatic configuration, but in actual development, developers still need to expand and implement some functions. Below we use a specific case to illustrate the integration of Spring Boot Spring MVC framework to achieve Web development extension functions.
Building the basic environment of the project
Use the Spring Inifializr method to create a Spring Boot project named springboot02 and import Web and Thymeleaf dependencies.
After we start the project and visit http://localhost:8080/, we can see that the following interface indicates that the visit is successful and that our project is created successfully.
We create a login interface login.html in the templates package under resources
Login
Finally, create the controller package and the LoginController class under the com.hjk package
Package com.hjk.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import java.util.Calendar;@Controllerpublic class LoginController {/ * get and encapsulate the current year jump to the login page login.html * / @ GetMapping ("/ toLoginPage") public String toLoginPage (Model model) {model.addAttribute ("currentYear", Calendar.getInstance () .get (Calendar.YEAR)) Implementation of return "login";}} function extension
Next, we use Spring Boot to integrate Spring MVC for Web development to achieve a simple page jump function. Here we will use the WebMvcConfigurer interface provided by Spring Boot to write a custom configuration and extend the Web function appropriately. Here we demonstrate the implementation of the view manager and interceptor, respectively.
Register View Manager
Create a config package under com.hjk of the springboot project and create a configuration class MyMVCconfig that implements the WebMvcConfigurer interface, which is used to extend the functions of the MVC framework
Package com.hjk.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import javax.annotation.Resource;@Configurationpublic class MyMVCconfig implements WebMvcConfigurer {@ Override public void addViewControllers (ViewControllerRegistry registry) {registry.addViewController ("/ toLoginPage") .setViewName ("login") Registry.addViewController ("/ login.html") .setViewName ("login");}}
MMVCconig implements the addViewControllerse (ViewControllerRegistry registry) method of the interface WebMvcConigurer. Inside the addViewControllers () method, the addviewController () method of ViewControllerRegistry defines the request control for "tologinPage" and "login.html" respectively, and causes the setViewName ("login") method to map the path to the login.html page.
After customizing the view management function of MVC
The effect test can be carried out. In order to demonstrate this customization effect, restart the chapter05 project and start the project successfully. You can access the login.html page by visiting http://localhost:8080/toLoginPage and http://localhost:8080/login.htm on the browser respectively.
The user request control method defined by WebMvcConfigurer interface also realizes the effect of user request control jump. Compared with the traditional request processing method, this method is more concise, intuitive and convenient. At the same time, it can also be seen that it is impossible to get the data processed in the background in this way. It should be noted that using the addViewControllers (ViewControllelRegistry registry) method in the WebMvcConfigurer API to customize view control is only suitable for relatively simple Get requests without parameters. For jump requests with parameters or business processing, it is best to use the traditional method to process requests.
Register a custom interceptor
The WebMvcConfigurer interface provides many MVC development related methods, adding interceptor methods addInterceptors (), adding formatted interceptor methods addFormatters () We implement interceptor methods here.
We create a custom interceptor class MyInterceptor under the config package with the following code.
Package com.hjk.config;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.Calendar;@Componentpublic class MyInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String uri = request.getRequestURI (); Object loginUser = request.getSession () .getAttribute ("loginUser") If (uri.startsWith ("/ admin") & & null==loginUser) {try {response.sendRedirect ("/ toLoginPage");} catch (IOException e) {e.printStackTrace ();} return false;} return true } public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println ("interceptor interception"); public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
The custom interceptor class Mylnterceptor implements the HandlerInterceptor interface. In the preHandle () method, if the user request starts with "/ admin", that is, accessing an address such as http://localhost:8080/admin determines whether the user is logged in, and if not, redirects to the login page corresponding to the "hoLoginPage" request.
In the postHandle () method, the interceptor interception is printed on the console.
Then in the custom configuration class MyMVCconfig under the config package, override the addlnterceptors () method to register the custom interceptor. Add the following code.
@ Autowiredprivate MyInterceptor myInterceptor;@Overridepublic void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (myInterceptor) .addPathPatterns ("/ *") .excludePathPatterns ("/ login.html");}
First introduce the custom Mylnterceptor interceptor component using the @ Autowired annotation, and then override the addinterceptors () method in it to register the custom interceptor. When registering a custom interceptor, the addPathPatterns ("/ * *) method is used to intercept all path requests, and the excludePathPatterns (" / login.htm ") method releases the request for the" login.html "path.
Test: we can visit http://localhost:8080/admin and find that it redirects the big toLoginPage interface.
Spring integrates the three components of Servlet
Here we use the component registration method to integrate the three major components of Servlet, Filter and Listener. We only need to register the custom components into the container through the ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean classes.
Using registration to integrate Servlet using component registration
We create a package for servletComponent under the com.hjk package, create a MyServlet class under that package, and inherit the HttpServlet class.
Package com.hjk.servletCompont;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Componentpublic class MyServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doGet (req, resp) } protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter (). Write ("hello MyServlet");}
The @ Component annotation injects the MyServlet class into the Spring container as a component. The MySeret class inherits from HttpServlet and outputs "hello MyServlet" to the page through the HttpServletResponse object.
Create a Servlet component configuration class. Create a Servlet component configuration class servietConfig under the project com.hjk.confg package to register Servlet-related components
Package com.hjk.config;import com.hjk.servletCompont.MyServlet;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class ServletConfig {@ Bean public ServletRegistrationBean getServlet (MyServlet myServlet) {ServletRegistrationBean registrationBean = new ServletRegistrationBean (myServlet, "/ myServlet"); return registrationBean;}}
The ServletConfig is annotated as a configuration class with the @ Configuration annotation, and the getServlet () method inside the ServletConfig class is used to register the custom MyServlet and return a Bean object of type ServletRegistrationBean.
Test: after the project starts successfully, visit "http://localhost:8080/myServlet"myServlet" on the browser and display the data normally, indicating that Spring Boot has successfully integrated Servlet components.
Integrate Filter using component registration
Create a MyFilter class under the servletCompont package and implement the Filter interface. The Filter package is misguided.
Package com.hjk.servletCompont;import org.springframework.stereotype.Component;import javax.servlet.*;import java.io.IOException;@Componentpublic class MyFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println ("hello MyFilter"); public void destroy () {}
Register in the ServletConfig class under the config package, that is, add methods to the class.
@ Beanpublic FilterRegistrationBean getFilter (MyFilter myFilter) {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean (myFilter); filterRegistrationBean.setUrlPatterns (Arrays.asList ("/ toLogin", "/ myFilter"); return filterRegistrationBean;}
The filtered request path is defined using the setUrilPatterns (Arrays.asList ("/ toLoginPage", / myFilter') method
"/ toLoginPage" and "/ myFilter", using the @ Bean annotation to return the currently assembled FilterRegistrationBea object as a Bean component.
Test: visit "http://localhost:8080/myFilter"" on the browser to view the printing effect of the console (because there is no request processing method for writing the corresponding path, the browser will have a 404 error page, just focus on the console), and the browser will visit "http://localhost:8080/"
When "myFilter", the console prints out the output statement "hello MyFilter" that defines figure 5-6 in the custom Filter to integrate the running results of Filter using component registration, which shows that the Spring Boot integration of custom Filter components is successful.
Integrate Listener using component registration
(1) create a custom Listener class. Create a class MyListener under the com.itheima.senleiComponent package to implement the ServletContextListener interface
Package com.hjk.servletCompont;import org.springframework.stereotype.Component;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;@Componentpublic class MyListener implements ServletContextListener {@ Override public void contextInitialized (ServletContextEvent sce) {System.out.println ("contextnitialized...");} public void contextDestroyed (ServletContextEvent sce) {System.out.println ("contextDestroyed...");}
Add registration in servletConfig
@ Beanpublic ServletListenerRegistrationBean getServletListener (MyListener myListener) {ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean (myListener); return servletListenerRegistrationBean;}
It is important to note that the Servlet container provides many Listener interfaces, such as ServletRequestListener, ritpSessionListener, ServletContextListener and so on. When we customize the Listener class, we need to choose to implement the corresponding interface according to our own needs.
Test: after the program starts successfully, the console will print out the output statement "contextlnitialized.." defined in the custom Listener component. Click the [Exit] button in the figure to close the current project (note that if clicking the red button forces the program to be closed, the browser will not be able to print the closed listening message) and view the console print again.
After the program closes successfully, the console prints out the output statement "contextDestroyed.." defined in the custom Listener component. Through the effect demonstration, it shows that the integration of custom Listener components by Spring Boot is successful.
File upload and download
When developing web applications, file upload is a very common requirement. The browser passes the file to the server in the form of a stream, and the server is parsing and processing the uploaded data.
File upload, compile upload form interface
This form interface is called upload.html and is under the templates folder
File upload:
We upload files through the form, and the form is submitted to the uploadFile controller. Post must be submitted in this way, because get uploads are rare and must contain enctype= "multipart/form-data".
We should also be clear by submitting the address, we will definitely write a uploadFile controller.
Add configuration related to file upload
We add the configuration to the application.properties file and the size limit for uploading the file.
# # maximum file limit is 10mb, default is 1mbspring.servlet.multipart.max-file-size=1MB
If the file exceeds the limit size, an error will be reported.
Write a controller
We unloaded a class called FileController in the com.hjk.controller package, which is used to implement the controller for file upload.
Our file upload is only a simple file upload, and does not take into account the duplicate name of the uploaded file. In fact, if the file has the same name, it will overwrite the previous file. To upload a file, we must give it a unique name, which can be implemented using uuid. We don't consider the location of the file here. I wrote down the address myself, so we won't implement it here.
Implementation process: when writing this controller, my code is correct, the front-end files can also be submitted, but the back-end access to the file is null, I also read a lot of blogs, some said that they did not register multipartResolver this Bean, some said it was a version problem, etc., but none of them was solved. The last inadvertently small detail caused my code not to get the file this time. That is, we have the annotation @ RequestParam before (@ RequestParam ("filename") MultipartFile file). Anyway, this one of mine can be used after it is added. My springboot version is 2.6.6. As for the real reason, I don't want to think about it now. I'll change it later.
@ RequestPara ("filename") must get the file parameter named filename
@ RequestParam () is required by default and can be set to optional via @ RequestParam (required = false). Because the invalid value defaults to true, it must be passed by default.
@ RequestParam ("filename") or @ RequestParam (value = "filename") specify the parameter name
@ RequestParam (defaultValue = "0") specifies the parameter default value
Package com.hjk.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;@Controllerpublic class FileController {@ GetMapping ("/ toUpload") public String toUpload () {return "upload" } @ RequestMapping (value = "/ uploadFile", method = RequestMethod.POST) public String uploadFile (@ RequestParam ("filename") MultipartFile file) {String filename = file.getOriginalFilename (); String dirPath = "D:/file/"; File filePath = new File (dirPath); if (! filePath.exists ()) {filePath.mkdir () } try {file.transferTo (new File (dirPath+filename));} catch (IOException e) {e.printStackTrace ();}
Here we submit three pictures for the following file download
File download
Many frameworks for file download are not encapsulated, and different browsers have different parsing processes, so garbled code may occur.
After adding the dependencies, we create a html called filedownload.html, which will be used to write the download interface.
Add dependent commons-io commons-io 2.6 download processing controller
Let's add download handling methods to the FileController class. Just add it to it.
@ GetMapping ("/ toDownload") public String toDownload () {return "filedownload";} @ GetMapping ("/ download") public ResponseEntity fileDownload (String filename) {/ / specified download address file path String dirPath = "D:/file/"; / / create file download object File file = new File (dirPath + File.separator + filename); / / set response header HttpHeaders httpHeaders = new HttpHeaders () / / notify the browser to open httpHeaders.setContentDispositionFormData ("attachment", filename) by downloading; / / define the returned file httpHeaders.setContentType (MediaType.APPLICATION_OCTET_STREAM) to download as a stream; try {return new ResponseEntity (FileUtils.readFileToByteArray (file), httpHeaders, HttpStatus.OK);} catch (IOException e) {e.printStackTrace (); return new ResponseEntity (e.getMessage (). GetBytes (), HttpStatus.EXPECTATION_FAILED) Write frontend code file download file download list 0000001.jpg download file 0000002.jpg download file 0000003.jpg download file
We used thymeleaf to write the front-end code this time.
In fact, we may encounter the problem of downloading Chinese files, which may lead to garbled codes.
Let's write an example of solving Chinese garbled code here. For example, when I change 0000001.jpg to "Hello jpg" and then redeploy the download, I will find that the name is _. Jpg
Let's directly add a getFileName method to our fileController class and modify the fileDownload method to make changes.
Public String getFileName (HttpServletRequest request,String filename) throws Exception {String [] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"}; String userAgent = request.getHeader ("User-Agent"); for (String ieBrowserKeyWord: IEBrowserKeyWords) {if (userAgent.contains (ieBrowserKeyWord)) {return URLEncoder.encode (filename, "UTF-8"). Replace ("+", "") }} return new String (filename.getBytes (StandardCharsets.UTF_8), "ISO-8859-1");} @ GetMapping ("/ download") public ResponseEntity fileDownload (HttpServletRequest request,String filename) throws Exception {/ / specified download address file path String dirPath = "D:/file/"; / / create file download object File file = new File (dirPath + File.separator + filename) / / set the response header HttpHeaders httpHeaders = new HttpHeaders (); / / notify the browser to download 7, 000 and performance transcoding filename = getFileName (request,filename); / / notify the browser to open httpHeaders.setContentDispositionFormData ("attachment", filename) in download mode; / / define the return file httpHeaders.setContentType (MediaType.APPLICATION_OCTET_STREAM) to be downloaded as a stream Try {return new ResponseEntity (FileUtils.readFileToByteArray (file), httpHeaders, HttpStatus.OK);} catch (IOException e) {e.printStackTrace (); return new ResponseEntity (e.getMessage (). GetBytes (), HttpStatus.EXPECTATION_FAILED); packaged deployment of SpringBoot
Springboot uses an embedded Servlet container, so it is packaged in jar packages by default. You can also package war, but you need to do some configuration.
Packing in jar package form
When we create the springboot project, we will import the packaged plug-in of maven for us by default, if not, we can add it manually.
Org.springframework.boot spring-boot-maven-plugin
Double-click package and wait.
Waiting for the completion, you can see the packing time, the location of the jar package and other information. We can also view the jar package under the target package.
Start the jar package
We can start it by entering a command in the idea console after closing the started springboot project.
Java-jar target\ springboot02-0.0.1-SNAPSHOT.jar
We can also start it in the terminal window that comes with the system.
Packing in war package form
First of all, we need to change the default packaging method to war package.
Springboot02Demo project for Spring Bootwar 1.8
Import external Tomcat server
Org.springframework.boot spring-boot-starter-tomcat provided
Open the startup class and inherit the springbootServletInitializer class
Package com.hjk;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.web.servlet.ServletComponentScan;import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;@ServletComponentScan@SpringBootApplicationpublic class Springboot02Application extends SpringBootServletInitializer {public static void main (String [] args) {SpringApplication.run (Springboot02Application.class, args) @ Override protected SpringApplicationBuilder configure (SpringApplicationBuilder builder) {return builder.sources (Springboot02Application.class);}}
Then, in the same way as the jar package, double-click package and wait for the package to complete.
Deployment of war packages
The deployment of the war package is more troublesome than the jar package, we need an external server, we need to copy the war package to the webapps directory under the tomcat installation directory, execute the startup.bat command in the directory to start the war package, so we are done.
This is the end of the content of "how SpringBoot implements the common functions of WEB". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.