12-SpringBoot——Spring MVC基础-常用配置
来源:互联网 发布:李小冉 知乎 编辑:程序博客网 时间:2024/05/16 23:54
Spring MVC基础-常用配置
【博文目录>>>】
【项目源码>>>】
【常用配置】
Spring MVC 的定制配置需要我们的配置类继承一个WebMvcConfigurerAdapter 类,并在此类使用@EnableWebMvc 注解,来开启对Spring MVC 的配置支持,这样我们就可以重写这个类的方法,完成我们的常用配置。
【静态资源映射】
程序的静态文件( js 、css 、图片)等需要直接访问,可以在配置里重写addResourceHandlers 方法来实现。我们在src/main/resources 下建立assets/js 目录,并复制一个jquery.js到此目录下。
【拦截器配置】
拦截器( Interceptor )实现对每一个请求处理前后进行相关的业务处理,类似于Serviet 的Filter 。可让普通的Bean 实现Hanlderlnterceptor 接口或者继承HandlerinterceptorAdapter 类来实现自定义拦截器。:通过重写WebMvcConfigurerAdapter的addInterceptors 方法来注册自定义的栏截器。
【@ControllerAdvice】
通过@ControllerAdvice ,我们可以将对于控制器的全局配置放置在同一个位置,注解了@Controller 的类的方法可使用@ExceptionHandler、@InitBinder、@ModelAttribute 注解到方法上,这对所有注解了@RequestMapping 的控制器内的方法有效。
@ExceptionHandler:用于全局处理控制器里的异常。
@InitBinder:用来设置WebDataBindcr, WebDataBinder用来自动绑定前台请求参数到Model 中。
@ModelAttribute:@ModelAttribute 本来的作用是绑定键值对到Model里,此处是让全局的@RequestMapping都能获得在此处设置的键值对。
【其他配置】
快捷的ViewController
配置页面转向的时候使用的如下代码
@RequestMapping(“/index”)public String hello() { return “index”;}
此处无任何业务处理,只是简单的页面转向,写了至少三行有效代码:在实际开发中会涉及大量这样的页面转向,若都这样写会很麻烦,我们可以通过在配置中重写addViewControllers来简化配置,这样实现的代码更简沽,管理更集中。
public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(“/index”).setViewName(“/index”);}
路径匹配参数配置
在Spring MVC 中,路径参数如果带“.”的话,“.”后面的值将被忽略,例如,访问http://localhost: 8080/springmvc/anno/pathvar/xx. yy ,此时“.”后面的yy 被忽略。通过重写configurePathMatch 方法可不忽略“.”后面的参数,这时再访问http://localhost: 8080/springmvc/anno/pathvar/xx. yy,就可以接受“.”后面的yy 了,代码如下。
public void configurePathMatch(PathMatchConfigurer configurer) { configure.setUserSuffixPattenMatch(false);}
更多配置可以查看WebMvcConfigurerAdapter 类。
【代码实现】
package com.example.spring.framework.mvc.configuration.advice;import org.springframework.ui.Model;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.context.request.WebRequest;import org.springframework.web.servlet.ModelAndView;/** * 1、@Controller Advice 声明一个控制器建言,@ControllerAdvice 组合了@Component 注解, * 所以自动注册为Spring 的Bean * 2、@ExceptionHandler 在此处定义全局处理,通@ExceptionHandler 的value 属性可过 * 滤拦截的条件,在此处我们可以看出我们拦截所有的Exception * 3、此处使用@ModelAttribute 注解将键值对添加到全局,所有注解的@RequestMapping * 的方法可获得此键值对。 * 4、通过@InitBinder 注解定制WebDataBinder * 5、此处演示忽略request 参数的id ,更多关于WebDataBinder 的自己置,请参考 * WebDataBinder 的API 文档。 * Author: 王俊超 * Date: 2017-07-12 07:28 * All Rights Reserved !!! */@ControllerAdvice // 1public class ExceptionHandlerAdvice { @ExceptionHandler(value = Exception.class) // 2 public ModelAndView exception(Exception exception, WebRequest request) { ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("errorMessage", exception.getMessage()); return modelAndView; } @ModelAttribute // 3 public void addAttributes(Model model) { model.addAttribute("msg", "额外信息"); //3 } @InitBinder //4 public void initBinder(WebDataBinder webDataBinder) { webDataBinder.setDisallowedFields("id"); //5 }}
package com.example.spring.framework.mvc.configuration.controller;import com.example.spring.framework.mvc.configuration.domain.DemoObj;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;/** * Author: 王俊超 * Date: 2017-07-12 07:32 * All Rights Reserved !!! */@Controllerpublic class AdviceController { @RequestMapping("/advice") public String getSomething(@ModelAttribute("msg") String msg, DemoObj obj) { throw new IllegalArgumentException("非常抱歉,参数有误/" + "来自@ModelAttribute:" + msg); }}
package com.example.spring.framework.mvc.configuration.domain;/** * Author: 王俊超 * Date: 2017-07-11 22:07 * All Rights Reserved !!! */public class DemoObj { private Long id; private String name; public DemoObj() { super(); } public DemoObj(Long id, String name) { super(); this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
package com.example.spring.framework.mvc.configuration.config;import com.example.spring.framework.mvc.configuration.interceptor.DemoInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.view.InternalResourceViewResolver;import org.springframework.web.servlet.view.JstlView;/** * Author: 王俊超 * Date: 2017-07-12 07:22 * All Rights Reserved !!! */@Configuration@EnableWebMvc@ComponentScan("com.example.spring.framework.mvc.configuration")public class MyMvcConfig extends WebMvcConfigurerAdapter{ @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/"); super.addResourceHandlers(registry); } // 1 @Bean public DemoInterceptor demoInterceptor() { return new DemoInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) {// 2 registry.addInterceptor(demoInterceptor()); }}
package com.example.spring.framework.mvc.configuration.interceptor;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Author: 王俊超 * Date: 2017-07-12 07:26 * All Rights Reserved !!! */public class DemoInterceptor extends HandlerInterceptorAdapter{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime = System.currentTimeMillis(); request.setAttribute("startTime", startTime); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute("startTime"); request.removeAttribute("startTime"); long endTime = System.currentTimeMillis(); System.out.println("本次请求处理时间为:" + new Long(endTime - startTime)+"ms"); request.setAttribute("handlingTime", endTime - startTime); }}
package com.example.spring.framework.mvc.configuration;import com.example.spring.framework.mvc.configuration.config.MyMvcConfig;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration;/** * Author: 王俊超 * Date: 2017-07-11 21:51 * All Rights Reserved !!! */public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(MyMvcConfig.class); ctx.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); }}
- 12-SpringBoot——Spring MVC基础-常用配置
- 11-SpringBoot——Spring MVC基础-常用注解
- 13-SpringBoot——Spring MVC基础-高级配置-文件上传
- 14-SpringBoot——Spring MVC基础-自定义HttpMessageConverter
- 15-SpringBoot——Spring MVC基础-服务端推送技术
- 16-SpringBoot——Spring MVC基础-测试
- 04-SpringBoot——Spring常用配置-Bean的Scope
- 07-SpringBoot——Spring常用配置-Profiles
- 08-SpringBoot——Spring常用配置-事件
- 02-SpringBoot——Spring基础-Java配置
- SpringBoot系列—基础配置
- spring mvc常用配置
- spring mvc 基础配置
- 十、SpringBoot的Spring MVC自动配置
- 05-SpringBoot——Spring常用配置-Spring EL和资源调用
- 03-SpringBoot——Spring基础-AOP
- 06-SpringBoot——Spring常用配置-Bean的初始化和销毁
- spring mvc 三个常用配置
- css3元素向上移动
- R实战:【I/O】文本文件与因子转换
- 最佳调度问题
- VMware12安装Linux7系统进而安装Oracle12c中遇到的问题
- Java 写有n个人围成一圈,顺序排号,从第一个人开始报数(从1~3报数),凡报到3的人退出圈子,问最后留下的人原来排在第几号。
- 12-SpringBoot——Spring MVC基础-常用配置
- Mysql的高可用MHA实现
- web.xml与注解配置servlet使用介绍
- QThread的细节描述(Detailed Description)翻译
- eclipse自动提示设置以及问题:去除变量自动提示(图文详解)
- 7.16
- 分块(有理有据的暴力)
- 7.17
- 7.20