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

时间:2022-07-25
本文章向大家介绍使用web.xml配置SpringMvc(使用Java加载配置),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、配置web.xml

<!--使用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

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

三、配置WebConfig

@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:

@Controller
public class HelloController {

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

        return "hello";
    }
}

hello.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>Welcome to SpringMvc</h1>

</body>
</html>