【问题标题】:ajax call to the Spring mvc controller returns jsp code instead jsp view对 Spring mvc 控制器的 ajax 调用返回 jsp 代码而不是 jsp 视图
【发布时间】:2018-06-26 07:29:46
【问题描述】:

我希望我的 ajax 调用点击 Spring mvc controller 并返回 jsp view

我已经编写了以下代码来做到这一点

$(document).on("click","#loginSubmit",function(event){

    var userName=$("#userName").val();
    var pwd=$("#password").val();

        var url = contextPath+"/authenticate";       
            $.ajax({        
                url : url,          
                type:"get",   
                data:"&userName="+userName+"&pwd="+pwd,  
                contentType:'application/json; charset=utf-8',  
                async: false,       
                success:function(response) 
                {        

                    console.log(response);
                }  
            }); 
});

这是我的控制器

@RequestMapping(value="/authenticate") 
    @ResponseBody
    public ModelAndView dashboard(@RequestParam("userName") String username,@RequestParam("pwd") String pwd) throws IOException
    { 
     boolean res=false; 


         try { 

    res=service.authenticate(username,pwd); 
         }
         catch (Exception e) {
            e.printStackTrace(); 
        }    
         if(res =true)
         {
             return new ModelAndView("dashboard");  
         }
         else {
             return new ModelAndView("login");
         }

    }

当我点击提交时,它返回 jsp 代码而不是 jsp 视图。

怎么办,我的代码不正确吗?

【问题讨论】:

    标签: spring-mvc jsp


    【解决方案1】:

    这里有些东西混在一起了。 首先你使用的是@ResponseBody,它会返回一个body而不是调用/login。

    其次,我知道您想使用 ajax 是因为身份验证验证,但是如果身份验证成功,为什么不在 javascript 中调用 /dashboard。

    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    @ResponseBody
    public AuthenticateDto dashboard(@RequestParam("userName") String username,@RequestParam("pwd") String pwd) throws IOException
        { 
        return new AuthenticateDto(service.authenticate(username,pwd));
    
    }
    

    【讨论】:

    • 我在spring mvc中没有找到用java脚本调用jsp的方法
    • 没错。 Javascript 应在成功验证后发出 /dashboard 请求..
    • window.location.href = "/dashboard";
    【解决方案2】:

    Ajax 调用总是期望来自控制器的一些响应,因此这种“ajax 调用来命中 Spring mvc 控制器并返回一个 jsp 视图”是不可能的。

    您可以做的是从控制器获得成功响应后,您可以重定向到一个控制器方法 URL,该 URL 将返回 JSP 页面

    success:function(response) 
    {        
    window.location.href = "/urlToDashboard";
    }  
    

    在控制器中:

    @RequestMapping(value="urlToDashboard")
    public String dashboardPage()
    { 
    return "dashboard"; // return dashboard.jsp page
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多