我试着找出servlet是如何工作的。 我用这段代码来设计我的servlet
formPanel.setAction(GWT.getModuleBaseURL()+ “文件上传”);
并点击
formPanel.Sumit();
在Server中,我没有理解客户端如何调用这个doPost方法。
当我点击提交按钮时,我可以在开发模式中“选择test.doc”。
请有人帮忙。
源代码。 客户端。
final FormPanel formPanel = new FormPanel();
formPanel.addFormHandler(new FormHandler() {
public void onSubmitComplete(final FormSubmitCompleteEvent event) {
// TODO Auto-generated method stub
Window.alert(event.getResults());
}
public void onSubmit(final FormSubmitEvent event) {
// TODO Auto-generated method stub
event.setCancelled(true);
}
});
final FileUpload upload = new FileUpload();
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setAction(GWT.getModuleBaseURL()+"fileupload");
formPanel.setWidget(upload);
Button btnAdd = new Button("Add");
btnAdd.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("you selected " + upload.getFilename(), null);
formPanel.submit();
}
});
服务器
public class FileUpload extends HttpServlet {
public void dopost(HttpServletRequest request,HttpServletResponse response){
ServletFileUpload upload = new ServletFileUpload();
System.out.println("pratyush file upload");
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()){
FileItemStream itemStream = iterator.next();
String name = itemStream.getFieldName();
InputStream stream = itemStream.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, len);
}
int maxFileSize = 2*(1024*1024);
if (outputStream.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
throw new RuntimeException();
}
}
}
答案 0 :(得分:2)
form.setMethod(FormPanel.METHOD_POST); //will generate <form method="post"></form>
form.setAction(GWT.getModuleBaseURL()+"fileupload");
// and now <form method="post" action="domain/testapp/fileupload"></form>
因此,当您点击提交时,其路径将与fileUploaderServler
网址格式匹配,因此com.testapp.server.FileUpload.doPost(HttpServletRequest request, HttpServletResponse response);
将被执行。