欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring in Action(五):基于Java Config的SpringMVC

程序员文章站 2024-02-15 12:09:46
...

1、搭建SpringMVC项目

可参考搭建Spring项目教程:http://blog.csdn.net/lom9357bye/article/details/72796668

pom文件如下

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.learning</groupId>
    <artifactId>springmvc-learning</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>springmvc-learning Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>

        <!--使用单元测试所需jar包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>

        <!--spring相关包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>


        <!--jstl-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>springmvc-learning</finalName>
    </build>
</project>

2、由于使用java文件进行配置,所以可以将web.xml清空

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">


</web-app>

3、在java目录下创建包,并创建一个RootConfig和WebConfig类

4、创建一个初始化配置的类SpittrWebAppInitializer,并继承AbstractAnnotationConfigDispatcherServletInitializer

package com.learn.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 继承AbstractAnnotationConfigDispatcherServletInitializer的类会自动配置DispatcherServlet和spring应用上下文
 * 1.在Servlet 3.0中,容器会在类路径中查找实现ServletContainerInitializer接口的类,并用它来配置Servlet容器
 * 2.Spring中有ServletContainerInitializer接口的实现,名为SpringServletContainerInitializer,这个类又会查找实现WebApplicationInitializer的类并将配置任务交给它们来完成
 * 3.AbstractAnnotationConfigDispatcherServletInitializer是WebApplicationInitializer的实现类,而我们的配置类SpittrWebAppInitializer又继承了它
 * 4.因此可以使用我们的配置类来配置Servlet上下文
 * spring in action
 */
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    protected String[] getServletMappings() {
        //将DispatcherServlet映射到"/",相当于web.xml中配置的servlet-mapping
        return new String[]{"/"};
    }
}

5、WebConfig类中配置视图解析器

package com.learn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Configuration//将类作为配置配
@EnableWebMvc//启用SpringMVC
@ComponentScan("com.learn.controller")//启用组件扫描
public class WebConfig extends WebMvcConfigurerAdapter{

    //注册一个ViewResolver视图解析器bean,配置JSP视图解析器
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver=new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    //配置静态资源的处理,要求DispathServlet将对静态资源的请求转发到Servlet容器中默认的servlet
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
        configurer.enable();
    }
}

6、RootConfig

package com.learn.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;


@Configuration
@ComponentScan(basePackages = "com.learn",excludeFilters = {
        @Filter(type=FilterType.ANNOTATION,value= EnableWebMvc.class)
})
public class RootConfig {
}

7、现在springmvc项目所需要的基本配置已经配置完毕,接下来创建一个HelloController

package com.learn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller//将此类作为控制器
public class HelloController {

    @RequestMapping(value="/hello")//设置请求映射,处理对"/hello"的请求
    public String hello(){
        return "hello";//视图名为hello,视图解析器会寻找WEB-INF/views/hello.jsp
    }
}

8、在WEB-INF/下建一个views文件夹,并在views目录下建一个hello.jsp

<html>
<body>
<h2>hello spring mvc</h2>
</body>
</html>


9、启动Tomcat

输入http://localhost:8080/hello进行测试

Spring in Action(五):基于Java Config的SpringMVC

注:在配置Tomcat时,ApplicationContext设为了/,因此可以直接通过http://localhost:8080/访问项目,而不需要带上项目名称

Spring in Action(五):基于Java Config的SpringMVC


10、使用mock进行单元测试

package com.learn.controller;

import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceView;


public class HelloControllerTest {

    @Test
    public void helloTest() throws Exception{
        HelloController controller=new HelloController();
        MockMvc mockMvc= MockMvcBuilders.standaloneSetup(controller).setSingleView(new InternalResourceView("/WEB-INF/views/hello.jsp")).build();
        mockMvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.view().name("hello"));
    }
}


参考:Spring in Action