简体   繁体   English

在Spring MVC中使用jQuery进行URL映射

[英]URL mapping using jquery in spring mvc

This somewhat confusing but it is my project requirement. 这有点令人困惑,但这是我的项目要求。 I am using spring mvc and jquery. 我正在使用spring mvc和jquery。 Now I have to post the form and expose the data to back end using ajax call of jquery for this my jquery is 现在,我必须发布表单,并使用jquery的ajax调用将数据公开到后端,因为我的jquery是

home='<%=request.getContextPath()%>';

$('#userReg').submit(function(event){
    var add = {}
    add["type"] = $("#type").val();
    add["name"] = $("#companyName").val();
    add["regNumber"] = $("#regNumber").val();
    add["dob"] = $("#dob").val();
    add["email"] = $("#email").val();
    add["password"] = $("#password").val();
    add["confirmPassword"] = $("#cpassword").val();
    add["line1"] = $("#line1").val();
    add["line2"] = $("#line2").val();
    add["state"] = $("#state").val();
    add["country"] = $("#country").val();
    add["zipCode"] = $("#zipCode").val();
    console.log("search: ", add);
    event.preventDefault();
    $.ajax({
        type : "POST",
         headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            },
            url : home+"/addCompany",
        data : JSON.stringify(add),
        dataType : 'json',
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            alert(data)

        },
        error : function(e) {
            console.log("ERROR: ", e);
            alert(e);

        },done : function(e) {
            console.log("DONE");
        }
});
});

and corresponding method 和相应的方法

 @RequestMapping(value="/addCompany",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
   public@ResponseBody String userLogin(HttpServletRequest req,@RequestBody CompanyRegVO user){
    logger.debug("signUp user:"+user);
     // get reCAPTCHA request param
    String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
    boolean isVerified= Verify.verifyGcaptchResponse(gRecaptchaResponse);
    ObjectMapper mapper=new ObjectMapper();
    String jsonString="";       
    System.out.println("signUp user:"+user);
    Integer id=null;
    try{
        if(isVerified){
            id = signupHandler.process(user);
            if(id!=null){
                logger.debug("ID in controller:"+id);

                emailHandler.sendVerificationMail(id,user.getEmail());
                System.out.println("user create successfully"); 

            }
            jsonString=mapper.writeValueAsString("User creaated successfully");

        }
         else
        jsonString= mapper.writeValueAsString("please verify that you are not a robot");
    } catch (JsonGenerationException e) {

        e.printStackTrace();
    } catch (JsonMappingException e) {

        e.printStackTrace();
    } catch (IOException e) {
                e.printStackTrace();
    } catch (Exception e) {
        try {
            jsonString=mapper.writeValueAsString(e.getMessage());
        } catch (JsonProcessingException e1) {

        }
        return jsonString;
    }


    return "success";

   }

Now my form is mapped with this URL 现在,我的表单已与此URL映射

@RequestMapping(value="/signUp",method=RequestMethod.GET)
   public String register(Model model){
    CompanyRegVO user=new CompanyRegVO();
    model.addAttribute("userForm", user);
    return "signUp";
   }

When I submit my form I expected that my jquery code will execute will invoke my upper one method but it inovkes above get method and return me signUp page with my data as query parameter. 当我提交表单时,我希望我的jquery代码将执行,将调用我的上一个方法,但它会调用get方法上方,并以我的数据作为查询参数返回signUp页面。 Now if I comment mapping for "/signUp" my server is giving 404 error. 现在,如果我评论“ / signUp”的映射,我的服务器将显示404错误。 since page is mapped to that URL. 因为页面已映射到该URL。 So any one can please tell what is remedy for this kind of situation jquery or spring?? 那么任何人都可以告诉我这种情况jquery或spring的补救方法是什么?

Edit 1: below is my form 编辑1:下面是我的表格

<form class="form-horizontal" name="userReg"  id="userReg">
 <div class="form-group">
 <label class="col-sm-2 control-label">Company Name</label>
 <div class="col-sm-4">
 <input  name="companyName" type="text"   class="form-control" id="companyName" placeholder="Name" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">Registration number</label>
 <div class="col-sm-4">
 <input  name="RegNumber" type="number" required="required"  class="form-control" id="regNumber" placeholder="Registration number" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">Address line 1</label>
 <div class="col-sm-4">
 <input  name="line1" type="text" required="required"  class="form-control" id="line1" placeholder="line1" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">Address line 2</label>
 <div class="col-sm-4">
 <input  name="line2" type="text"   class="form-control" id="line2" placeholder="line2" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">Zip code</label>
 <div class="col-sm-4">
 <input  name="zipCode" type="number" required="required"  class="form-control" id="zipCode" placeholder="zip code" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">State</label>
 <div class="col-sm-4">
 <input  name="state" type="text" required="required"  class="form-control" id="state" placeholder="State" />
 </div>
</div>
<br>
 <div class="form-group">
 <label class="col-sm-2 control-label">Country</label>
 <div class="col-sm-4">
 <input  name="country" type="text" required="required"  class="form-control" id="country" placeholder="country" />
 </div>
</div>
      <br>         
 <div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input name="email" type="email" class="form-control" id="email" placeholder="Email" />
</div>
 </div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Date of Birth(dd-mm-yyyy)</label>
<div class="col-sm-4">
<input name="dob"  type="text" class="form-control" id="dob" placeholder="Date of birth" />
</div>
</div>

<br>
<div class="form-group">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input name="password" id="password" maxlength="12" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,12})" required="required" type="password" class="form-control" id="password" placeholder="password" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-4">
<input name="confirmPassword" id="cpassword"  maxlength="12" required="required" type="password" class="form-control" id="cpassword" placeholder="confirm password" />
<span id='message'></span>
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">User type</label>
<div class="col-sm-4">
<select class="form-control" id="type" name="type" >
<option selected="selected">--select--</option>
 <option  value="user" >CEO</option>
 <option value="admin">HR</option>

</select>
</div>
</div>
<br>
<div class="form-group">

<div class="g-recaptcha"
            data-sitekey="my-public key"></div>
</div>
<br>

<div class="col-md-6 center-block">

<input type="submit" class="btn-lg btn-primary center-block" value="save">
</div>
 </form>

When use <input type="submit" ..... /> it will submit your form according to your form action url. 使用<input type="submit" ..... /> ,它将根据您的form操作URL提交您的表单。 eg something.html 例如something.html

So change the and add a click listener. 因此,更改并添加一个点击监听器。

<input type="button" onclick="_submit()"/>

and your js would be 和你的js

function _submit(){
    // submit your form via ajax.
}

This should submit your form with your specified url. 这应该使用您指定的网址提交表单。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM