Python 官方文档:入门教程 => 点击学习
目录SpringBoot跳转到指定页面controller的写法springboot重定向和请求转发springboot重定向springboot的请求转发springboot转发和
必须是templates下面的页面,不经过配置,无法直接跳转到public,static,等目录下的页面
package com.ljf.spring.boot.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.WEB.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class UserController {
@RequestMapping("/api/show")
public String showName(String userName,Model model){
System.out.println("进入controller层了!!!"+userName);
model.addAttribute("name",userName);
return "index";//跳转到指定页面
}
}
方式一:使用 "redirect" 关键字(不是指java关键字),注意:类的注解不能使用@RestController,要用@Controller;因为@RestController内含@ResponseBody,解析返回的是JSON串。不是跳转页面
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public String test(@PathVariable String name) {
return "redirect:/ceng/hello.html";
}
方式二:使用servlet 提供的API,注意:类的注解可以使用@RestController,也可以使用@Controller
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public void test(@PathVariable String name, httpservletResponse response) throws IOException {
response.sendRedirect("/ceng/hello.html");
}
方式一:使用 "forWord" 关键字(不是指java关键字),注意:类的注解不能使用@RestController 要用@Controller
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public String test(@PathVariable String name) {
return "forword:/ceng/hello.html";
}
方式二:使用servlet 提供的API,注意:类的注解可以使用@RestController,也可以使用@Controller
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public void test(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
request.getRequestDispatcher("/ceng/hello.html").forward(request,response);
}
@RequestMapping(“/test1”)
public String test1(){
return “index”;
}
转发是不需要手动加html的,此时springboot发现是转发,默认配置下他会自动去templates文件夹下找到对应的文件进行转发,如果return后写的是index.html会报404。
重定向
@RequestMapping(“/test2”)
public String test2(){
return “redirect:index1.html”;
}
首先,添加redirect:这个毋庸置疑是mvc的语法问题,其次这里需要注意的是需要手动添加.html,否则会报404
地址栏不发生变化,显示的是上一个页面的地址
请求次数:只有1次请求
根目录:http://localhost:8080/项目地址/,包含了项目的访问地址
请求域中数据不会丢失
地址栏:显示新的地址
请求次数:2次
根目录:http://localhost:8080/ 没有项目的名字
请求域中的数据会丢失,因为是2次请求
疑问
问:什么时候使用转发,什么时候使用重定向?
如果要保留请求域中的数据,使用转发,否则使用重定向。
以后访问数据库,增删改使用重定向,查询使用转发。
问:转发或重定向后续的代码是否还会运行?
无论转发或重定向后续的代码都会执行
1、转发使用的是getRequestDispatcher()方法;重定向使用的是sendRedirect();
2、转发:浏览器URL的地址栏不变。重定向:浏览器URL的地址栏改变;
3、转发是服务器行为,重定向是客户端行为;
4、转发是浏览器只做了一次访问请求。重定向是浏览器做了至少两次的访问请求;
5、转发2次跳转之间传输的信息不会丢失,重定向2次跳转之间传输的信息会丢失(request范围)。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 使用springboot跳转到指定页面和(重定向,请求转发的实例)
本文链接: https://www.lsjlt.com/news/160156.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0