2013-10-27 161 views
1

我有一個用戶名(jeff)存儲在cookie當用戶請求官員/用戶頁面,如果有一個userName在cookie我想向用戶顯示官員/用戶的詳細信息。我使用ajax請求以獲取詳細信息。春天MVC控制器沒有返回正確的視圖

AJAX請求轉到控制器和然而獲取數據時i中視圖返回給用戶的對象。因此沒有數據綁定到對象。該視圖然後是空的。我想向用戶返回具有官員/用戶數據的對象。

下是我的代碼和在螢火蟲請求的屏幕截圖。請告訴我我哪裏錯了。

從視圖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[email protected]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 {[email protected], 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.s[email protected]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.s[email protected]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: [email protected] 
758528 [http-bio-8084-exec-9] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request 

屏幕截圖

的用戶名是傑夫

這是螢火蟲,它顯示了POST jeff.htm正在返回的數據。我認爲被返回的視圖不正確。

enter image description here

Officer_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> 
+1

如何處理ajax請求返回的數據?看起來您的視圖是正確生成的,只需查看螢火蟲中的響應圖像即可。我懷疑問題是與應該更新你看的表單的JavaScript。 –

+0

我沒有返回對象的成功函數。我應該在對象返回時包含成功函數嗎?它將如何綁定? – devdar

+0

我想從控制器綁定對象,並返回視圖,使對象將顯示在視圖 – devdar

回答

1

查看問題中的最後一張圖片,我可以看到您使用的是jQuery,它看起來像你會得到一個包含HTML的響應,我假設你正在使用jQuery來發出ajax請求(例如使用$.ajax$.get)。假設你正在使用jQuery's ajax function。您的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傳輸,並只更新現有表單中的值。 Spring對使用@ResponseBody註釋返回JSON提供了很好的支持。

1

相反的:

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

這樣做:

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

Spring會將返回的String解釋爲視圖名稱,並使用您在該方法中構建的模型。

+0

這是行爲等同於OP目前正在做的。 –

+0

不正確。 OP正在返回一個'ModelAndView',其中包含一個新的EMPTY模型以及視圖的名稱。他放在模型中的任何東西都會使它看起來不錯。 – MattSenter

+1

不正確。去看看'ModelAndViewMethodReturnValueHandler','MapMethodProcessor'和'ModelMethodProcessor'的源代碼。傳遞給handler方法的'Model'和'ModelMap'參數以及其中包含的屬性將與返回的'ModelAndView'中的參數同步。最後,所有這些屬性都將包含在用於請求的'ModelAndViewContainer'中。 –

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(它看起來像」 ......)純文本。因此,它是unconvinient從這樣的文本

解析軍官數據

在第二種情況下,您將獲得json格式的官員對象,因此從中可以非常容易地從中提取數據。

+0

你確定這是問題嗎?查看問題中的最後一張圖片,似乎是使用數據生成的響應。春天是否可以將作爲參數傳遞的'Model'與自動從方法返回的'ModelAndView'合併?無論如何,我認爲你的代碼通常更清晰。 –

+0

是的,你是對的。向ModelAndView添加模型不會改變結果。 – yname

+0

我沒有必須提取數據,因爲我使用彈簧窗體標籤,這應該允許字段從對象中查找相關屬性。 – devdar

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 

打印,在返回ModelAndViewmodelnull。該日誌說法來自InvocableHandlerMethod#invokeForRequest,看起來像這樣

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

@Controller處理方法創建並返回一個新ModelAndView對象

return new ModelAndView("officer_registration");  

ModelAndView構造函數,它接受一個String沒有初始化其model場。因此它仍然是null但是不要驚慌。您的處理程序方法聲明的參數ModelMapModel將同時傳遞類型BindingAwareModelMap的相同參數,該參數由HandlerMethodArgumentResolver解決。 Model參數的具體實現類別爲ModelMethodProcessorModelMapMapMethodProcessor。這兩個解決方案都會針對每個請求生成的ModelAndViewContainer解析其目標參數。他們都會給出同樣的例子。你聲明兩者都是多餘的。

即使在返回ModelAndViewmodelnull,進一步下跌的請求處理,將與已作爲參數傳遞,因此將包含您所

model.addAttribute("officers",officerManager.getOfficer(userName)); 
屬性集中 BindingAwareModelMap同步

或錯誤屬性,具體取決於。

您將不得不告訴我們您的officer_registration視圖,並告訴我們您期望在ajax處理程序中看到的更多細節。 請注意,ajax處理程序將收到您的視圖中生成的響應。如果這是一個jsp,那麼ajax將會看到一些HTML。那是你要的嗎?

+0

在我的表單中我使用了spring form標籤來允許綁定 – devdar

+0

@devdar好的,給我們看。 –

+0

我包含了表單代碼 – devdar

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請求,因爲兩個命中控制器和兩個使用相同的返回語句。

相關問題