以下是我的servlet的get()和post()方法。我是servlet的新手。当我从我的客户端调用时,这个servlet创建一个新页面并覆盖我客户端中的所有html元素。我想做的就是留在我的html页面中,让servlet独自完成他的工作。
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
答案 0 :(得分:4)
我想要做的就是留在我的html页面中,让servlet独自完成他的工作。
这是使用Asynchronous call AKA Ajax的完美候选者。
学习AJAX。
答案 1 :(得分:0)
如果您希望servlet应该进行处理并且它应该显示html页面,那么您可以在servlet的try块末尾使用RequestDispatcher
。因此,当点击你的html页面中的任何动作时,它将转到servlet并执行适当的操作,并且它将再次重定向到html。
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);