通过@RequestMapping更改Spring MVC中的url路径

时间:2015-04-09 05:48:15

标签: spring model-view-controller annotations

目前路径正在显示

http://localhost:8081/UserLogin/login

但我想要这个

http://localhost:8081/UserLogin/index
or
http://localhost:8081/UserLogin/

我的控制器类是

@RequestMapping(value = "/login" ,method = RequestMethod.POST)
  public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
      //return "hi this is a test";
      String userName = request.getParameter("data[Admin][user_name]");
      String userPass=request.getParameter("data[Admin][password]");
      int userId=userDAO.getUser(userName, userPass);
      if(userId!=0){  
        String message = "welcome!!!"; 
        return new ModelAndView("result", "message", message);  
      }  
      else{  
        String message = "fail";
        return new ModelAndView("index", "message",message);  
      } 
  }

想要在不匹配时更改其他条件。 提前致谢。 :)

2 个答案:

答案 0 :(得分:0)

我会返回一个重定向来渲染新网址下的视图:

request.addAttribute("message",message) // better use a Model
return "redirect:/[SERVLET_MAPPING]/index";

答案 1 :(得分:0)

需要一些时间来了解您的需求: - 我想您想要在登录后更改从服务器返回的URL。

但这不起作用,因为从浏览器请求URL并且服务器无法更改它们。相反,服务器可以响应" HTTP 303重定向" (而不是视图)。这会导致浏览器加载使用Redirect指定的URL。

  @RequestMapping(value = "/login" ,method = RequestMethod.POST)
  public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
      //return "hi this is a test";
      String userName = request.getParameter("data[Admin][user_name]");
      String userPass=request.getParameter("data[Admin][password]");
      int userId=userDAO.getUser(userName, userPass);
      if(userId!=0){  
        return new ModelAndView(new RedirectView("/result", true));  // "/result" this is/become an URL!
      }  
      else {  
        return new ModelAndView(new RedirectView("/index", true));  // "/index" this is/become an URL!
      } 
  }

  @RequestMapping(value = "/index" ,method = RequestMethod.GET)
  public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
      String message = "fail";
      return new ModelAndView("index", "message",message);  //"index" the the name of an jsp (or other template)!!
  }

  @RequestMapping(value = "/result" ,method = RequestMethod.GET)
  public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
      String message = "welcome!!!"; 
      return new ModelAndView("result", "message", message);  //"result" the the name of an jsp (or other template)!! 
  }

@See http://en.wikipedia.org/wiki/URL_redirection