spring mvc

使用idea 搭建一个spring web 项目,spring boot 也行,反正是温故学习,弄明白就好。

MVC 配置:

@Configuration
@EnableWebMvc
@ComponentScan("com.duoke.demo")
public class SpringMvcConfig {

//    配置解析器Bean
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("WEB-INF/classes/views");
        viewResolver.setSuffix(".html");
//        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }
}

对于使用@Controller 注解声明的类,servlet 会自动扫描注解了此注解的类。

在作为控制器的时候只能使用它。

 

@RequestMapping

映射web请求,路径及参数

@RequestBody

响应body,返回一在一个响应内容

@RequestBody

请求参数

@PathVariable

接收路径参数,类似rest请求的路径参数。

@RestController

组合注解(Controller 与 ResponserBody)

 

拦截器:配置拦截器CustomInter,在配置中注册拦截器

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(new CustomInter());
        registration.addPathPatterns("/**");
        registration.excludePathPatterns("/","/login","/error");
    }
}
    @Override
//    请求发生前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("start",startTime);
        return super.preHandle(request, response, handler);
    }

    @Override
//    请求发生后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long) request.getAttribute("start");
        long endTme = System.currentTimeMillis();
        System.out.println(endTme - startTime);
        request.removeAttribute("start");
        super.postHandle(request, response, handler, modelAndView);
    }

 

控制转向(针对重定向的页面使用方便)

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/login");
    }

 

EventSource

SSR (server - sent event)

http://javascript.ruanyifeng.com/htmlapi/eventsource.html

 

posted @ 2019-08-13 23:48  李鹏飞ONLINE  阅读(136)  评论(0编辑  收藏  举报