12-SpringBoot——Spring MVC基础-常用配置

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 // 1
public 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 !!!
 */
@Controller
public 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);
    }
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值