Spring MVC 全注解配置

  时间:2018-11-07
本文章向大家介绍Spring MVC 全注解配置 ,需要的朋友可以参考一下

父级的pom配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.nf</groupId>
    <artifactId>springmvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>ch01</module>
        <module>ch02</module>
        <module>ch03</module>
        <module>ch04</module>
        <module>ch05</module>
        <module>ch06</module>
        <module>ch07</module>
        <module>ch08</module>
        <module>ch09</module>
        <module>ch10</module>
        <module>ch11</module>
    </modules>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        <!-- spring版本 -->
        <spring.version>5.1.1.RELEASE</spring.version>
        <servlet.version>4.0.1</servlet.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Spring mvc依赖,会传递依赖context、core等核心包-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

    <!-- war插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <warSourceDirectory>web</warSourceDirectory>
                    <!-- 指定web.xml路径 -->
                    <!--<webXml>webWEB-INFweb.xml</webXml>-->
                    <!-- 打包时忽略web.xml文件-->
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
View Code

子级的pom(ch11)配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springmvc</artifactId>
        <groupId>edu.nf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>ch11</artifactId>
    <packaging>war</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.13.Final</version>
        </dependency>
    </dependencies>

</project>
View Code

取代web.xml的配置类

 

package edu.nf.ch11.config;

import edu.nf.ch11.filter.EncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;

/**
 * @author wangl
 * @date 2018/11/6
 * 取代web.xml
 */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    /**
     * 指定mvc的核心配置类
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    /**
     * 等同于将DispatcherServlet的url-pattern设置为"/"
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 也可以在onStartup中可以添加自定义的Servlet、Listener、Filter
     * 这里以添加过滤器为演示
     * addMappingForUrlPatterns方法参数说明:
     * 参数一: 请求过滤的类型,如果要使用默认的EnumSet.of(DispatcherType.REQUEST)(表示过滤所有的请求),则为null
     * 参数二: 如果给定的过滤器映射应在其他任何声明的过滤器映射之后匹配,则为true;
     *         如果在获得此FilterRegistration的ServletContext的任何已声明过滤器映射之前应该匹配,则为false
     * 参数三: 过滤器映射的url
     * @param servletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addFilter("encodingFilter", EncodingFilter.class)
                .addMappingForUrlPatterns(null, false, "/*");
        //必须调用回父类的onStartup方法,否则不会初始化DispatcherServlet
        super.onStartup(servletContext);
    }
}

 

mvc配置类,取代dispatcher-servlet.xml

 

package edu.nf.ch11.config;

import edu.nf.ch11.interceptors.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author wangl
 * @date 2018/11/6
 * mvc配置类,取代dispatcher-servlet.xml
 */

/**
 * 声明配置类
 */
//@Configuration
/**
 * 启用包扫描
 */
@ComponentScan(basePackages = "edu.nf.ch11")
/**
 * 启用mvc注解驱动
 */
@EnableWebMvc
/**
 * 如果需要扩展webmvc配置,可以实现WebMvcConfigurer接口,
 * 覆盖相关的default方法
 */
public class WebConfig implements WebMvcConfigurer {


    /**
     * 配置静态资源处理方式一:使用容器的默认Servlet处理
     */
    /*@Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        //启用默认Servlet支持
        configurer.enable();
    }*/

    /**
     * 配置静态资源处理方式二:springmvc处理静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("/static/");
    }

    /**
     * 添加拦截器
     * addInterceptor方法指定自定义拦截器对象
     * addPathPatterns方法指定哪些请求经过拦截器
     * excludePathPatterns方法指定哪些请求放行
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).
                addPathPatterns("/**").
                excludePathPatterns("/static/login.html","/static/js/**","/userLogin");
    }

    /**
     * 配置commons-upload上传
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        //设置限制上传大小
        resolver.setMaxUploadSize(104857600);
        //设置编码
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }

    /**
     * 配置默认的视图解析器
     */
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        //如果页面需要使用JSTL标签库
        //viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }
}

 

BaseController:

package edu.nf.ch11.controller;

import edu.nf.ch11.controller.vo.ResponseVO;

/**
 * @author wangl
 * @date 2018/11/6
 */
public class BaseController {

    protected ResponseVO success(Object value){
        ResponseVO vo = new ResponseVO();
        vo.setValue(value);
        return vo;
    }

    protected ResponseVO success(){
        ResponseVO vo = new ResponseVO();
        return vo;
    }

    protected ResponseVO error(int code, String message){
        ResponseVO vo = new ResponseVO();
        vo.setCode(code);
        vo.setMessage(message);
        return vo;
    }
}
View Code

UserController:

package edu.nf.ch11.controller;

import edu.nf.ch11.controller.vo.ResponseVO;
import edu.nf.ch11.entity.Users;
import edu.nf.ch11.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author wangl
 * @date 2018/11/6
 */
@Controller
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @PostMapping("/userLogin")
    public @ResponseBody ResponseVO login(Users user, HttpSession session){
        user = userService.getUser(user);
        session.setAttribute("user", user);
        return success("/static/index.html");
    }
}
View Code

EncodingFilter:

package edu.nf.ch11.filter;

import org.springframework.context.annotation.ComponentScan;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author wangl
 * @date 2018/11/6
 */
//@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("字符过滤器...");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        //请求放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
View Code

 

原文地址:http://www.manongjc.com/article/17692.html