1. 程式人生 > >SpringMVC 基本配置

SpringMVC 基本配置

解析 res 項目 interval list 1.0 name 地址 util

<一> 配置 WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID"
version="3.1" > <!-- 配置項目名稱 --> <display-name>WebStudy</display-name> <!-- 配置 LOG4J 日誌 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:config/log4j.properties</param-value>
</context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class
> </listener> <!-- 配置 DispatcherServlet --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置 DispatcherServlet 的 SpringMVC 配置文件在 SRC 下的全路徑 classpath:config/spring.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置 DispatcherServlet 應答所有請求 --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

< 二 > 配置 SpringMVC

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置自動掃描的包 -->
    <context:component-scan base-package="spring_mvc"></context:component-scan>
    
    <!-- 配置視圖解析器, 配置後 訪問的地址為: /WEB-INF/vie/控制器方法的返回值.jsp-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/vie/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

< 三 > 控制器類

package spring_mvc;

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

@Controller  //註釋為控制器
public class HelloWorld {
    
    /**
     * @RequestMapping 註解, 映射 URL 請求
     */
    @RequestMapping("/main")
    public String demo1(){
        return "main";
    }
    
}

< 四 > 在WEB-INF下創建vie目錄, 並創建和方法返回值同名的 .jsp 文件

< 五 > SpringMVC 架構圖

技術分享

SpringMVC 基本配置