SpringBoot MVC 静态资源存放和访问
在SpringBoot中提供几个约定的静态资源存放路径。
src/main/resources/public (优先级最低)
src/main/resources/static
src/main/resources/resources
src/main/resources/META-INF/resources (优先级最高)
自定义静态资源路径,需要定义配置类
@Configuration
public class MyStaticConfiguration implements WebMvcConfigurer{
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/mystatic/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
); } }
SpringBoot MVC异常处理机制
SpringBoot底层提供了一个ErrorMvcAutoConfiguration自动配置组件,创建了一个BasicErrorController对象,该Controller提供了/error请求响应处理,当框架一旦捕获到程序异常就会自动转发/error请求,就会看到一个白板提示页面“Whitelabel Error Page”。
1.如果需要自定义异常界面,可以编写一个ErrorController覆盖底层自动配置BasicErrorController功能。
@Controller
public class MyErrorController implements ErrorController{
@RequestMapping("/error")
public ModelAndView errorHtml() {
ModelAndView mav = new ModelAndView();
mav.setViewName("myerror");
return mav; }
@Override
public String getErrorPath() {
return "/error"; } }
2.如果需要处理某一个或多个Controller中产生的异常,使用@ExceptionHandler标记
//在Controller类中添加下面的方法
@ExceptionHandler
@ResponseBody
public String errorException(Exception ex) {
return "发生异常:"+ex.getClass().getName();
}
如果需要重用,可以将该方法封装,采用继承形式使用。如果使用@ControllerAdvice表示所有Controller继承使用了。
@ControllerAdvice//等价于其他controller都继承BasicController
public class BasicController {
@ExceptionHandler
@ResponseBody
public String errorException(Exception ex) {
return "发生异常:"+ex.getClass().getName(); } }
SpringBoot MVC拦截器
1.编写拦截器组件,实现HandlerInterceptor接口
preHandle、postHandle、afterCompletion
@Component
public class CheckLoginInterceptor implements HandlerInterceptor{
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
Object user = request.getSession().getAttribute("user");
if(user == null) {
//设置响应界面
response.sendRedirect("/tologin");
return false;//表示未登录 }
return true;//表示已登录 }}
2.配置拦截器,实现WebMvcConfigurer接口
@Component
public class InterceptorConfiguration implements WebMvcConfigurer{
@Autowired
private CheckLoginInterceptor check;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(check).addPathPatterns("/**").excludePathPatterns("/tologin"); }}
SpringBoot Servlet/Filter
Filter使用
1.编写Filter组件,实现Filter接口
2.配置Filter组件
使用@Bean+FilterRegistrationBean配置
@Configuration
public class ServletConfiguration {
@Bean
public FilterRegistrationBean<Filter> checkLoginFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<Filter>();
bean.setFilter(new CheckLoginFilter());
List<String> urls = new ArrayList<String>();
urls.add("/*");
bean.setUrlPatterns(urls);
return bean; } }
提示:多个Filter执行顺序按bean.setOrder(1)指定。
使用@ServletComponentScan+@WebFilter配置
@WebFilter(filterName="checkLoginFilter",urlPatterns= {"/*"})
public class CheckLoginFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
String uri = httpRequest.getRequestURI();
if(!uri.equals("/tologin")) {
Object user = httpRequest.getSession().getAttribute("user");
if(user==null) {
//未登录
httpResponse.sendRedirect("/tologin");
return; } }
chain.doFilter(httpRequest, httpResponse); } }
启动类前面追加@ServletComponentScan
@SpringBootApplication
@MapperScan(basePackages= {"cn.xdl.dao"})
@ServletComponentScan//扫描servlet、filter、listener
public class RunBoot {
public static void main(String[] args) {
SpringApplication.run(RunBoot.class, args); } }
提示:多个Filter执行顺序按类名字典顺序调用。
SpringBoot Servlet
1.编写Servlet组件,继承HttpServlet
2.配置Servlet组件
使用@Bean+ServletRegistrationBean配置
@Bean
public ServletRegistrationBean<Servlet> someServlet(){
ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<Servlet>();
bean.setServlet(new SomeServlet());
bean.setLoadOnStartup(1);
List<String> urls = new ArrayList<String>();
urls.add("/some");
urls.add("/some.do");
bean.setUrlMappings(urls);
return bean; }
使用@ServletComponentScan+@WebServlet配置
@WebServlet(name="helloservlet",urlPatterns= {"/some","/some.do"})
public class SomeServlet extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println("Hello Servlet");
out.flush();
out.close(); } }