使用web.xml配置SpringMvc(使用Java加载配置)

2020-09-20 20:25:05 浏览数 (1)

一、配置web.xml

代码语言:javascript复制
<!--使用Java配置-->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <!--指定根配置类-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.spittr.config.RootConfig</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoader</listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <!--使用Java配置-->
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--指定DispatcherServlet配置类-->
            <param-value>com.spittr.config.WebConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

二、配置RootConfig

代码语言:javascript复制
@Configuration
@ComponentScan(basePackages = "com.spittr",
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value= EnableWebMvc.class)})
public class RootConfig {
}

三、配置WebConfig

代码语言:javascript复制
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.spittr")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setExposeContextBeansAsAttributes(true);

        registry.viewResolver(viewResolver);
    }
}

四、编写controller和jsp来测试

HelloController:

代码语言:javascript复制
@Controller
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(){
        System.out.println("进入了hello方法");

        return "hello";
    }
}

hello.jsp:

代码语言:javascript复制
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>Welcome to SpringMvc</h1>

</body>
</html>

0 人点赞