1. 程式人生 > >【SpringMVC】【web和ApplicationContext.xml檔案的配置】

【SpringMVC】【web和ApplicationContext.xml檔案的配置】

使用的包

這裡寫圖片描述

web.xml

  • 啟動伺服器時候,啟動Spring容器
  • utf-8配置
<web-app>

<!-- 配置前端控制器 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 宣告Spring容器的配置檔案位置 -->
<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!-- 宣告在伺服器啟動時候,就啟動Spring容器 --> <load-on-startup>1</load-on-startup
>
</servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- utf-8的過濾器 --> <filter> <filter-name>characterEncoding</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> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

applicationContext.xml

  • 匯入mvc的名稱空間
  • 防止處理靜態資源(即可以直接訪問的jsp無法訪問)
  • 註解宣告
  • 檢視解析器
 xmlns:mvc="http://www.springframework.org/schema/mvc"

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    <!-- 防止DispatcherServlet處理靜態資源 -->
    <mvc:default-servlet-handler/>

    <!-- annotation -->
    <context:annotation-config />
    <mvc:annotation-driven/>    <!-- 對Springmvc註解的支援 -->
    <context:component-scan base-package="com.lwf.MVC.controller"/>

    <!--檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

controller類上的註解

@Controller  //表示注入到Spring容器
public class TextController {

    @RequestMapping("/method1") //訪問的資源名是method1
    public ModelAndView method1(HttpServletRequest req) throws Exception{

        return null;

    }
}