Spring MVC页面的HTTP状态400和错误的URL [英] Spring MVC Pages HTTP Status 400 and Incorrect URL's

查看:275
本文介绍了Spring MVC页面的HTTP状态400和错误的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中遇到了一些问题.我有一个注册表格,该表格从控制器发布到另一个页面 此页面显示注册表单中的查询结果.在结果页面上,我选择一条记录,并返回给我 数据到注册页面.用户一旦返回记录,便应该能够更新记录,或者再次执行查询.

I am experiencing some issues with the application. I have a registration form which is post to another page from the controller this page displays the results of the query from the registration form. On the results page i select a record and it returns me with the data to the registration page. The user should be able to update the record once its returned or execute a query again.

我遇到的问题是当用户在注册表单上并执行查询时,他们被发布到结果页面 结果页面会显示,但网址不会更改.注册网址为http://localhost:8084/crimeTrack/citizen_registration.htm 通过单击查询按钮将其发布到结果页面时,URL仍为http://localhost:8084/crimeTrack/citizen_registration.htm 在结果页面(具有多个记录)上单击/选择一条记录时,用户将被发布回注册页面,其中包含 选定的记录,并显示给用户,以便用户现在再次执行更新或查询,URL为http://localhost:8084/crimeTrack/getCitizen/1985121244.htm 用户现在位于注册页面上.

The problems i am having is when the user is on the registration form and executes a query they are posted to the results page the results page is displayed however the url does not change. The registration url is http://localhost:8084/crimeTrack/citizen_registration.htm when posted to the results page by clicking the query button the url is still http://localhost:8084/crimeTrack/citizen_registration.htm when a record is clicked/selected on the results page (which has several records) the user is posted back to the registration page with the selected record and it is displayed for the user to now execute an update or a query again, the url is http://localhost:8084/crimeTrack/getCitizen/1985121244.htm and the user is now on the registration page.

如果我再次单击查询/更新,我将收到 HTTP 400错误,并且网址显示为http://localhost:8084/crimeTrack/getCitizen/citizen_registration.htm/ 并且这不是Controller中的有效URL映射.我认为注册页面为时,网址应为http://localhost:8084/crimeTrack/citizen_registration.htm 要求.我不确定结果页面上的POST何时将用户带回注册页面,URL是否应为http://localhost:8084/crimeTrack/getCitizen/1985121244.htm 所附的号码是公民号码.下是我的代码,我不确定我是否正确执行了这些调用,我想解释一下我得到的结果以及 解决遇到的问题的方法;

If i click query/update again i am getting an HTTP 400 error and the url is reading http://localhost:8084/crimeTrack/getCitizen/citizen_registration.htm/ and this is not a valid URL mapping in the Controller. I think the url should be http://localhost:8084/crimeTrack/citizen_registration.htm when the registration page is requested. I am not sure when the POST from the results page takes the user back to the registration page is the url should be http://localhost:8084/crimeTrack/getCitizen/1985121244.htm the attached number is the citizen number. Under is my code i am not sure if i am doing these calls correctly and i would like an explanation for the results i am getting as well as a solution to the issues experienced;

页面是使用 jquery 提交的:

这是注册页面的示例,所有其他页面都遵循相同的模式

This is an example for the registration page and all other pages follow the same pattern

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 Not Found - http://localhost:8084/crimeTrack/citizenList.htm"

I tried using return new ModelAndView("redirect:/citizenList.htm"); in the controller when the user clicks query however i am getting 404 Not Found - 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)将输入类型更改为button而不是Submit,并添加一个onclick事件,该事件将调用您的commitPage函数并传递要调用的操作

1) change the input type to button instead of submit and add an onclick event that will call your submitPage function passing in the action to call

<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函数,以根据单击的按钮来设置操作

2) change your submitPage function to set the action based on which button was clicked

function submitPage(action){   
    document.getElementById("citizenRegistration").action = action;
    document.getElementById("citizenRegistration").method = "POST";
    document.getElementById("citizenRegistration").submit();
}

3)有2种控制器方法,一种映射到保存/更新,另一种映射到列表

3) have 2 controller methods, one mapped to save/update, the other mapped to list

@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");
    }
}

这篇关于Spring MVC页面的HTTP状态400和错误的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