Java 如何通过单击控制器不同的同一JSP页面的两个不同按钮来开发两个调用ajax?
我正在春季开发一份员工登记表。我使用了两个ajax调用,一个用于员工信息,另一个用于上传e文件(图像),并将它们存储在单个jsp页面和单个控制器中的特定文件夹中。这是我的jsp页面:Java 如何通过单击控制器不同的同一JSP页面的两个不同按钮来开发两个调用ajax?,java,ajax,jsp,spring-mvc,Java,Ajax,Jsp,Spring Mvc,我正在春季开发一份员工登记表。我使用了两个ajax调用,一个用于员工信息,另一个用于上传e文件(图像),并将它们存储在单个jsp页面和单个控制器中的特定文件夹中。这是我的jsp页面: function onuploadCall(){ var file = $('[name="file"]'); console.log(file); var filename = $.trim(file.val()); console.log(filename); //va
function onuploadCall(){
var file = $('[name="file"]');
console.log(file);
var filename = $.trim(file.val());
console.log(filename);
//var imgContainer = $('#imgContainer');
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
$.ajax({
url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
type: "POST",
async:true,
data: formData,
enctype: "multipart/form-data",
processData: false,
modelAttribute:'uploadedFile',
contentType: true,
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
/* }).done(function(data) {
// imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
alert("success");
// imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
}); */
}
function madeAjaxCall(){
array();
var gender = $('#gender').val();
var blood = $('#blood').val();
$.ajax({
type: "post",
url: "http://localhost:8080/EmployeeRegistrationForm/employee",
cache: false,
async:false,
data:'name=' + $("#name").val()
+"&fname=" + $("#fname").val()
+"&mname=" + $("#mname").val()
+"&nid=" + $("#nid").val()
+"&age=" + $("#age").val()
+"&blood=" + blood
+"&gender=" + gender
+"&caddress=" + $("#caddress").val()
+"&paddress=" + $("#paddress").val()
+"&paddress=" + $("#paddress").val()
+"&pdegree=" + $("#pdegree").val()
+"&puniversity=" + $("#puniversity").val()
+"&pyear="+ $("#pyear").val()
+"&presult=" + $("#presult").val()
+"&mdegree=" + $("#mdegree").val()
+"&muniversity=" + $("#muniversity").val()
+"&mresult=" + $("#mresult").val()
+"&myear=" + $("#myear").val()
+"&bdegree=" + $("#bdegree").val()
+"&buniversity=" + $("#buniversity").val()
+"&bresult=" + $("#bresult").val()
+"&byear=" + $("#byear").val()
+"&hdegree=" + $("#hdegree").val()
+"&college=" + $("#college").val()
+"&hresult=" + $("#hresult").val()
+"&hyear=" + $("#hyear").val()
+"&sdegree=" + $("#sdegree").val()
+"&school=" + $("#school").val()
+"&sresult=" + $("#sresult").val()
+"&syear=" + $("#syear").val()
+"&date=" + $("#date").val()
+"&department=" + $("#department").val()
+"&location=" + $("#location").val()
+"&company=" + company
+"&from=" + from
+"&to=" + to
+"&year=" + year
+"&organization=" + organization
+"&topic=" + topic
+"&duration=" + duration,
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
}
函数onuploadCall(){
var file=$('[name=“file”]');
console.log(文件);
var filename=$.trim(file.val());
log(文件名);
//var imgContainer=$(“#imgContainer”);
var formData=new formData();
formData.append('file',jQuery('input[type=file]')[0].files[0]);
$.ajax({
url:“http://localhost:8080/EmployeeRegistrationForm/echofile",
类型:“POST”,
async:true,
数据:formData,
enctype:“多部分/表单数据”,
processData:false,
modelAttribute:'uploadedFile',
contentType:true,
成功:功能(响应){
var obj=JSON.parse(响应);
警报(响应);
},
错误:函数(){
警报(“请求时出错…”;
}
});
/*}).完成(函数(数据){
//imgContainer.html(“”);
var img=“”;
警惕(“成功”);
//imgContainer.append(img);
}).fail(函数(jqXHR,textStatus){
//警报(jqXHR.responseText);
警报('文件上载失败…');
}); */
}
函数madeAjaxCall(){
数组();
var gender=$('#gender').val();
var blood=$('#blood').val();
$.ajax({
类型:“post”,
url:“http://localhost:8080/EmployeeRegistrationForm/employee",
cache:false,
async:false,
数据:'name='+$(“#name”).val()
+“&fname=“+$(“#fname”).val()
+“&mname=“+$(“#mname”).val()
+“&nid=”+$(“#nid”).val()
+“&age=“+$(“#age”).val()
+“&blood=“+blood”
+“&gender=“+gender
+“&CadAddress=“+$(“#CadAddress”).val()
+“&paddress=”+$(“#paddress”).val()
+“&paddress=”+$(“#paddress”).val()
+“&pdegree=“+$(“#pdegree”).val()
+“&puniversity=“+$(“#puniversity”).val()
+“&pyear=”+$(“#pyear”).val()
+“&presult=”+$(“#presult”).val()
+“&mdegree=“+$(“#mdegree”).val()
+“&muniversity=“+$(“#muniversity”).val()
+“&mresult=“+$(“#mresult”).val()
+“&myear=”+$(“#myear”).val()
+“&bdegree=“+$(“#bdegree”).val()
+“&buniversity=“+$(“#buniversity”).val()
+“&bresult=“+$(“#bresult”).val()
+“&byear=”+$(“#byear”).val()
+“&hdegree=“+$(“#hdegree”).val()
+“&college=“+$(“#college”).val()
+“&hresult=“+$(“#hresult”).val()
+“&hyear=”+$(“#hyear”).val()
+“&sdegree=“+$(“#sdegree”).val()
+“&school=“+$(“#school”).val()
+“&sresult=“+$(“#sresult”).val()
+“&syear=”+$(“#syear”).val()
+“&date=“+$(“#date”).val()
+“&department=”+$(“#department”).val()
+“&location=”+$(“#location”).val()
+“&company=“+公司”
+“&from=“+from”
+“&to=“+to”
+“&year=“+year”
+“&organization=“+organization
+“&topic=“+topic
+“&duration=“+duration,
成功:功能(响应){
var obj=JSON.parse(响应);
警报(响应);
},
错误:函数(){
警报(“请求时出错…”;
}
});
}
这是我的控制器:
@Controller
public class imageUploadController {
@RequestMapping(value = "/echofile",method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response , @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile multipartFile = request.getFile("file");
MultipartFile file = upldfile.getFile();
String fileName = multipartFile.getOriginalFilename();
System.out.println("vcvvvvvvvv"+fileName);
upldfile.setFile(file);
Long size = file.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
inputStream = file.getInputStream();
File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
// byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
@控制器
公共类imageUploadController{
@RequestMapping(value=“/echofile”,method=RequestMethod.POST)
public@ResponseBody HashMap echoFile(multipathttpservletrequest,
HttpServletResponse,@ModelAttribute(“uploadedFile”)uploadedFile upldfile)引发异常{
InputStream InputStream=null;
OutputStream OutputStream=null;
MultipartFile MultipartFile=request.getFile(“文件”);
MultipartFile file=upldfile.getFile();
字符串文件名=multipartFile.getOriginalFilename();
System.out.println(“vcvv”+文件名);
upldfile.setFile(文件);
Long size=file.getSize();
String contentType=multipartFile.getContentType();
InputStream=multipartFile.getInputStream();
byte[]bytes=IOUtils.toByteArray(流);
HashMap=newHashMap();
map.put(“fileoriginalsize”,大小);
map.put(“contenttype”,contenttype);
put(“base64”,新字符串(Base64Utils.encode(bytes));
试一试{
inputStream=file.getInputStream();
File newFile=新文件(“E:/Java_项目/EmployeeRegistrationForm/src/main/webapp/resources/image/”+文件名);
如果(!newFile.exists()){
createNewFile();
}
outputStream=新文件outputStream(新文件);
int read=0;
//字节[]字节=新字节[1024];
而((read=inputStream.read(bytes))!=-1){
outputStream.write(字节,0,读取);
}
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回图;
}
}
但这表明了错误:
EVERE:Servlet.service()用于具有路径的上下文中的Servlet[dispatcher]
[/EmployeeRegistrationForm]引发异常[请求处理]
失败;嵌套异常为
org.springframework.web.bind.annotation.support.HandlerMethodInvocationException:
未能调用处理程序方法[pu]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="EmployeeRegistrationForm.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
function uploadImage() {
var file = $('[name="file"]');
//var imgContainer = $('#imgContainer');
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
type: "POST",
data: new FormData(document.getElementById("fileForm")),
//data: formData,
enctype: 'multipart/form-data',
processData: false,
aync: false,
modelAttribute:'uploadedFile',
headers: {'Content-Type': 'multipart/form-data'},
contentType: false,
/* }).done(function(data) {
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
alert("success");
}).fail(function(jqXHR, textStatus) {
alert('File upload failed ...');
}); */
success: function(response){
var obj = JSON.parse(response);
alert(response);
},
error: function(){
alert('Error while request..');
}
});
}
@RequestMapping(value = "/echofile",method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> echoFile(HttpServletRequest request,
HttpServletResponse response , @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
if(request instanceof MultipartHttpServletRequest){
InputStream inputStream = null;
OutputStream outputStream = null;
// MultipartFile multipartFile = request.getFile("file");
MultipartFile file = upldfile.getFile();
String fileName = file.getOriginalFilename();
System.out.println("vcvvvvvvvv"+fileName);
upldfile.setFile(file);
Long size = file.getSize();
String contentType = file.getContentType();
InputStream stream = file.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
inputStream = file.getInputStream();
File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] byt = new byte[1024];
while ((read = inputStream.read(byt)) != -1) {
outputStream.write(byt, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map;
}