gpt4 book ai didi

javascript - AJax 调用 Controller 从 JSP 页面传递数据

转载 作者:行者123 更新时间:2023-12-02 12:03:13 33 4
gpt4 key购买 nike

我是 spring mvc 的初学者,遇到了一个错误,我无法使用 ajax 将数据传递到 Controller 。请找到代码并建议可能的解决方案。

 <form class="form-horizontal bucket-form" id="myform" method="post" >
<div class="control-label text-center">
<p class="required"><em>required fields</em></p></div>

<div class="form-group">
<label class="col-sm-3 control-label required">First Name</label>
<div class="col-sm-6">
<input type="text" name="firstname" id="firstname" class="form-control">
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Last Name</label>
<div class="col-sm-6">
<input type="text" name="lastname" id="lastname" class="form-control">
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Gender</label>
<span style="padding-left:15px">
<label class="radio-inline">
<input type="radio" name="gender" id="gender" >
Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender" >
Female
</label>
</span>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Email id</label>
<div class="col-sm-6">
<input type="email" class="form-control" placeholder="" name="mail" id="mail" >
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Profession</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="" name="prof" id="prof" >
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label ">Organisation</label>
<div class="col-sm-6">
<input type="text" name="org" id="org" class="form-control" placeholder="eg:Tech Mahindra">
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label ">Experience</label>
<div class="col-sm-6">
<input type="number" class="form-control" min="0" name="exp" id="exp" placeholder="">
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Achievements</label>
<div class="col-sm-6">
<textarea class="form-control" rows="5" name="ach" id="ach" placeholder=""></textarea>
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label required">Event ID</label>
<div class="col-sm-3">
<input type="number" class="form-control" name="eid" id="eid" >
</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label">Upload image</label>
<div class="col-sm-6">
<input type="file" class="form-control" id="forImage" accept="image/*">
</div>
</div>

<div class="form-group">
<div class="col-lg-offset-3 col-lg-6">
<button class="btn btn-primary" id="speakerSubmit" type="submit">Save</button>
<button type="reset" class="btn btn" onClick="myFunction()">Reset</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("myform").reset();
}
</script>
</div>
</div>

</form>
</div>
</section>
</section>

<div class="footer">
<div class="row">
<div style="float:left" class="col-md-6"><p
style="padding:15px">© 2017.All rights reserved | Powered by <a
href="www.techmahindra.com"> TechMahindra </a></div> </p>
<div class="social col-md-6 " style="float:right">
<a href="facebook.com" class="fa fa-facebook"></a>
<a href="twitter.com" class="fa fa-twitter"></a>
<a href="plus.google.com" class="fa fa-google"></a>
<a href="linkedin.com" class="fa fa-linkedin"></a>
</div>
</div>
</div>

</section>
<script src="js/jquery2.0.3.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="js/bootstrap.js"></script><!--bootstrap script-->
<script src="js/jquery.dcjqaccordion.2.7.js"></script>
<script src="js/scripts.js"></script>
<script src="js/jquery.nicescroll.js"></script>

