07_SpringBoot的web开发

2017-11-11  本文已影响0人  对方不想理你并向你抛出一个异常

Spring Boot的web开发

spring-boot-autoconfigure-1.5.2.RELEASE.jar中,
Web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration

自动配置的ViewResolver


视图的配置mvcProperties对象中:
org.springframework.boot.autoconfigure.web.WebMvcProperties.View
"NoHandlerFoundException" should be thrown if no Handler was found to process a request.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

自动配置静态资源

自定义消息转化器

自定义消息转化器,只需要在@Configuration的类中添加消息转化器的@bean加入到Spring容器,就会被Spring Boot自动加入到容器中。

    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter(){
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

默认配置:



自定义SpringMVC的配置

有些时候我们需要自已配置SpringMVC而不是采用默认,比如说增加一个拦截器,这个时候就得通过继承WebMvcConfigurerAdapter然后重写父类中的方法进行扩展。

package cn.huachao.springboot.controller;

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

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MySpringMVCConfig extends WebMvcConfigurerAdapter{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("自定义拦截器............");
                return true;
            }
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                        ModelAndView modelAndView) throws Exception {
                
            }
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                    Exception ex)throws Exception {
                
            }
        };
        registry.addInterceptor(handlerInterceptor);
    }

  // 自定义消息转化器的第二种方法
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(converter);
    }
    
}
上一篇 下一篇

猜你喜欢

热点阅读