Java doGet, doPost方法和文件上传实例代码
JavadoGet,doPost方法和文件上传
index.html
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>Title</title> </head> <body> <formaction="/test"method="post"enctype="multipart/form-data"> <table> <tr> <td> 用户名: </td> <td> <inputname="username"type="text"> </td><tr> <td> 密  码: </td> <tdcolspan="2"> <inputname="password"type="password"> </td> </tr> <tralign="center"> <td><inputname="login"type="submit"value="登陆"></td> <td><inputname="register"type="reset"value="重置"></td> </tr> <tr> <tdcolspan="2"> <inputtype="radio"name="sex"value="male">男 </td><tdcolspan="2"> <inputtype="radio"name="sex"value="female">女 </td> </tr> <tr> <tdcolspan="2"> <inputname="upload"type="file"> </td> </tr> </table> </form> </body> </html>
TestServlet.Java
importorg.apache.commons.fileupload.FileItem;
importorg.apache.commons.fileupload.FileUploadException;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
importorg.apache.commons.fileupload.servlet.ServletFileUpload;
importjavax.servlet.ServletException;
importjavax.servlet.ServletInputStream;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjava.net.URLDecoder;
importjava.net.URLEncoder;
importjava.util.Enumeration;
importjava.util.List;
/**
*Project:Day15_Web
*Created:Lulu
*Date:2016/8/16
*/
@WebServlet(name="TestServlet")
publicclassTestServletextendsHttpServlet{
privateFileroot_upload;
publicTestServlet(){
root_upload=newFile("C:/temp");
if(!root_upload.exists()){
root_upload.mkdirs();
}
}
//两种链接方式doPostdoGet
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
ServletOutputStreamos=response.getOutputStream();
StringBuilderbuilder=newStringBuilder();
builder.append("<html>");
builder.append("<head>");
builder.append("<metacharset=\"utf-8\">");
builder.append("<title>测试Servlet</title>");
builder.append("</head>");
builder.append("<body>");
Enumeration<String>names=request.getHeaderNames();
while(names.hasMoreElements()){
Stringname=names.nextElement();
builder.append(name)
.append(":")
.append(request.getHeader(name))
.append("<br>");
}
DiskFileItemFactoryfactory=newDiskFileItemFactory();
factory.setSizeThreshold(10);//设置未保存在临时路径的最大值
factory.setRepository(newFile("C:/temp/temp"));//超过上述最大值后保存的临时路径
ServletFileUploadupload=newServletFileUpload(factory);
try{
List<FileItem>list=upload.parseRequest(request);//上传的文件列表
for(FileItemitem:list){
builder.append(item.getFieldName())
.append(":")
.append(item.isFormField()?item.getString():item.getName())//判断是不是属性,如果是属性,就
.append("<br>");
if(!item.isFormField()){
Filefile=newFile(root_upload,item.getName());
builder.append(file.getAbsolutePath()).append("<br>");
item.write(file);
}
}
}catch(FileUploadExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
//可以从输入流中读取数据
//ServletInputStreamis=request.getInputStream();
//byte[]buffer=newbyte[8192];
//intlen;
//ByteArrayOutputStreambos=newByteArrayOutputStream();
//while((len=is.read(buffer))!=-1){
//bos.write(buffer,0,len);
//}
//builder.append("InputStream:")
//.append(bos.toString("UTF-8"))
//.append("<br>");
//builder.append("<h1>Post的请求参数</h1>").append("<br/>");
//
//Enumeration<String>parameterNames=request.getParameterNames();
//while(parameterNames.hasMoreElements()){
//Stringname=parameterNames.nextElement();
//builder.append(name)
//.append(":")
//.append(request.getParameter(name))
//.append("<br/>");
//}
//接收来自浏览器的文件,
os.write(builder.toString().getBytes("UTF-8"));
//参数列表:待转码的字符串,字符编码
URLEncoder.encode("&","UTF-8");
URLDecoder.decode("%26","UTF-8");
builder.append("</body>");
builder.append("</html>");
}
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doPost(request,response);
}
}
web.xml
<?xmlversion="1.0"encoding="UTF-8"?> <web-appxmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>org.lulu.learn.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> </web-app>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!