<script>
$( document ).ready(function() {
$("#speakerSubmit").click(function(){
alert("create ready");
alert("data="+window.opener);
var firstname=document.getElementById("firstname").value;
alert("Firstname " +firstname );
var lastname=document.getElementById("lastname").value;
alert("lastname " +lastname);
var mail=document.getElementById("mail").value;
alert("mail " +mail);
var prof=document.getElementById("prof").value;
alert("prof " +prof);
var org=document.getElementById("org").value;
alert("org "+org);
var exp=document.getElementById("exp").value;
alert("exp " +exp);
var ach=document.getElementById("ach").value;
alert("ach "+ach);
var eid=document.getElementById("eid").value;
alert("eid "+eid);
var gender="M";
//var ge=document.getElementsByName("optionsRadios").value; //1 n as _
var details={firstname:firstname,lastname:lastname,gender:gender,mail:mail,prof:prof,org:org,exp:exp,ach:ach,eid:eid};
alert(details.FNAME+" "+details.LNAME+" "+details.GENDER+" "+details.SPKR_MAILID+" "+details.PROFESSION+" "+details.ORGN+" "+details.EXP+" "+details.ACHIEVMNTS+" "+details.SPKR_EVNT_ID);
var res=JSON.stringify(details);
alert("mytxt "+res);
//alert(res.FNAME+" "+res.LNAME+" "+res.GENDER+" "+res.SPKR_MAILID+" "+res.PROFESSION+" "+res.ORGN+" "+res.EXP+" "+res.ACHIEVMNTS+" "+res.SPKR_EVNT_ID);
$.ajax({

url: "http://localhost:8080/EMS_APP/spkr",
type: "POST",
contentType:"application/json",
data : res,
success: function(data, status) {
if(data){
//window.open("CreateEvent.jsp","_self"); //using "_self" or "_parent" will open in same window and same tab
// window.open("CreateEvent.jsp","_self");
alert("inserted");

}else{
//window.open("index.jsp","_self");
alert("not inserted");
}
},
error: function(e) {
console.log("error");
}
});


});
});


</script>

演讲者类别

package com.ems.DO;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="ems_spkr_tbl")
public class Speaker {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="SPKR_ID",nullable=false)
private int speakerId;
@Column(name="FNAME")
private String firstname;
@Column(name="LNAME")
private String lastname;
@Column(name="GENDER")
private String gender;
/*private String DOB;*/
@Column(name="SPKR_MAILID")
private String mail;
@Column(name="PROFESSION")
private String prof;
@Column(name="ORGN")
private String org;
@Column(name="EXP")
private String exp;
@Column(name="ACHIEVMNTS")
private String ach;
@Column(name="SPKR_EVNT_ID")
private int eid;

public Speaker(){

}

public Speaker(int speakerId, String firstname, String lastname, String
gender, String mail, String prof,String org, String exp, String ach, int
eid) {
super();
this.speakerId = speakerId;
this.firstname= firstname;
this.lastname = lastname;
this.gender = gender;
this.mail = mail;
this.prof = prof;
this.org = org;
this.exp = exp;
this.ach = ach;
this.eid = eid;
}


/*@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="SPKR_ID",nullable=false)*/
public int getSpeakerId() {
return speakerId;
}

public void setSpeakerId(int speakerId) {
this.speakerId = speakerId;
}



public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}



public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}



public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}



public String getMail() {
return mail;
}

public void setMail(String mail) {
this.mail = mail;
}



public String getProf() {
return prof;
}

public void setProf(String prof) {
this.prof = prof;
}



public String getOrg() {
return org;
}

public void setOrg(String org) {
this.org = org;
}



public String getExp() {
return exp;
}

public void setExp(String exp) {
this.exp = exp;
}



public String getAch() {
return ach;
}

public void setAch(String ach) {
this.ach = ach;
}


public int getEid() {
return eid;
}

public void setEid(int eid) {
this.eid = eid;
}
}

扬声器 Controller

Controller 类,我尝试使用 @RequestParam("att-name") 注释读取从 jsp 页面传递的值,并在 ("attribute-name") 中使用相同的名称,但遇到了 400 Status 等错误。

     package com.ems.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ems.DO.Speaker;
import com.ems.service.SpeakerService;

