随笔 - 8  文章 - 0  评论 - 2 

spring 框架集成springMvc (二) java 配置方式

本文章将介绍使用java 配置的方式,代替xml的实现方式。

1.使用idea创建maven project

点击next

点击next -->finish。最终生成的工程目录结构如下:

2.修改pom.xml文件

添加

<packaging>war</packaging>

添加依赖

   <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
    </dependencies>

3.创建包目录结构

com.feiyuxuy.config、controller、service

4.创建配置类

@Configuration
@ComponentScan(basePackages = "com.feiyuxuy",useDefaultFilters = true,
        excludeFilters = {@ComponentScan.Filter(type =FilterType.ANNOTATION,classes = Controller.class
)})
public class SpringConfig {
}

@Configuration
@ComponentScan(basePackages = "com.feiyuxuy",useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class),
                @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Configuration.class)
})
public class SpringMvcConfig {
}
/** 类似web.xml 功能
 * 加载配置文件
 */
public class WebInit implements WebApplicationInitializer {


    @Override
    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);
    }
}

5.创建 controller 和service

@RestController
public class HelloController {

   @GetMapping("/hello")
    public  String hello(){
        return "hello";
    }
}
@Service
public class HelloService {

    public String sayHello() {
        return  "hello";
    }
}

6.测试

配置项目到tomcat中,配置过程详见上一篇文章。

地址栏输入http://localhost:8080/hello显示如图:

7.添加静态资源过滤

7.1在resource 目录下 新建 static目录,在目录中添加hello.html

7.2改造 SpringMvcConfig.java

@Configuration
@ComponentScan(basePackages = "com.feiyuxuy",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/");
    }
}

7.3 测试

http://localhost:8080/static/hello.html

效果如图:

8.创建拦截器

8.1 编写拦截器代码

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

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

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

8.2 配置拦截器

修改SpringMvcConfig.java

@Configuration
@ComponentScan(basePackages = "com.feiyuxuy",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();
    }
}

9.配置fastjson

对fastjson没有默认支持,需要手动配置

9.1 引入 fastjson maven配置

  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>

9.2在SpringMvcConfig.java中 添加消息转换配置

  /**
     * 添加fastjson配置
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
        converters.add(converter);
    }

9.3 编写测试

   @GetMapping("/getJsonData")
    public List<String> getJsonData(){
       List list=new ArrayList();
       for(int i=0;i<10;i++){
           list.add("this is json "+i);
       }
       return list;
    }

输入http://localhost:8080/getJsonData测试返回数据。

如果对您有帮助,请点推荐支持一下。

源代码下载地址:
链接:https://pan.baidu.com/s/1IxrLWT_QJnYtFxVkSbCmSQ
提取码:xsyu

posted on 2020-08-23 13:24  飞鱼xuy  阅读(59)  评论(0编辑  收藏