美文网首页Spring-BootSpring Boot征服Spring
朝花夕拾之Spring WebMVC (Java config)

朝花夕拾之Spring WebMVC (Java config)

作者: Tony_HQ | 来源:发表于2016-10-20 11:27 被阅读0次

继上一篇配置好Spring framework, 现在接入Spring Web MVC。

顺序如下

  1. 修改pom.xml+Maven Tomcat Plugins+web.xml(配置了2就不用配置这个)
  2. 添加WebMVCInitializer
  3. 修改Application.java(Spring framework的配置)配置webMVC, 修改 configureMessageConverters,建立JSON 自动映射(使用Fastjson)
  4. 路由实例

pom.xml

        //主库
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>

配置Maven自启动tomcat

<build>
        <pluginManagement>
            <plugins>
                <!-- junit plugins-->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat6-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <url>http://localhost:8080</url>
                        <server>tomcat</server>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <url>http://localhost:8080</url>
                        <server>tomcat</server>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

新建web.xml,在/web/WEB-INF下,或者修改对应路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

博主用的是IntelliJ IDEA,所以修改Module Setting, output path 到/web/WEB-INF-classes

新建WebMVCIniatializer.java

public class WebMVCIniatializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{
            Application.class
        };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{
                "/"
        };
    }
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addListener(new SessionListener());
    }
}

其中servletContext.addListener(new SessionListener());
可以不加,自己需要什么样的Listener自己添加。

修改Application.java主要三个步骤

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableSpringConfigured
@ComponentScan("jufou.info.*")
@EnableWebMvc
public class Application  extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter4=new FastJsonHttpMessageConverter4();
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setFeatures(Feature.IgnoreNotMatch);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        fastJsonHttpMessageConverter4.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter4);
        super.configureMessageConverters(converters);
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
        configurer.enable();
    }
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        commonsMultipartResolver.setMaxUploadSize(-1);
        commonsMultipartResolver.setMaxUploadSizePerFile(-1);
        return commonsMultipartResolver;
    }
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .setUseSuffixPatternMatch(true)
                .setUseTrailingSlashMatch(false)
                .setUseRegisteredSuffixPatternMatch(true);
    }

}

1.主要添加@EnableWebMvc
2.添加Bean multipartResolver 用以处理Multipart 请求
@Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        commonsMultipartResolver.setMaxUploadSize(-1);
        commonsMultipartResolver.setMaxUploadSizePerFile(-1);
        return commonsMultipartResolver;
    }
3.configureMessageConverters
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter4=new FastJsonHttpMessageConverter4();
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setFeatures(Feature.IgnoreNotMatch);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        fastJsonHttpMessageConverter4.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter4);
        super.configureMessageConverters(converters);
    }

至此基本完成Spring WebMVC的配置。

最后测试类,写路由配置

@RestController
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @RequestMapping(method= RequestMethod.GET,value="/user/nickname/{id}")
    public void printUserNickname(@PathVariable long id) {
        System.out.println(userService.getUserNickname());
    }

    @RequestMapping(method= RequestMethod.PUT,value="/user",consumes = "application/json")
    public void putUserNickname(@RequestBody User user {
        System.out.println(user.getUserNickname());
    }
}

相关文章

网友评论

    本文标题:朝花夕拾之Spring WebMVC (Java config)

    本文链接:https://www.haomeiwen.com/subject/agdfuttx.html