maven创建springBoot工程很简单:
File-->new-->project-->Spring Initializr-->next-->next-->web-->web
里面自动生成了一个启动类SpringbootExampleApplication:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootExampleApplication.class, args);
}
}
自定义一个Controller:
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello/{userId}")
public String say(@PathVariable("userId") Integer userId){
System.out.println("进入controller中的say方法");
return "Hello:" + userId;
}
@ResponseBody
@RequestMapping("/search")
public List<String> getAllInfo(){
List<String> res = new ArrayList<>();
res.add("wqh");
res.add("hello");
res.add("end");
return res;
}
}
右击SpringbootExampleApplication,选择Debug,发现tomcat已经启动。
测试均没问题:
http://localhost:8080/hello/4
http://localhost:8080/search
有时候需要自定义一个SpringBoot拦截器完成相关需求。
定义一个拦截器:
@Component
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
}
配置类:
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Autowired
MyInterceptor1 myInterceptor1;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor1).addPathPatterns("/**").excludePathPatterns("/search");//选择过滤的url请求
}
}
实现WebMvcConfigurer接口,不要继承WebMvcConfigurerAdapter这个类,因为该类已经过时,也不要继承WebMvcConfigurationSupport这个类,因为该类会使WebMvc自动失效。可参考:
https://blog.youkuaiyun.com/qq_35299712/article/details/80061532
参考: