springboot如何重定向外部网页
作者:梁晓山(ben)
这篇文章主要介绍了springboot如何重定向外部网页,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
springboot重定向外部网页
package com.liangxs.web;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//注意这里不能用@RestController,RestController由@Controller+ResponseBody组成,返回的是数据中支持跳转视图
@RequestMapping("/upload")
public class TestController {
	@RequestMapping("/redirect")
	public String redirect(HttpServletResponse response) {
		 return "redirect:http://www.baidu.com";//spring redirect方式
	}
	@RequestMapping("/redirect1")
	public void redirect1(HttpServletResponse response) {
		try {
			response.sendRedirect("http://www.baidu.com");//HttpServletResponse方式
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}springboot页面重定向问题
@GetMapping("/delemp/{id}")
public String deleteEmp(@PathVariable("id")Integer id){
    employeeDao.delete(id);
    return "redirect:/emps";
}如上述代码所示,接受前端请求后通返回"redirect:/emps"即可实现重定向到localhost:8080/emps请求中,此时不能写成"redirect:emps"即最前端的斜杠不能省略,否则运行时报错
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘java.lang.Integer’;
nested exception is java.lang.NumberFormatException: For input string: “emps”]。
在没有@PathVariable的请求中可以写成"redirect:emps"重定向返回(目前不知道报错和可以省略斜杠的原因)
如下代码所示,但建议都写成"redirect:/emps"。
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
    employeeDao.save(employee);
    return "redirect:emps";
}以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
