SpringMVC中Controller类的方法返回String不跳转,而是将字符串显示到页面

时间:2023-03-10 02:01:37
SpringMVC中Controller类的方法返回String不跳转,而是将字符串显示到页面

问题描述:

在spring中,控制层的注解一般都是使用@Controller,如果哪个请求参数需要返回数据的话,我们可以在该方法上配合@ResponseBody注解使用,这也是比较常见的方式了。

今天调试一个问题的时候,使用了@RestController注解,出现了一个问题,Controller类的方法返回String,但是页面不跳转,而是直接把字符串的内容("admin/tag_add")显示到页面上。

	/**
* 跳转至标签新增页面
* @return
*/
@RequestMapping(path={"/tagAddViewFtl"}, method = RequestMethod.GET)
public String saveTagViewFtl() {
return "admin/tag_add";
}

  

原因:

这是由于@RestController注解导致的,该注解的作用是:@RestController注解等价于@Controller、@ResponseBody注解结合在一起使用

@ResponseBody注解的作用,是给页面返回json格式的数据,所以会把返回值直接写入HTTP response body中。最终”admin/tag_add”没有被解析为跳转路径,页面没有跳转效果。

SpringMVC中Controller类的方法返回String不跳转,而是将字符串显示到页面

参考链接:

https://blog.****.net/maijia0754/article/details/78309142

https://www.cnblogs.com/softidea/p/5884772.html