1

当用户请求官员/用户页面时,如果我想向用户显示官员/用户详细信息的cookie中有用户名,我有一个用户名(杰夫)存储在 cookie 中。我使用ajax 请求来获取详细信息。

ajax请求转到控制器并获取数据,但是当我将视图返回给用户时,对象null。因此,没有数据绑定到对象。然后视图为空。我想将具有官员/用户数据的对象返回给用户。

下面是我的代码和萤火虫中请求的屏幕截图。请告诉我哪里出错了。

来自视图的 Ajax 请求

<script type="text/javascript"> 
  function getCookie(name) {
    var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
    var result = regexp.exec(document.cookie);
    return (result === null) ? null : result[1];
  }

  var userName = getCookie("userName");
  console.log(getCookie("userName"));

  if(userName != null & userName != 'Guest'){
     alert('Redirecting to get officer');

    $.ajax({
            type:'POST',
        url:'getOfficer/'+ userName + '.htm',
        contentType: "application/json",
        async: false,
        cache: false, 
        data:userName                   
        });     
    }

控制器

 @RequestMapping(value="getOfficer/{userName}.htm", method = RequestMethod.POST)
 public ModelAndView getOfficer(@PathVariable String userName,@ModelAttribute Officers officer, 
BindingResult result,ModelMap m,Model model,HttpServletRequest request,  
HttpServletResponse response) {

 logger.info("In get Officer by userName");
 try{
    model.addAttribute("officers",officerManager.getOfficer(userName));
 }catch(Exception e){
    logger.error("Exception In Officer Controller getOfficer/{userName} " + e.getMessage());
    request.setAttribute("error",e.getMessage());
 }

 logger.info("about to return new officer_registration");
 logger.info("Officer Badge Number is "+officer.getBadgeNo());
 logger.info("Officer First and last name is "+officer.getfName() + " - " + officer.getlName());

 return new ModelAndView("officer_registration");    

}

带有 Logger.info 消息的错误日志

我注意到这条线表明模型为空。为什么?

