《Springboot极简教程》继承WebMvcConfigurerAdapter: 一行代码写Controller

来源:互联网 发布:ubuntu wget安装 编辑:程序博客网 时间:2024/05/22 05:30

文章概要

registry.addViewController("/login").setViewName("login");

常用的写Controller类方法

我们通常这样写一个直接跳转view的Controller

package com.restfeel.controller;import java.util.Map;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.annotation.ComponentScan;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@EnableAutoConfiguration@ComponentScanpublic class LoginController {    @RequestMapping("/login")    public String login(Map<String, Object> model) {        return "login";    }}

要添加一个新页面访问总是要新增一个Controller或者在已有的一个Controller中新增一个方法,然后再跳转到设置的页面上去。考虑到大部分应用场景中View和后台都会有数据交互,这样的处理也无可厚非,不过我们肯定也有只是想通过一个URL Mapping然后不经过Controller处理直接跳转到页面上的需求!

继承 WebMvcConfigurerAdapter的Controller写法

package com.restfeel.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * Created by jack on 2017/3/28. * WebMvcConfig配置总类 * * @author jack * @date 2017/03/28 */@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter {    @Override    public void addViewControllers(ViewControllerRegistry registry) {        //这一段等同于com.restfeel.controller.LoginController,静态资源的拦截处理在com.restfeel.config.security.SecurityConfig设置        registry.addViewController("/login").setViewName("login");    }}

这一段等同于com.restfeel.controller.LoginController,静态资源的拦截处理在com.restfeel.config.security.SecurityConfig设置。

源码:https://github.com/Jason-Chen-2017/restfeel/blob/master/src/main/java/com/restfeel/config/WebMvcConfig.java

阅读全文
0 0
原创粉丝点击