1、create project
后面next即可
项目结构
2、config Tomcat
3、实现
pom
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
MyHandler
public class MyHandler implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
System.out.println("请求之前处理");
String token = request.getParameter("token");
System.out.println("token=" + token);
if (StringUtils.isEmpty(token)) {
response.getWriter().write("token is null");
return false;
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("postHandle方法之后处理");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("afterCompletion方法之后处理");
}
}
MyWebApplicationInitializer
public class MyWebApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.register(SpringMvcConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(webApplicationContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", dispatcherServlet);
servlet.addMapping("/");//添加上下文路径地址
servlet.setLoadOnStartup(1);//最优先启动
servlet.setAsyncSupported(true); //设置允许异步线程
}
}
PayService
@Component
public class PayService {
public void pay() {
try {
System.out.println(">>>3.pay业务<<<<<<< ThradName:" + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(">>>4.pay业务<<<<<<< ThradName:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
SpringMvcConfig
@Configuration //相当bean.xml
@ComponentScan(basePackages = {"com.whotw"}) //开启扫包
@EnableWebMvc //相当开启注解版springmvc 相当web.xml
public class SpringMvcConfig implements WebMvcConfigurer {
//如果使用继承 WebMvcConfigurationSupport 的方式则 @EnableWebMvc 需要关闭,因为@EnableWebMvc底层就是继承WebMvcConfigurationSupport
/***配置视图解析器*/
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
// 前缀
internalResourceViewResolver.setPrefix("/WEB-INF/view/");
// 后缀
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
@Bean
public MyHandler myHandler() {
//自定义拦截器交给spring管理
return new MyHandler();
}
/**重写WebMvcConfigurer的addInterceptors方法*/
public void addInterceptors(InterceptorRegistry registry) {
//添加拦截器
registry.addInterceptor(myHandler()).addPathPatterns("/**");
}
}
SpringMvcController
@Controller
public class SpringMvcController {
@ResponseBody
@RequestMapping(value = "/")
public String boot(HttpServletRequest request) {
return "this is spring-mvc of annotation";
}
@RequestMapping(value = "/index")
public String index() {
System.out.println("index方法处理");
return "index";
}
@ResponseBody
@RequestMapping(value = "/login")
public String login() {
System.out.println("login方法处理");
return "login success";
}
@Autowired
private PayService payService;
@RequestMapping(value = "/asyncPay")
@ResponseBody
public Callable<String> asyncPay() {
System.out.println("asyncPay方法处理");
System.out.println(">>>1.开始调用pay<<<<<<< ThradName:" + Thread.currentThread().getName());
//Callable<String>表示返回类型为String
Callable callable = new Callable<String>() {
public String call() throws Exception {
payService.pay();
return "success";
}
};
System.out.println(">>>2.结束调用pay<<<<<<< ThradName:" + Thread.currentThread().getName());
return callable;
}
}
4、打包项目
指令打包或
5、运行项目
6、测试项目
http://localhost:8080/index?token=11 //token值随便 测试整合视图解析器
http://localhost:8080/login http://localhost:8080/login?token=11 测试拦截器是否生效
http://localhost:8080/asyncPay?token=11 //测试接口调用是否使用了多线程
测试结果如下:
小知识
拦截器与过滤器之间有那些区别?
相同点:拦截器与过滤器都是基于Aop技术,对方法实现增强,都可以拦截请求方法。
不同点:
1.过滤器属于Servlet自己研发的,而拦截器技术属于SpringMVC自己研发的。
2.过滤器属于拦截Web请求,而拦截器不仅可以拦截请求还可以拦截普通方法。
3.过滤器会比拦截器先执行,拦截器封装的方法比过滤器拦截使用起来更加简单。
实际开发中绝大多数情况下,都会使用拦截器,
拦截器:权限控制、日志打印、参数验证 、会话。
过滤器应用场景:编码转换、跨域解决、xss攻击
SpringMVC项目中使用到多线程呢? 肯定是有。
为什么要使用多线程?提高我们响应的速度、异步执行。
在我们的Web中为什么要使用异步呢?
目的:快速响应给客户端,防止客户端请求等待的。
单独开启一个线程处理。
使用异步也有缺点:线程安全问题、不能及时拿到结果、消耗CPU
能够让耗时的时间,交给单独线程处理 也能够拿到异步线程结果