我的 Spring MVC 应用程序中有一个非常奇怪的问题。我正在编写一个登录表单,并通过 AJAX 将数据发布到 Spring MVC Controller 中,如下所示:
@Controller
public class LoginResourceController {
private static final Logger log = Logger.getLogger (LoginResourceController.class.getName());
@RequestMapping (value="/login", method = RequestMethod.POST)
public String checkAccount (HttpServletRequest httpRequest, HttpServletResponse httpResponse,
@RequestHeader (value = "User-Agent") String retrievedUserAgent,
@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("rememberMe") String rememberMe)
{
//Check username and password in DB, and then if OK,
return "redirect:/login/redirectToMain";
}
@RequestMapping (value = "/login/redirectToMainpage", method = RequestMethod.GET)
public String redirectControllerToMainPage (HttpServletRequest httpRequest, HttpServletResponse httpResponse)
{
return "mainPage";
}
现在的问题是,我的客户端(浏览器)在重定向时请求包含 mainPage.jsp
的全部内容的 URL在网址中。所以它看起来像:
https://localhost:8443/<!DOCTYPE html><html><head><meta charset=utf-8 /><title>Page that the subscriber sees after login</title>....
我对这个错误感到非常困惑。这是 WEB-INF/web.xml
中的一些 servlet 设置吗?或mvc-dispatcher-servlet.xml
我需要改变吗?我使用的是 Spring 3.0.5。
顺便说一句,我的重定向对于 GET
完美无缺。同一 Spring MVC 应用程序中的方法 Controller 。 (例如,当我重新加载应用程序的主页时,重定向到上面登录的 mainPage.jsp
可以完美地工作)。而且,其他GET
其他 jsps 上的方法也可以正常工作(例如,通过 /login
重定向到 login.jsp
页面,通过 GET
的 https://localhost:8443/
。
最佳答案
尽量不要将重定向放在 Controller 的返回中。这似乎要么导致整个页面呈现为 ajax 响应,要么使用 url 填充重定向 header ,并将页面的完整内容作为响应正文中的字符串。
作为第一种方法,尝试使请求成为普通的 HTTP 请求而不是 ajax,它应该可以正常工作。
或者尝试使返回正文为空,并向客户端返回 HTTP 状态代码。如果帐户正常,则200 OK
或401 Unauthorized
:
@RequestMapping (value="/login", method = RequestMethod.POST)
public ResponseEntity checkAccount (HttpServletRequest httpRequest, HttpServletResponse httpResponse,
@RequestHeader (value = "User-Agent") String retrievedUserAgent,
@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("rememberMe") String rememberMe)
{
//Check username and password in DB
....
HttpStatus returnCode = null;
if(usernameAndPasswordOK) {
returnCode = HttpStatus.OK;
}
else {
returnCode = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity(returnCode);
}
然后在客户端使用 Javascript 进行相应的重定向。
关于java - Spring MVC 和 POST 上的重定向在 URL 上发送目标文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160829/