[SPRING] Spring MVC 페이지 HTTP 상태 400 및 잘못된 URL
SPRINGSpring MVC 페이지 HTTP 상태 400 및 잘못된 URL
신청서에 몇 가지 문제가 있습니다. 컨트롤러에서 다른 페이지로의 게시물 인 등록 양식이 있습니다. 이 페이지에는 등록 양식의 쿼리 결과가 표시됩니다. 결과 페이지에서 레코드를 선택하면 데이터를 등록 페이지로 전송하십시오. 사용자는 리턴 된 레코드를 갱신하거나 조회를 다시 실행할 수 있어야합니다.
내가 겪고있는 문제는 사용자가 등록 양식을보고 결과 페이지에 게시 된 쿼리를 실행하는 경우입니다. 결과 페이지가 표시되지만 URL은 변경되지 않습니다. 등록 url은 http : // localhost : 8084 / crimeTrack / citizen_registration.htm입니다. 쿼리 버튼을 클릭하여 결과 페이지에 게시 할 때 url은 여전히 http : // localhost : 8084 / crimeTrack / citizen_registration.htm입니다. 결과 페이지 (여러 레코드가 있음)에서 레코드가 클릭 / 선택되면 사용자는 다음과 같은 등록 페이지로 다시 게시됩니다. 선택한 레코드가 있고 사용자가 지금 업데이트 또는 쿼리를 실행하기 위해 표시되면 url은 http : // localhost : 8084 / crimeTrack / getCitizen / 1985121244.htm입니다. 사용자는 이제 등록 페이지에 있습니다.
쿼리 / 업데이트를 다시 클릭하면 HTTP 400 오류가 발생하고 url은 http : // localhost : 8084 / crimeTrack / getCitizen / citizen_registration.htm / 이는 컨트롤러에서 유효한 URL 매핑이 아닙니다. 나는 url이 http : // localhost : 8084 / crimeTrack / citizen_registration.htm이되어야한다고 생각한다. 등록 페이지는 다음과 같다. 요청했다. 결과 페이지의 POST가 사용자가 등록 페이지로 돌아갈 때 URL이 http : // localhost : 8084 / crimeTrack / getCitizen / 1985121244.htm이어야하는지 잘 모르겠습니다. 첨부 번호는 시민 번호입니다. 아래는 내 코드입니다.이 전화를 올바르게하고 있는지, 내가 얻고있는 결과에 대한 설명을 원한다면 잘 모르겠습니다. 경험 한 문제점에 해결책;
페이지는 jquery를 사용하여 제출됩니다.
이것은 등록 페이지의 예이며 다른 모든 페이지는 동일한 패턴을 따릅니다.
JScript
function submitPage(){
document.getElementById("citizenRegistration").action="citizen_registration.htm";
//document.getElementById("citizenRegistration").target="_self";
document.getElementById("citizenRegistration").method = "POST";
document.getElementById("citizenRegistration").submit();
}
citizen_registration.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html lang="en">
<head>
<title>Citizen Registration</title>
</head>
<body>
<div id="tab1" class="divGroup">
<form:form id="citizenRegistration" name ="citizenRegistration" commandName="citizens">
........................
<div class="buttons">
<ol>
<li><input class="button" id="save" type="submit" name= "user_request" value="Save"/>
<input class="button" id="update" type="submit" name= "user_request" value="Update"/>
<input class="button" id="query" type="submit" name= "user_request" value="Query"/>
</li>
</form:form>
</div>
</body>
</html>
citizenList.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function submitPage(socialSecurityNumber){
document.getElementById("citizenList").action="getCitizen/1985121244.htm";//harded coded for testing
//document.getElementById("citizenList").target="_self";
document.getElementById("citizenList").method = "POST";
document.getElementById("citizenList").submit();
}
function GetCitizenTypeDescription(citizenTypeId){
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeId').each(function(i){
if($(this).val() === citizenTypeId){
//finds parent div
var parent = $(this).parent();
//search for child element wit class name citizenTypeDesc
var thisCitizenTypeDesc = parent.children('.citizenTypeDesc');
thisCitizenTypeDesc.text(data);
}
});
}
});
}
<title>Citizen Search Results</title>
</head>
<body>
<form:form id="citizenList" name ="citizenList">
<div id ="content">
<c:forEach items="${citizens}" var="citizen">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
<label class="citizenTypeDesc"></label></br>
<a class="socialSecurityNumber" href="${citizen.socialSecurityNumber}">${citizen.fName} ${citizen.lName}</a>
<input type="hidden" id="photo" value="${citizen.photo}" class="photos"/>
<input type="hidden" id="socialSecurityNumber" value="${citizen.socialSecurityNumber}" />
<input type="hidden" class="citizenTypeId" value="${citizen.citizenTypeId}"/>
</div>
</c:forEach>
</div>
</form:form>
</body>
</html>
CitizenRegistrationController.java
@Controller
public class CitizenRegistrationController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private CitizenTypeManager citizenTypeManager;
............
Map<String, Object> myCitizenType = new HashMap<String, Object>();
.......
@InitBinder("citizens")
protected void initBinder(WebDataBinder binder){
//removes white spaces
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
//formats date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//By passing true this will convert empty strings to null
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
dateFormat.setLenient(false);
//binder.setValidator(new OfficerRegistrationValidation());
binder.setValidator(citizenRegistrationValidation);
binder.registerCustomEditor(Integer.class,new CustomIntEditor());
}
@RequestMapping(value="citizen_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(@ModelAttribute Citizens citizen,
BindingResult result,
ModelMap m,
Model model,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
logger.debug("In Http method for CitizenRegistrationController");
myCitizenType.put("citizenTypeList", this.citizenTypeManager.getCitizenType());
myGender.put("genderList", this.genderManager.getGenderList());
......
return new ModelAndView("citizen_registration");
}catch(Exception e){
logger.error("Exception in CitizenRegistrationController - ModelAndView loadPage "+e);
request.setAttribute("error",e.getMessage());
return new ModelAndView("error_page");
}
}
@RequestMapping(value="citizen_registration.htm", method = RequestMethod.POST)
public ModelAndView handleRequest(@Valid @ModelAttribute Citizens citizen,
BindingResult result,
ModelMap m,
Model model,
@RequestParam(value="user_request") String user_request) throws Exception {
try{
logger.debug("In Http method for CitizenRegistrationController - Punishment Registration");
logger.debug("User Request Is " + user_request);
if(result.hasErrors()){
logger.debug("Has Errors");
return new ModelAndView("citizen_registration");
}else{
//check if its a save of an update
if(user_request.equals("Save")){
citizenManager.RegisterCitizen(citizen);
model.addAttribute("icon","ui-icon ui-icon-circle-check");
model.addAttribute("results","Record Was Saved");
return new ModelAndView("citizen_registration");
}else if (user_request.equals("Query")){
logger.debug("about to preform query");
//citizenManager.getListOfCitizens(citizen);
if(citizenManager.getListOfCitizens(citizen).isEmpty()){
model.addAttribute("icon","ui-icon ui-icon-circle-close");
model.addAttribute("results","Notice: Query Caused No Records To Be Retrived!");
}else{
model.addAttribute("citizens",citizenManager.getListOfCitizens(citizen));
return new ModelAndView("citizenList");
}
}else if (user_request.equals("Update")){
logger.info("About to do update");
citizenManager.UpdateCitizen(citizen);
return new ModelAndView("citizen_registration");
}
}
logger.debug("Has No Errors");
return new ModelAndView("citizen_registration");
}catch(Exception e){
logger.error("Exception in CitizenRegistrationController - ModelAndView loadPage "+e);
//request.setAttribute("error",e.getMessage());
return new ModelAndView("citizen_registration");
}
}
@RequestMapping(value="getCitizen/{socialSecurityNumber}.htm", method = RequestMethod.POST)
public ModelAndView getCitizen(@PathVariable Integer socialSecurityNumber,@ModelAttribute Citizens citizen,
BindingResult result,ModelMap m,Model model,HttpServletRequest request,
HttpServletResponse response) {
try {
model.addAttribute("citizens",citizenManager.getCitizen(socialSecurityNumber));
//model.addAttribute("citizens",citizenManager.getCitizen(socialSecurityNumber));
} catch (Exception e) {
logger.error("Exception in CitizenRegistrationController - ModelAndView getCitizen "+e);
}
return new ModelAndView("citizen_registration");
}
@RequestMapping(value="getCitizenTypeDescription.htm", method=RequestMethod.GET)
public @ResponseBody String citizenTypeDescription(@RequestParam Integer citizenTypeId)throws Exception{
String data = "No Data Found";
try{
data = citizenTypeManager.getCitizenTypeDescription(citizenTypeId);
}catch(Exception e){
data = e.getMessage();
logger.error("Exception In getCitizenTypeDescription.htm error : " + e);
}
return data;
}
//setter methods
/**
* @param citizenTypeManager the citizenTypeManager to set
*/
public void setCitizenTypeManager(CitizenTypeManager citizenTypeManager) {
this.citizenTypeManager = citizenTypeManager;
}
................................
}
편집하다
return new ModelAndView ( "redirect : /citizenList.htm");를 사용하여 시도했다. 컨트롤러에서 사용자가 쿼리를 클릭하면 404 찾을 수 없음 - http : // localhost : 8084 / crimeTrack / citizenList.htm "
Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans/spring-context-3.0.xsd">
<!-- __________________________________________________________________________________________________ -->
<!-- Supports annotations and allows the use of @Controller, @Required, @RequestMapping -->
<context:annotation-config/>
<context:component-scan base-package="com.crimetrack.business"/>
<context:component-scan base-package="com.crimetrack.jdbc"/>
<context:component-scan base-package="com.crimetrack.service"/>
<context:component-scan base-package="com.crimetrack.web" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
<!-- __________________________________________________________________________________________________ -->
<!-- Forwards requests to the "/" resource to the "login" view -->
<mvc:view-controller path="/login" view-name="login"/>
<!-- Forwards requests to the "/" resource to the "officer_registration" view -->
<mvc:view-controller path="/officer_registration" view-name="officer_registration"/>
<!-- Forwards requests to the "/" resource to the "citizenList" view -->
<mvc:view-controller path="/citizenList" view-name="citizenList"/>
<!-- Forwards requests to the "/" resource to the "citizen_registration" view -->
<mvc:view-controller path="/citizen_registration" view-name="citizen_registration"/>
<!-- __________________________________________________________________________________________________ -->
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> -->
<!-- Is used to process method level annotations -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- __________________________________________________________________________________________________ -->
<!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<!-- __________________________________________________________________________________________________ -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
해결법
-
==============================
1.1) 제출 대신 입력 유형을 버튼으로 변경하고 submitPage 함수를 호출 할 onclick 이벤트를 추가하여 호출 액션에 전달합니다.
1) 제출 대신 입력 유형을 버튼으로 변경하고 submitPage 함수를 호출 할 onclick 이벤트를 추가하여 호출 액션에 전달합니다.
<input class="button" id="save" type="button" name="user_request" value="Save" onclick="submitPage('citizen_registration.htm');"/> <input class="button" id="update" type="button" name="user_request" value="Update" onclick="submitPage('citizen_registration.htm');"/> <input class="button" id="query" type="button" name="user_request" value="Query" onclick="submitPage('citizen_list.htm');"/>
2) submitPage 함수를 변경하여 어떤 버튼이 클릭되었는지에 따라 액션을 설정합니다.
function submitPage(action){ document.getElementById("citizenRegistration").action = action; document.getElementById("citizenRegistration").method = "POST"; document.getElementById("citizenRegistration").submit(); }
3) 두 개의 컨트롤러 메소드가 있는데, 하나는 저장 / 업데이트로 매핑되고, 다른 하나는리스트로 매핑됩니다.
@RequestMapping(value="citizen_list.htm", method = RequestMethod.POST) public ModelAndView getCitizenList(@Valid @ModelAttribute Citizens citizen, BindingResult result, ModelMap m, Model model, @RequestParam(value="user_request") String user_request) throws Exception { try{ logger.debug("about to preform query"); //citizenManager.getListOfCitizens(citizen); if(citizenManager.getListOfCitizens(citizen).isEmpty()){ model.addAttribute("icon","ui-icon ui-icon-circle-close"); model.addAttribute("results","Notice: Query Caused No Records To Be Retrived!"); }else{ model.addAttribute("citizens",citizenManager.getListOfCitizens(citizen)); return new ModelAndView("citizenList"); } }catch(Exception e){ logger.error("Exception in CitizenRegistrationController - ModelAndView loadPage "+e); //request.setAttribute("error",e.getMessage()); return new ModelAndView("citizen_registration"); } } @RequestMapping(value="citizen_registration.htm", method = RequestMethod.POST) public ModelAndView handleRequest(@Valid @ModelAttribute Citizens citizen, BindingResult result, ModelMap m, Model model, @RequestParam(value="user_request") String user_request) throws Exception { try{ logger.debug("In Http method for CitizenRegistrationController - Punishment Registration"); logger.debug("User Request Is " + user_request); if(result.hasErrors()){ logger.debug("Has Errors"); return new ModelAndView("citizen_registration"); }else{ //check if its a save of an update if(user_request.equals("Save")){ citizenManager.RegisterCitizen(citizen); model.addAttribute("icon","ui-icon ui-icon-circle-check"); model.addAttribute("results","Record Was Saved"); return new ModelAndView("citizen_registration"); } else if (user_request.equals("Update")){ logger.info("About to do update"); citizenManager.UpdateCitizen(citizen); return new ModelAndView("citizen_registration"); } } logger.debug("Has No Errors"); return new ModelAndView("citizen_registration"); }catch(Exception e){ logger.error("Exception in CitizenRegistrationController - ModelAndView loadPage "+e); //request.setAttribute("error",e.getMessage()); return new ModelAndView("citizen_registration"); } }
-
==============================
2.문제는 action = "citizen_registration.htm"이라고 할 때 상대 경로를 사용하고 있다는 것입니다.
문제는 action = "citizen_registration.htm"이라고 할 때 상대 경로를 사용하고 있다는 것입니다.
그것을 다음으로 변경하십시오.
document.getElementById("citizenRegistration").action="/crimeTrack/citizen_registration.htm";
또는
document.getElementById("citizenRegistration").action="../citizen_registration.htm";
from https://stackoverflow.com/questions/15456724/spring-mvc-pages-http-status-400-and-incorrect-urls by cc-by-sa and MIT license
'SPRING' 카테고리의 다른 글
[SPRING] Spring과 Thymeleaf : 컨트롤러에 객체 보내기 : 각 테이블 (0) | 2019.05.25 |
---|---|
[SPRING] 초기화 할 때로드 될 모든 Spring 부트 속성과 모든 것을 존중하고 속성 파일의 값을 기반으로 @Aspect를 제어합니다. (0) | 2019.05.25 |
[SPRING] @Autowired beans는 beans를 사용한 후에 로딩하지 않는다 : spring 3.1의 프로파일들 (0) | 2019.05.24 |
[SPRING] Maven 플러그인 커넥터 설정 오류 (0) | 2019.05.24 |
[SPRING] 한 컨트롤러에서 다른 컨트롤러 스프링으로 모델 데이터를 전달하는 방법 (0) | 2019.05.24 |