2014-07-10 4 views
1

일부 사용자의 데이터를 업데이트하고 JSP 드롭 다운 메뉴에서 매개 변수를받는 데 문제가 있습니다. "Enter PC"블록에서 입력 된 compId를 받고 PathVariable로 전달하고 싶습니다. 그러나 그것은 보이지 않습니다. action = "$ {app} /adminEdit.do/ $ {user.userId}/$ {any number}" "으로 하드 코드하면됩니다. 질문은 - 이제이 매개 변수를 드롭 다운에서 가져 와서 경로로 설정 하시겠습니까? 미리 감사드립니다.URL 문제로 JSP에서 컨트롤러로 매개 변수 전달

Update.jsp는

<c:set var="app" value="${pageContext.request.contextPath}"/> 
............ 
<DIV class="admin_redaction_block"> 
<sf:form name="adminUserUpdate" 
     method="POST" 
     modelAttribute="userForm" 
     action="${app}/adminEdit.do/${user.userId}/${comp.compId}" 
     enctype="application/x-www-form-urlencoded"> 

    <c:if test="${not empty errorMsg}"> 
     <div class="error"> 
      <c:out value="${errorMsg}"/> 
     </div> 
    </c:if> 

    <sf:label path="password"><strong>Enter new password:</strong></sf:label> <br> 
    <sf:input path="password" type="text" size="20"/><br> 
    <sf:errors path="password" cssClass="error"/> 
    <br> 
    <sf:label path="email"><strong>Enter new Email:</strong></sf:label> <br> 
    <sf:input path="email" type="text" size="20"/><br> 
    <sf:errors path="email" cssClass="error"/> 

    <strong>PC Assigned:</strong> 
    <h3 class="h3"> 
     <td> 
      <c:choose> 
       <c:when test="${user.computers!= null && !user.computers['empty']}"> 
        <c:forEach items="${user.computers}" var="comp"> 
         <c:out value="${comp.pcName}"/> 
        </c:forEach> 
       </c:when> 
       <c:otherwise> 
        <p class="h3_error">No PC Assigned</p> 
       </c:otherwise> 
      </c:choose> 
     </td> 
    </h3> 

    <sf:label path="computers">Enter PC:</sf:label> <br> 
    <sf:select path="computers" size="3"> 
     <c:forEach items="${computers}" var="comp"> 
      <sf:option value="${comp.compId}"> 
       <c:out value="${comp.compId}"/> 
      </sf:option> 
     </c:forEach> 
    </sf:select> 
    <br> <br> 

    <input type="SUBMIT" name="SUBMIT" value="Update User"/> 
</sf:form> 

컨트롤러

@RequestMapping(value = "/adminEdit.do/{userId}/{compId}", method = RequestMethod.POST) 
public ModelAndView updateUserProcess(@ModelAttribute(value = "userForm") 
UserForm userForm, 
@PathVariable("userId") Integer userId, 
@PathVariable("compId") Integer compId, 
     BindingResult result, Model model, 
     HttpSession session, 
     HttpServletRequest request) { 
User user = userService.getUserById(userId); 
model.addAttribute("computers", computerService.getAllComputers()); 
............ 
model.addAttribute("userForm", userForm); 
return updatingUser(user, model, userForm); 
} 
+1

당신이 점점 오류의 유형은 무엇? '하드 코드 액션 = "$ {app} /adminEdit.do/ $ {user.userId}/$ {숫자}"이면 작동합니다 .- 무슨 뜻입니까? –

+0

경로가 잘못되어 404 오류가 발생합니다. ** localhost : 8080/adminEdit.do/2/** - 두 번째 PathVariable이 없습니다. 하드 코드에 대해서 - 나는 값을 설정하면 ** localhost : 8080/adminEdit.do/2/5 (또는 임의의 숫자) **라는 올바른 경로를 얻는다는 것을 의미합니다. 컨트롤러에 두 개의 변수가 전달됨을 의미합니다. 지금은 더 명확 해지기를 바랍니다. – Devour

+0

문제가 두 번째 매개 변수를 올바르게 전달하지 못한다는 의미이므로 비어 있습니다. –

답변

2

당신은 할 수 없습니다에게 니펫을.

당신은 그 일이 다른 시간에 쓰여진다는 것을 잊었을 것입니다.

<sf:form name="adminUserUpdate" ... 
    action="${app}/adminEdit.do/${user.userId}/${comp.compId}" ...> 

는 형태 생성 요청에 응답 시에 기입된다. 그 당시 앱 (서버 측)은 단순히 HTML 페이지를 생성하고 있으며 $comp.compid}은 존재하지 않습니다. 브라우저에서 페이지의 HTML 소스 코드를보고 확인할 수 있습니다.

나중에는 submit 버튼을 클릭하면, 브라우저는 인코딩 입력 필드에서 모든 데이터 를 수집하고을 변경하지 않고 액션 URL 에 POST 요청을 통해 보낼 수 있습니다. 브라우저는 심지어 당신이 당신의 JSP에 ${app}/adminEdit.do/${user.userId}/${comp.compId}을 쓴 것을 알고하지 않습니다 : 그것은 단지 일반 텍스트 문자열

localhost:8080/adminEdit.do/2/ 그래서를 받았다 ... <sf:select> 또는 <sf:checkboxes> 태그를 사용하여 양식의 입력 필드에서 comp.compid를 얻을하려고합니다.

+0

네, FORM에도 값을 설정하려고했지만 어떻게 든 설정되지 않았습니다. , 대단히 고마워. 내가 이런 식으로 일할거야. – Devour

2

글쎄, 오랫동안 검색 한 결과 JSP에서 Controller로 매개 변수를 전달할 수 있음을 알게되었습니다. CustomCollectionEditor 특별 선택 클래스가있어 여러 선택 값을 전달하는 데 도움이됩니다. 다음은 좋은 예에게 있습니다 https://blog.codecentric.de/en/2009/07/multiple-selects-mit-spring-mvc-2/

그리고 내 조각 :

@InitBinder("userForm") 
    private void initBinder(WebDataBinder binder) { 
     binder.registerCustomEditor(Set.class, "computers", new CustomCollectionEditor(Set.class) { 

      @Override 
      protected Object convertElement(Object element) { 
       String pcName = null; 
       Set<Computer> computerSet = new LinkedHashSet<>();  
       if (element instanceof String && !((String) element).equals("")) { 
        pcName = (String) element;      
       }     
       return pcName != null ? computerService.getComputerByName(pcName) : null; 
      } 
     }); 
    } 
관련 문제