首页
学习
活动
专区
圈层
工具
发布

《Springboot极简教程》继承WebMvcConfigurerAdapter: 一行代码写Controller文章概要常用的写Controller类方法继承 WebMvcConfigurerAd

文章概要

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

常用的写Controller类方法

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

代码语言:javascript
复制
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
@ComponentScan
public class LoginController {

    @RequestMapping("/login")
    public String login(Map<String, Object> model) {
        return "login";
    }
}

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

继承 WebMvcConfigurerAdapter的Controller写法

代码语言:javascript
复制
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
 */
@Configuration
public 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

下一篇
举报
领券