SpringMVC-08-SpringMVC层编写

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

原文地址:https://www.cnblogs.com/CodeHuba/p/13656465.html