@Controller
public class SpeakerController {

@Autowired
SpeakerService speakerService;


@RequestMapping(value="/spkr",method=RequestMethod.POST)

public @ResponseBody boolean speakerAdd(@RequestParam("firstname") String
FNAME,@RequestParam("lastname") String LNAME,@RequestParam("gender")
String GENDER,@RequestParam("mail") String
SPKR_MAILID,@RequestParam("prof") String PROFESSION,@RequestParam("org")
String ORGN,@RequestParam("exp") String EXP,@RequestParam("ach") String
ACHIEVEMENTS,@RequestParam("eid") String eventid) {

System.out.println("in speakercontrol");
Speaker s=new Speaker();
int i=Integer.parseInt(eventid);
/*s.setfirstname(FNAME);
s.setlastname(LNAME);
s.setgender(GENDER);
s.setspkrmailid(SPKR_MAILID);
s.setprofession(PROFESSION);
s.setorgn(ORGN);
s.setexp(EXP);
s.setachievements(ACHIEVEMENTS);
s.setspkrevntid(eventid);*/
s.setFirstname(FNAME);
s.setLastname(LNAME);
s.setGender(GENDER);
s.setMail(SPKR_MAILID);
s.setProf(PROFESSION);
s.setOrg(ORGN);
s.setExp(EXP);
s.setAch(ACHIEVEMENTS);
s.setSpeakerId(i);
System.out.println(eventid);
System.out.println("Ajax");
System.out.println("----In controller----");
boolean status=speakerService.add(s);
return false;
}
}

SpeakerserviceImpl

 package com.ems.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ems.DO.Speaker;
import com.ems.dao.SpeakerDao;

@Repository
public class SpeakerServiceImpl implements SpeakerService{

@Autowired
SpeakerDao speakerDao;

public SpeakerServiceImpl() {
super();
// TODO Auto-generated constructor stub
}

public boolean add(Speaker s) {


//System.out.println(fname +" "+skill);
System.out.println("----In service----");
boolean status=speakerDao.add(s);
return status;

}}

SpeakerdaoImpl

   package com.ems.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ems.DO.Speaker;

@Repository
public class SpeakerDaoImpl implements SpeakerDao{

@Autowired
private SessionFactory sessionFactory;


public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public boolean add(Speaker s) {
boolean status=false;
Session session = sessionFactory.getSessionFactory().openSession();
session.save(s);
System.out.println(s.getAch()+" "+s.getMail()+" "+s.getSpeakerId());
System.out.println("one record inserted");
return true;
}
}

错误结果

客户端发送的请求在语法上不正确状态-400

最佳答案

Controller

@PostMapping("EMS_APP/spkr")
public ResponseEntity addSpeaker(@RequestBody SpeakerAddRequest request) {
Speaker speaker = new Speaker();
speaker.setFirstName(request.getFirstName());
...
}

发生了什么?

  • @PostMapping@RequestMapping(method = RequestMethod.POST) 的缩写。
    @PostMapping("EMS_APP/spkr")@RequestMapping(value = "EMS_APP/spkr", method = RequestMethod.POST) 的缩写。
    这指定了将调用该方法的 URL 和 HTTP 方法。

  • @RequestBody 用于将 POST 请求的负载映射到 POJO。在本例中,POJO 是 SpeakerAddRequest

  • 您滥用了@RequestParam@RequestParam 用于映射 URL 中的参数。例如:

    // GET request with URL ../EMS_APP/spkr?name=foo

    @GetMapping("EMS_APP/spkr")
    public ResponseEntity<Speaker> getSpeakerByName(@RequestParam("name") String speakerName) {
    // speakerName== "foo"
    }

数据传输对象(DTO)

public class SpeakerAddRequest {

@JsonProperty("firstname")
private String firstName;
...

public String getFirstName() {
return firstName;
}
}

发生了什么?

POST 负载到 POJO 的映射发生在这里。例如,property"firstname": "John" 将映射到 private String firstName,因为属性键与 @JsonProperty< 中指定的键相同。/

表格

替换你的ajax调用

$.ajax({
...
});

$.post("EMS_APP/spkr", $("#myform").serialize());

发生了什么?

不用手动映射所有表单元素,而是使用它自动将表单转换为正确的负载并将其作为 POST 请求发送到指定的 URL。

关于javascript - AJax 调用 Controller 从 JSP 页面传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094586/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com