- 首先編寫相當於web.xml的配置類
package com.powernode.springmvc.config;
import jakarta.servlet.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import java.nio.charset.CharacterCodingException;
//相當於web.xml配置檔案
@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringmvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected Filter[] getServletFilters() {
//配置字元編碼過濾器
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8");
// characterEncodingFilter.setEncoding("utf-8");
characterEncodingFilter.setForceResponseEncoding(true);
characterEncodingFilter.setForceRequestEncoding(true);
//配置HiddenHttpMethodFilter
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
}
- 編寫spring配置檔案的類
package com.powernode.springmvc.config;
import com.powernode.springmvc.interceptors.MyInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import java.util.List;
import java.util.Properties;
//相當於springmvc的配置檔案
@Configuration
@ComponentScan("com.powernode.springmvc.controller")
//開啟註解驅動
@EnableWebMvc
public class SpringmvcConfig implements WebMvcConfigurer {
@Bean
public ThymeleafViewResolver getViewResolver(SpringTemplateEngine springTemplateEngine){
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(springTemplateEngine);
thymeleafViewResolver.setCharacterEncoding("UTF-8");
thymeleafViewResolver.setOrder(1);
return thymeleafViewResolver;
}
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver iTemplateResolver){
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setTemplateResolver(iTemplateResolver);
return springTemplateEngine;
}
@Bean
public ITemplateResolver templateResolver(ApplicationContext applicationContext){
SpringResourceTemplateResolver springResourceTemplateResolver = new SpringResourceTemplateResolver();
springResourceTemplateResolver.setApplicationContext(applicationContext);
springResourceTemplateResolver.setPrefix("/WEB-INF/templates/");
springResourceTemplateResolver.setSuffix(".html");
springResourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
springResourceTemplateResolver.setCharacterEncoding("utf-8");
springResourceTemplateResolver.setCacheable(false);
return springResourceTemplateResolver;
}
//開啟靜態資源處理,開啟預設餓Servlet處理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//開啟檢視控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("Test");
}
//配置異常處理器
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
//可以配置多個異常處理器,這是其中一個
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
//配置異常對映:
Properties properties = new Properties();
properties.setProperty("java.lang.Exception","tip");
simpleMappingExceptionResolver.setExceptionMappings(properties);
//設定異常屬性名:
simpleMappingExceptionResolver.setExceptionAttribute("exception");
//將異常處理器新增到List集合中
resolvers.add(simpleMappingExceptionResolver);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
MyInterceptor myInterceptor = new MyInterceptor();
registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/test");
}
}
- 編寫Controller類
package com.powernode.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloController {
@RequestMapping(value = "/hello")
public String hello(){
System.out.println("hello方法");
return "hello";
}
}
-
編寫hello.html頁面,啟動tomcat,訪問localhost/hello測試
-
編寫配置Interceptor
package com.powernode.springmvc.interceptors;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle執行了");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
- 設定攔截規則