758511 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod  - Method [postOfficer] returned [ModelAndView: reference to view with name 'officer_registration'; model is null


758470 [http-bio-8084-exec-9] INFO  com.crimetrack.web.OfficerController  - In get Officer by userName
758470 [http-bio-8084-exec-9] INFO  com.crimetrack.jdbc.JdbcOfficersDAO  - Getting Officer in getOfficer(String userName)
758506 [http-bio-8084-exec-9] DEBUG org.springframework.jdbc.core.JdbcTemplate  - Executing prepared SQL query
758506 [http-bio-8084-exec-9] DEBUG org.springframework.jdbc.core.JdbcTemplate  - Executing prepared SQL statement [SELECT * FROM crimetrack.tblofficers WHERE userName = ?]
758506 [http-bio-8084-exec-9] DEBUG org.springframework.jdbc.datasource.DataSourceUtils  - Fetching JDBC Connection from DataSource
758508 [http-bio-8084-exec-9] DEBUG org.springframework.jdbc.core.StatementCreatorUtils  - Setting SQL statement parameter value: column index 1, parameter value [jeff], value class [java.lang.String], SQL type unknown
758510 [http-bio-8084-exec-9] DEBUG org.springframework.jdbc.datasource.DataSourceUtils  - Returning JDBC Connection to DataSource
758511 [http-bio-8084-exec-9] INFO  com.crimetrack.web.OfficerController  - about to return new officer_registration
758511 [http-bio-8084-exec-9] INFO  com.crimetrack.web.OfficerController  - Officer Badge Number is null
758511 [http-bio-8084-exec-9] INFO  com.crimetrack.web.OfficerController  - Officer First and last name is null - null
758511 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod  - Method [postOfficer] returned [ModelAndView: reference to view with name 'officer_registration'; model is null]
758511 [http-bio-8084-exec-9] DEBUG org.springframework.web.method.support.InvocableHandlerMethod  - Invoking [initBinder] method with arguments [org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder@b836456]
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.method.support.InvocableHandlerMethod  - Method [initBinder] returned [null]
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet  - Rendering view [org.springframework.web.servlet.view.JstlView: name 'officer_registration'; URL [/WEB-INF/jsp/officer_registration.jsp]] in DispatcherServlet with name 'crimetrack'
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.view.JstlView  - Rendering view with name 'officer_registration' with model {officers=com.crimetrack.business.Officers@5f305001, org.springframework.validation.BindingResult.officers=org.springframework.validation.BeanPropertyBindingResult: 0 errors} and static attributes {}
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'officers' of type [com.crimetrack.business.Officers] to request in view with name 'officer_registration'
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'userName' of type [java.lang.String] to request in view with name 'officer_registration'
758512 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.view.JstlView  - Added model object 'org.springframework.validation.BindingResult.officers' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'officer_registration'
758513 [http-bio-8084-exec-9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - No bean named 'requestDataValueProcessor' found in org.springframework.beans.factory.support.DefaultListableBeanFactory@726b5b3c: defining beans [citizenManager,validateCitizenManager,citizenDao,citizenTypeManager,citizenTypeDao,markerManager,markerDao,crimeHotSpotManager,crimeHotSpotDao,crimeManager,crimeRegistrationValidation,crimeDao,colorManager,colorDao,monitoringTypeManager,monitoringTypeDao,monitoringManager,monitoringDao,ethnicityManager,ethnicityDao,crimeLevelManager,crimeLevelDao,crimeTypeManager,crimeTypeDao,statusManager,statusDao,crimeCategoryManager,crimeCategoryDao,maritalStatusManager,maritalStatusDao,occupationManager,occupationDao,officerManager,countryManager,countryDao,authenticationManager,loginDao,divisionManager,divisionDao,positionManager,positionDao,genderManager,genderDao,officerRegistrationValidation,validateUserManager,officerDao,dataSource,propertyConfigurer,transactionManager]; root of factory hierarchy
758513 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.view.JstlView  - Forwarding to resource [/WEB-INF/jsp/officer_registration.jsp] in InternalResourceView 'officer_registration'
758514 [http-bio-8084-exec-9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - No bean named 'requestDataValueProcessor' found in org.springframework.beans.factory.support.DefaultListableBeanFactory@726b5b3c: defining beans [citizenManager,validateCitizenManager,citizenDao,citizenTypeManager,citizenTypeDao,markerManager,markerDao,crimeHotSpotManager,crimeHotSpotDao,crimeManager,crimeRegistrationValidation,crimeDao,colorManager,colorDao,monitoringTypeManager,monitoringTypeDao,monitoringManager,monitoringDao,ethnicityManager,ethnicityDao,crimeLevelManager,crimeLevelDao,crimeTypeManager,crimeTypeDao,statusManager,statusDao,crimeCategoryManager,crimeCategoryDao,maritalStatusManager,maritalStatusDao,occupationManager,occupationDao,officerManager,countryManager,countryDao,authenticationManager,loginDao,divisionManager,divisionDao,positionManager,positionDao,genderManager,genderDao,officerRegistrationValidation,validateUserManager,officerDao,dataSource,propertyConfigurer,transactionManager]; root of factory hierarchy
758528 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet  - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@51dd475f
758528 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet  - Successfully completed request

截屏

用户名是杰夫

这是来自 firebug,它显示 POST jeff.htm 正在返回数据。我认为返回的视图不正确。

在此处输入图像描述

Office_Registration.jsp

</head>
<body>
  <form:form id="officerRegistration" name="officerRegistration" method="post" modelAttribute="officers" action="officer_registration.htm">
  <ol>
  <li>
    <label>Badge No</label>
    <form:input path="badgeNo" id="badgeNo" title="Enter a Valid Badge Number"
      readonly="${badgeNoStatus}" class="formData" />
    <form:errors path="badgeNo" class="errors" />
    <label id="badgeNoErr"></label>
  </li>
  <li>
    <form:label for="userName" path="userName">User Name</form:label>
    <form:input path="userName" id="userName" title="Choose A Unique UserName"
      readonly="${userNameStatus}" class="formData" />
    <form:errors path="userName" class="errors" />
    <label id="userNameErr"></label>
  </li>
  <li>
    <label>Password</label>
    <form:password path="password" id="password" class="formData" />
    <form:errors path="password" class="errors" />
  </li>
  <li>
    <label>Re-Enter Password</label>
    <form:password path="password2" id="password2"
      class="formData" />
    <form:errors path="password2" class="errors" />
  </li>
  <li>
    <label>e-Mail Address</label>
    <form:input path="emailAdd" id="emailAdd" title="Enter eMail Address"
      class="formData" />
    <form:errors path="emailAdd" class="errors" />
  </li>
  <li>
    <label>First Name</label>
    <form:input path="fName" id="fName" title="Your First Name"
      class="formData" />
    <form:errors path="fName" class="errors" />
  </li>
  <li>
    <label>Last Name</label>
    <form:input path="lName" id="lName" title="Your Last Name"
      class="formData" />
    <form:errors path="lName" class="errors" />
  </li>
  <li>
4

5 回答 5

1

代替:

public ModelAndView getOfficer(...){...}

做这个:

public String getOfficer(...) {
    ...
    return "officer_registration";
}

Spring 会将返回的 String 解释为视图名称,并使用您在方法中构建的模型。

于 2013-10-27T18:54:54.257 回答
1

编辑:似乎这种方法无济于事。看下一个提示

您返回新的明确 ModelAndView。

试试这个:

ModelAndView m = new ModelAndView("officer_registration");
m.addAllObjects(model.asMap());
return m;

编辑:这可以帮助

但是,如果您只想请求官员数据,最好创建另一种方法:

@RequestMapping(value="getOfficer/{userName}.ajax", method = RequestMethod.POST)
public @ResponseBody Officers getOfficerInfo(@PathVariable String userName) {
    return officerManager.getOfficer(userName);
}

不要忘记添加杰克逊依赖项(http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs)。

在第一种情况下,您将获得纯文本,它将是您的“officer_registration”页面的 html(它看起来像“......)。因此从此类文本中解析官员数据是不方便的

在第二种情况下,您将获得 json 格式的官员对象。因此,从中提取数据将非常容易。

于 2013-10-27T19:11:23.650 回答
1

查看您问题中的最后一张图片,我可以看到您正在使用 jQuery,并且看起来您正在收到包含 HTML 的响应。我假设您正在使用 jQuery 来发出 ajax 请求(例如使用$.ajaxor $.get)。假设您正在使用jQuery 的 ajax 函数。您的 js 代码如下所示:

function getOfficerInfo(officerUserName) {
    var officerUrl = "/crimeTrack/getOffice/" + officerUserName + ".htm"
    $.ajax({
        url: officerUrl,
        type: "GET"
    });
}

这将向服务器发送一个 GET 请求,该请求将返回您在图像中查看的响应中显示的 html。但是,此代码不处理响应。为了做到这一点,您需要在传递给$.ajax函数的 javascript 对象中添加一个成功字段(或者您可以使用函数返回承诺的事实 $.ajax,但让我们坚持基础知识:))。

function getOfficerInfo(officerUserName) {
    var officerUrl = "/crimeTrack/getOffice/" + officerUserName + ".htm"
    $.ajax({
        url: officerUrl,
        type: "GET",
        success: function(data) {
            $("#form-container").html(data);
        }
    });
}

当 ajax 请求成功时,该success函数将被调用,data变量将保存响应中的数据。在这里,我假设您在页面上有一些带有 id 的元素,form-container其内容可以替换为您的 html 响应。

请注意,这里没有错误处理,因此您还应该添加一个error函数来处理超时、服务器端错误等。

最后。我建议您将数据作为 JSON 传输,并仅更新现有表单中的值。@ResponseBodySpring 对使用注解返回 JSON 有很好的支持。

于 2013-10-27T19:26:17.587 回答
1

这条线

758511 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod  - Method [postOfficer] returned [ModelAndView: reference to view with name 'officer_registration'; model is null

打印model返回的字段ModelAndViewnull. 此日志语句来自InvocableHandlerMethod#invokeForRequest并且看起来像这样

if (logger.isTraceEnabled()) {
    logger.trace("Method [" + this.getMethod().getName() + "] returned [" + returnValue + "]");
}

您的@Controller处理程序方法创建并返回一个新ModelAndView对象

return new ModelAndView("officer_registration");    

ModelAndView接受 a的构造函数String不会初始化其model字段。因此它仍然存在null不过不要惊慌。参数ModelMapModel您的处理程序方法声明的参数都将传递相同类型的参数,该参数BindingAwareModelMapHandlerMethodArgumentResolver. 具体的实现类是ModelMethodProcessor针对Model参数的,MapMethodProcessor针对ModelMap. ModelAndViewContainer这两个都从为每个请求生成的那个中解析它们的目标参数。他们都会给出相同的实例。你声明两者是多余的。

即使您model在返回的字段ModelAndViewnull,在请求处理的更下方,它将与BindingAwareModelMap作为参数传递的字段同步,因此将包含您设置的属性

model.addAttribute("officers",officerManager.getOfficer(userName));

或错误属性,具体取决于。

您必须向我们展示您的officer_registration观点并告诉我们您希望在 ajax 处理程序中看到的内容以获取更多详细信息。请注意,ajax 处理程序将接收从您的视图生成的响应。如果那是 a jsp,那么 ajax 将看到一些 HTML。那是你要的吗?

于 2013-10-27T21:52:43.787 回答
0

感谢大家对问题的所有回答,但是当你们都正确地识别出新的 ModelAndView 确实返回了一个新的对象时。我观察到的是发出请求时 url 没有改变,它保持不变

http://localhost:8084/crimeTrack/officer_registration.htm

这是错误的看法。

我决定在我的页面上包含一个按钮,以允许用户查看个人资料详细信息:

<button id= "view" class="btn" value ="save"   onclick= "submitPage('${pageContext.request.contextPath}/getOfficer/<%=request.getSession().getAttribute("userName")%>.htm');" type="button" ${viewbtn}>View Profile</button>

现在我所做的只是删除了 ajax 请求并包含了按钮,我保留了控制器代码。发出请求时,表单返回数据和读取的 url

http://localhost:8084/crimeTrack/getOfficer/jeff.htm

这工作得很好,我是 Spring MVC 的初学者,所以我无法解释为什么这对 ajax 请求有效,因为两者都击中了控制器并且都使用了相同的返回语句。

于 2013-10-27T22:12:49.937 回答