目录结构

.
├── pom.xml
├── spring+SpringMVC(anno).iml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── edu
│   │   │   └── lapponia
│   │   │   ├── config
│   │   │   │   ├── SpringConfig.java
│   │   │   │   ├── SpringMVCConfig.java
│   │   │   │   └── WebInit.java
│   │   │   ├── controller
│   │   │   │   └── HelloController.java
│   │   │   ├── interceptor
│   │   │   │   └── MyInterceptor.java
│   │   │   └── service
│   │   │   └── HelloService.java
│   │   └── resources
│   │   └── static
│   │   └── hello.html
│   └── test
│   └── java

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.lapponia</groupId>
    <artifactId>spring+SpringMVC(anno)</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>
</project>

SpringConfig.java

package edu.lapponia.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

/**
 * 注解所需设置的东西和使用xml配置的内容一致:扫描的包,扫描的文件
 */
@Configuration
@ComponentScan(basePackages = "edu.lapponia", useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type =
        FilterType.ANNOTATION, classes = Controller.class)})
public class SpringConfig {
}

SpringMVCConfig.java

package edu.lapponia.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import edu.lapponia.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * 在SpringMVC的配置文件中不仅扫Controller,也扫Configuration,否则Spring的配合文件不会被加载
 */
@Configuration
@ComponentScan(basePackages = "edu.lapponia", useDefaultFilters = false, includeFilters = {@ComponentScan.Filter(type =
        FilterType.ANNOTATION, classes = Controller.class), @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)})
public class SpringMVCConfig extends WebMvcConfigurationSupport {
// 扫描静态资源目录
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 一个*表示单层路径两个*表示任意多
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
    }

    @Bean
    MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converters.add(converter);
    }
}

WebInit.java

package edu.lapponia.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 在项目启动时使用上下文加载SpringMVCConfig
 */
public class WebInit implements WebApplicationInitializer {
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.setServletContext(servletContext);
        ctx.register(SpringMVCConfig.class);
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        springmvc.addMapping("/");
        springmvc.setLoadOnStartup(1);
    }
}

HelloController.java

package edu.lapponia.controller;

import edu.lapponia.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String hello() {
        return helloService.sayHello();
    }

    @GetMapping("/get")
    public List<String> getData() {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add("num" + i);
        }
        return list;
    }
}

MyInterceptor.java

package edu.lapponia.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//*
* 配置拦截器
*//
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandler");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

HelloService.java

package edu.lapponia.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String sayHello() {
        return "hello java ssm";
    }
}


Last modification:April 2nd, 2020 at 05:12 pm
If you think my article is useful to you, please feel free to appreciate