Article Directory
- Zero, learning goals
- One, Spring MVC automatic configuration
- Second, the implementation of Spring MVC function expansion
-
- (1) Create a Spring Boot project-SpringMvcDemo2021
- (2) Transform the current project-transplant the content of the previous project
- (3) Write the MVC configuration file and define the view jump
- (4) Write an interceptor to display the year on the login page
- (5) Write a login blocker to prevent non-login users from viewing all user information
-
- 1. Restore the annotations of the toLoginPage method in the login controller
- 2. Comment out the corresponding view controller in the custom MVC configuration
- 3. Modify the login() method in the login control
- 4. Rewrite the preHandle() method in the custom interceptor
- 5. Exclude paths that cannot be intercepted in the custom MVC configuration file
- 6. Start the application and test the effect
- 3. After-class development exercises
Zero, learning goals
- Understand Spring MVC automatic configuration in Spring Boot
- Master Spring MVC function extension and customization in Spring Boot
In Web development, functions such as access support for static resources, configuration of view parsers, customization of converters and formatters, file upload and download, etc. are involved, and even the customization of Servlet-related components associated with the Web server needs to be considered. , Spring Boot framework supports the integration of some commonly used web frameworks to realize web development, and supports some common functions in web development by default.
One, Spring MVC automatic configuration
(1) Overview of automatic configuration
In the Spring Boot project, once the Web dependency starter is introduced spring-boot-starter-web
, some XxxAutoConfiguration
automatic configuration classes implemented by Spring Boot integrated by the Spring MVC framework will automatically take effect, and Web development can be carried out almost without any additional configuration.
(2) Spring Boot integrates the automatic configuration features of Spring MVC
- Built-in two view resolvers:
ContentNegotiatingViewResolver
andBeanNameViewResolver
; - Support static resources and
WebJars
; - The converter and formatter are automatically registered;
- Support Http message converter;
- The message code parser is automatically registered;
- Support static project homepage
index.html
; - Support custom application icons
favicon.ico
; - Automatically initialize the web data binder
ConfigurableWebBindingInitializer
.
Second, the implementation of Spring MVC function expansion
(1) Create a Spring Boot project-SpringMvcDemo2021
- Use the Spring Initializr method to create a Spring Boot project, and select the Web dependency starter and Thymeleaf dependency starter in the Dependencies dependency selection
(2) Transform the current project-transplant the content of the previous project
- Copy the html template file, international configuration file, global configuration file and related Java files (except entry files) of the 10th lecture case [Thymeleaf18N] to the corresponding location of the current project
- Start the application and check if it is successful
- Visit the login page-http://localhost:8080/toLoginPage
- Visit the show all users page-http://localhost:8080/allUsers
(3) Write the MVC configuration file and define the view jump
1. Comment out the comment on the toLoginPage() method of the controller LoginController
2. Implement the interface WebMvcConfigurer and rewrite the addViewControllers method
package net.hw.lesson11.config;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import sun.misc.Contended;
/**
* 功能:自定义MVC配置
* 作者:华卫
* 日期:2021年02月27日
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
/**
* 添加视图控制器
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 当通过login.html访问时,直接跳转到login视图对应的页面,即login.html页面
registry.addViewController("login.html").setViewName("login");
// 通过toLoginPage访问时,也直接跳转到视图名login对应的页面,login.html页面
registry.addViewController("toLoginPage").setViewName("login");
}
}
- Note: The custom MVC configuration class must be annotated
@Configuration
- Note: In the toLoginPage() method, the attributes are set through the model
currentYear
, which will be passed to the front end when jumping to the login page, but directly through the view controller defined just now, there is no data transfer, therefore, the login page code must be modified , Do not display the year for the time being, so as not to report an error.
3. Modify the login page and comment out the code showing the year
3. Start the application and test the effect
- access
http://localhost:8080/toLoginPage
- access
http://localhost:8080/login.html
- Both methods can jump to the login.html page, of course, the year is not displayed at this time.
(4) Write an interceptor to display the year on the login page
The role of the interceptor is to perform related processing before or after the access request, such as judging whether the user is logged in before accessing the resource, if it is logged in, it can be accessed, otherwise it cannot be accessed. In this case, the year data of the current year is obtained after the access request and brought to the login page to display it.
1. Implement the interface HandlerInterceptor and implement the postHandle() method
- Note: The preHandle() method must be rewritten before the request is processed, the postHandle() method must be rewritten to process the request, and the afterCompletion() method must be rewritten after the request is completed.
package net.hw.lesson11.interceptor;
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.util.Calendar;
/**
* 功能:自定义拦截器
* 作者:华卫
* 日期:2021年02月27日
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
}
}
2. Rewrite the addInterceptors() method in MyMvcConfig to load a custom interceptor
3. Modify the login page and cancel the comment showing the year
- Compilation will report an error, saying that it cannot be parsed
currentYear
, don't care about it, because the data does not come from the controller, but from the interceptor. The data can only be obtained after the runtime request, so the compilation will report an error.
4. Start the application and test the effect
- access
http://localhost:8080/toLoginPage
- access
http://localhost:8080/login.html
- The year can be displayed in both ways, indicating that the postHandle() in the custom interceptor has taken effect.
(5) Write a login blocker to prevent non-login users from viewing all user information
- It is required that users who are not logged in cannot view user information, but before defining the interceptor,
http://localhost:8080/allUsers
all user information can be seen through the path .
1. Restore the annotations of the toLoginPage method in the login controller
2. Comment out the corresponding view controller in the custom MVC configuration
3. Modify the login() method in the login control
4. Rewrite the preHandle() method in the custom interceptor
- Block non-login users, redirect them directly to the login page, and force them to log in
5. Exclude paths that cannot be intercepted in the custom MVC configuration file
6. Start the application and test the effect
- Before
http://localhost:8080/allUsers
logging in , visit and jump directly to the login page. After logging in successfully, you can view all user information.