SpringMVC-08-SpringMVC層編寫

CodeHuba發表於2020-09-12

SpringMVC層編寫

web.xml

  • DispatcherServlet

    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
  • 亂碼問題

    <!--亂碼過濾-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  • Session

    <!--Session-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    

spring-mvc.xml

  • 註解驅動

    <!--1. 註解驅動-->
    <mvc:annotation-driven/>
    
  • 靜態資源過濾

    <!--2. 靜態資源過濾-->
    <mvc:default-servlet-handler/>
    
  • 掃描包

    <!--3. 掃描包:controller-->
    <context:component-scan base-package="com.kuang.controller"/>
    
  • 檢視解析器

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

Spring配置整合檔案

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>

</beans>

排錯思路

問題1:bean不存在

步驟:

  1. 檢視這個bean注入是否成功

  2. junit單元測試,觀察程式碼是否可以查詢出結果

  3. 前兩步都沒問題的話,問題不在我們的底層,是spring出了問題

  4. springMVC整合的時候沒有呼叫到service層的bean:

    • applicationContext.xml沒有注入bean

    • web.xml中,我們也繫結過配置檔案!發現問題,我們配置的是spring-mvc.xml,這裡確實沒有service bean,所以報空指標。

問題2:http://localhost:8080/book/allBook 404

原因:applicationContext.xml沒有import spring-mvc.xml

相關文章