在SpringMVC的客户端视图技术中处理json响应

Handling JsonResponse in clientSide view technology of SpringMVC

本文关键字:处理 json 响应 技术 视图 SpringMVC 客户端      更新时间:2023-09-26

我试图在Spring MVC中实现以下场景。但我面临着一些问题,无法决定正确的方法。我正在使用jsonRequest/jsonResone(Restful Webservices)

1。我有一个注册。jsp表单,其中包含几个字段,需要提交给控制器。

 <form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username : </td>
<td><input  id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>

</form>

2。表单的onSubmit将调用下面提到的注册javascript函数

var signupObj  = {
showSignup : function() {
    //There are Two Ways to Declare Function The Other Way is function showSignup().Checkout the reasons
        $.ajax({
            type: "GET",
            url: "showSignup",
            success: function(response) {
                $("#signupView").html( response );
            }
        });
},
 signup : function() {   
     alert("In Signup function");
     var input = '{';
        input += '"username":"'+$('#username').val()+'",';
        input += '"password":"'+$('#password').val()+'"';
        input += '}';
        alert(input);
     $.ajax({
         type: "POST",
         url : "signup",
         contentType: "application/json; charset=utf-8",
         data: input,
         dataFilter: function (response) {
                return response;
            }, 
        // crossDomain: true,
         async:false,
             success: (function(data) {
                 alert("In ajax Sucess");
                 alert(data.profileID);
                 signupObj.redirectview("success",data);
             }),
                error : function(data,textStatus,error){
                    alert("In ajax Failure");
                     alert(error);
                     signupObj.redirectview("failure",data);
                },
             dataType: "json"
     });
     alert("ajax finished");
 },
 redirectview : function(message,data) {
     alert("inside redirect view");
     if(message == "success"){
         url = "success";
     }
     else{
            url = "error";
         }
      $.ajax({
          type: "POST",
          url : "success",
          contentType: "application/json; charset=utf-8",
          data: data,
          async:false,
          dataType: "json",
         dataFilter: function (response) {
            return response;
        }, 
         // crossDomain: true,
          success: (function(data) {
              alert("data");
          }),
            error : function(data,textStatus,error){
                alert("In ajax Failure redirect");
                 alert(error);
            },

});}

};

3。上面的javascript函数对控制器进行ajax调用(输入是jsonRequest)

    @RequestMapping(value="/signup",method=RequestMethod.POST)
      @ResponseBody
        public ProfileDTO signup(@RequestBody LoginDTO loginDTO) {
          ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
          profileDto.setError(null);
          profileDto.setProfileID("profileID");
          profileDto.setProfileName("profileName");
          System.out.println("Submitting SignUP Form Will Return ProfileID");
            return profileDto;
        }
//Below method is for success view
    @RequestMapping(value="/success",method=RequestMethod.POST)
    @ResponseBody
    public String checkSignup(@RequestBody ProfileDTO profileDto,HttpServletRequest httprequest,HttpServletResponse httpResponse
            ) {
        //model.addAttribute(loginDTO);
    System.out.println("In loginSuccess");
        return "loginSucess";
    }

4。控制器给出profileDTO的JSON响应。现在,根据侧写to。我必须调用loginSuccess.jsp或loginFailure.jsp

现在我的问题是

1)如何在ajax调用中使用jsonResponse来重定向到loginSuccess.jsp或loginFailure.jsp,以及如何将我的profileDTO数据传递到loginSuccess视图。

2。)请建议我应该遵循的最佳实践

1。首先,你可以像下面这样在javascript中reduce your code,直接serialize的形式对象。

var signupObj  = {
 signup : function() {   
     alert("In Signup function");
        $.ajax({
         type: "POST",
         url : "signup",
         data: $('#myForm').serialize(),// add "myForm" as the form id 
         async:false,
             success: (function(data) {
                 alert("data"+data);
                 redirectView("success",data);
             })
             error : function(data, textStatus, errorThrown) {
                    alert(error_occured);
                    redirectView("error",data);
                }
     });
 }
 };

 <script
 function redirectView(message,data){
 var url = "";
 if(message == "success"){
    url = "/success";
 }else{
    url = "/error";
 }
     $.ajax({
                    type: "POST",
                    url : url,
                    data: data 
                    async:false,
                    success: (function(data) {
                        alert("data"+data);
                    })
                    error : function(data, textStatus, errorThrown) {
                        alert(error_occured);
                    }
     });
 }
 </script>

2)。从控制器本身重定向successfailure视图。

3)。将我的profileDTO数据传递给loginSuccess视图。

Spring MVC,从版本3开始,允许您使用控制器中的@ResponseBody注释返回直接转换为JSON的对象,如下所示

 @RequestMapping(value="/signup",method=RequestMethod.POST)
          @ResponseBody
            public ProfileDTO signup(@ModelAttribute("LoginDTO") LoginDTO loginDTO,BindingResult bindingResult) {
              ProfileDTO profileDto = new ProfileDTO();
    //In case no errors in backend logic
              profileDto.setError(null);
              profileDto.setProfileID("profileID");
              profileDto.setProfileName("profileName");
              System.out.println("Submitting SignUP Form Will Return ProfileID");
             return profileDto;

            }

If Forward from controller

使用prefix of forward,, Spring将获得指定路径的RequestDispatcher并转发给它。该过程的一部分将包括从为该请求处理周期创建的ModelAndView中获取模型,并将其所有属性放入HttpServletRequest属性中。

Servlet容器将获取RequestDispatcher#forward(..)并再次使用DispatcherServlet来处理它。您的DispatcherServlet将为这个处理周期创建一个新的ModelAndView和一个新的Model。因此,这个模型不包含之前的任何属性,但HttpServletRequest属性包含。

在你的例子中,这个

modelMap.put("key", "value");

最终会出现在

HttpServletRequest request = ...;
request.getAttribute("key");