调用控制器方法&保持相同的观点

时间:2014-07-18 06:51:38

标签: jquery spring spring-mvc model-view-controller

我正在学习spring mvc框架。我想知道有没有办法将数据(请求对象和字符串)传递给控制器​​&返回一个对象而不重新加载视图。

现在,当我返回对象时,它会重新加载视图&所有先前加载的值都将丢失。

public ModelAndView getSelectedApp( HttpServletRequest request, ModelAndView mav, @RequestParam(value="application") String appName){
    System.out.println("hello");
    List<ApplicationBean> apps = (List<ApplicationBean>)request.getServletContext().getAttribute("applications");
    ApplicationBean application = null;
    for (ApplicationBean applicationBean : apps) {
        if(applicationBean.getAppName().equals(appName)){
            application= applicationBean;
        }
    }
    //ModelAndView mav = new ModelAndView();
    mav.addObject("application", application);
    mav.setViewName("home");;
    //mav.setView(new Redi);
    return mav;
}

1 个答案:

答案 0 :(得分:1)

您需要从Controller渲染ModelAndAttribute。假设实体A,那么你必须把它放到一个表格中。

     <form:form id="formId" method="POST" modelAttribute="A">
         <form:hidden id="aId" path="A.id"/>
    </form:form> 
    <button id="buttonId" type="button" onclick="saveA()">Save</button>

然后你需要创建submitA con javascript方法并对控制器进行Ajax调用序列化formId

  function saveA() {
    $.ajax({
    dataType: "json",
    method: "POST",
    url: 'url',
    data: $('#formId').serialize(),
    success: function (data) {
        //Congratulation you did your first ajax call.
    }
  });
  }

在您的控制器上,您需要一种方法来等待A对象

     @RequestMapping(value = "/saveA.do", method =          RequestMethod.POST)
@ResponseBody
public final void saveA(@PathVariable(A a) {}