Spring Boot 2.x 页面跳转,重定向和请求转发使用方法,简单配置不用写Controller

@Configuration
public class MyConfig implements WebMvcConfigurer {
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/register").setViewName("register");
        //添加url路径,设置url对应的页面
        //访问http://localhost:8080/toIndex,请求转发到http://localhost:8080/index这个页面
        registry.addViewController("/toIndex").setViewName("index");
        registry.addViewController("/header").setViewName("header");

        /*
        这个是重定向,比如访问http://localhost:8080,
        链接会重定向到http://localhost:8080/index,
        第一个参数是URL路径(你浏览器访问的地址),第二个是参数也是url路径,
        不过是上面配置好的url(就是上面addViewController里的玩意),
        它会访问映射的页面index.html(index.jsp,index.ftl)等等,前提是放在templates下的页面


        实际流程就是访问http://localhost:8080 ---> http://localhost:8080/toIndex ---> 
        ---> http://localhost:8080/index
        */
        registry.addRedirectViewController("/","/toIndex");
    }
}

 

Spring Boot中,创建一个简单的RESTful控制器并实现页面跳转通常涉及到以下几个步骤: 1. **添加依赖**: 首先,你需要在`pom.xml`文件中添加Spring Web依赖,这将提供处理HTTP请求的能力以及支持模板引擎(如Thymeleaf)用于渲染HTML页面。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. **创建Controller**: 创建一个新的Java类,让它继承自`Spring MVC`的`RestController`,或者如果你想要更现代的风格,可以继承`WebFluxController`。这里我们用传统的`@RestController`为例。 ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PageController { @GetMapping("/redirect") public String redirectToLoginPage() { return "redirect:/login"; // 返回一个URL,告诉浏览器重定向到登录页面 } } ``` 上面的`@GetMapping("/redirect")`是一个HTTP GET映射,当访问`/redirect`路径时,它会返回一个重定向到"/login"的响应。 3. **设置视图解析器**: 如果你想使用Thymeleaf等模板引擎,需要配置Spring MVC的视图解析器。在`application.properties`或`application.yml`中添加如下内容: ```properties spring.mvc.view.prefix=/templates/ spring.mvc.view.suffix=.html ``` 这表示视图文件位于`src/main/resources/templates/`目录下,后缀名为`.html`。 4. **测试应用**: 启动你的Spring Boot应用,并通过浏览器访问`http://localhost:8080/redirect`,你应该能看到浏览器被重定向到`http://localhost:8080/login`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值