SpringMVC入门及拦截器

neweastsun 2019-11-11

   SSM最后一个框架springmvc,其实上手特别简单。但是我昨天看一个深入源码的视频,差点GG。其实以前学过很多东西,都忘了,不敢说学会,现在有了本书,看过一遍之后。多多少少记住一些,权当我会用了,不敢说精通。

本周计划,今天把springmvc搞完,明天搭建一个SSM项目,by the way 其实我毕设就是SSM项目。周三复习Maven,周四复习Redis,周五开始做SSM+Redis整合。下周开搞SSH,最后学习SpringBoot。这个月的主要事情就是学习框架。

springmvc的实际容器类是XmlWebApplicationContext。在web.xml文件中,如果我们使用idea的新建springmvc项目功能,会自动进行简单配置,非常聪明,我们一般需要进行字符过滤器CharacterEncoderingFilter的设置,启动参数context-param,来启动spring容器,spring容器是一个大的容器,包含springmvc容器。

web.xml配置如下

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>encoder</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>encoder</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

dispatcher-servlet.xml配置如下,也就是springmvc的配置,主要功能是

  • sao描控制器上的注解,把他们加入springmvc容器
  • <mvc:annotataion-driven/>启用默认的HandlerMapping,HandlerAdator,
  • <mvc:interceptors>配置拦截器
  • 配置视图解析器,这个功能更常用
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.houjun.controller"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

applicationContext.xml配置,这个是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 http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="com.houjun.pojo"></context:component-scan>
</beans>

一个简单的控制器如下

package com.houjun.controller;

import com.houjun.pojo.Student;
import com.houjun.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: HouJun
 * @Date: 2019/11/8 15:21
 * @Description: com.houjun.controller
 * @version: 1.0
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private Student student;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
   private ConfigurableWebApplicationContext configurableWebApplicationContext;
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("自动注入"+student);
        System.out.println("className"+applicationContext.getClass().getName());
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
        System.out.println("--------------------------------------------------------------------------------------");
        System.out.println("className"+configurableWebApplicationContext.getClass().getName());
        String[] beanDefinitionNames1 = configurableWebApplicationContext.getBeanDefinitionNames();
        for (String s : beanDefinitionNames1) {
            System.out.println(s);
        }
        return "/success.jsp";
    }
}

拦截器类,拦截器需要实现一个接口 HandlerInterceptorAdapter,可以有多个拦截器,拦截顺序以xml文件配置顺序为准,代码如下

package com.houjun.inerceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: HouJun
 * @Date: 2019/11/11 9:58
 * @Description: com.houjun.inerceptor
 * @version: 1.0
 */

public class UserInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("自定义拦截器1,进入控制器之前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("自定义拦截器1,控制器之后,进入视图之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("自定义拦截器1,控制器之后,进入视图之后");
    }
}

目录结构

SpringMVC入门及拦截器

  

有了这些东西,就能启动一个web项目了,需要注意的是,配置Project Stucture -->Libraries和Tomcat容器之时可能会有各种问题,不过慢慢来,一点一点就是知道配置这些的含义了。

相关推荐