Java doGet, doPost方法和文件上传实例代码

时间:2021-09-05 02:56:03

Java doGet, doPost方法和文件上传

index.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<form action="/test" method="post" enctype="multipart/form-data">
  <table >
    <tr>
      <td>
        用户名:
      </td>
      <td>
        <input name="username" type="text">
      </td>      <tr>
      <td>
        密&nbsp&nbsp码:
      </td>
      <td colspan="2">
        <input name="password" type="password">
      </td>
    </tr>
    <tr align="center">
      <td><input name="login" type="submit" value="登陆"></td>
      <td><input name="register" type="reset" value="重置"></td>
    </tr>
 
    <tr>
      <td colspan="2">
        <input type="radio" name="sex" value="male">男
      </td> <td colspan="2">
        <input type="radio" name="sex" value="female">女
      </td>
    </tr>
    <tr>
      <td colspan="2" >
        <input name="upload" type="file">
      </td>
    </tr>
 
  </table>
 
</form>
</body>
</html>

TestServlet.Java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.List;
 
/**
 * Project: Day15_Web
 * Created: Lulu
 * Date: 2016/8/16
 */
@WebServlet(name = "TestServlet")
public class TestServlet extends HttpServlet {
  private File root_upload;
  public TestServlet() {
    root_upload = new File("C:/temp");
    if (!root_upload.exists()) {
      root_upload.mkdirs();
    }
  }
 
 
  //两种链接方式 doPost doGet
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    ServletOutputStream os = response.getOutputStream();
    StringBuilder builder = new StringBuilder();
 
    builder.append("<html>");
    builder.append("<head>");
    builder.append("  <meta charset=\"utf-8\">");
    builder.append("  <title>测试Servlet</title>");
    builder.append("</head>");
    builder.append("<body>");
 
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = names.nextElement();
      builder.append(name)
          .append(":")
          .append(request.getHeader(name))
          .append("<br>");
    }
 
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(10);//设置未保存在临时路径的最大值
    factory.setRepository(new File("C:/temp/temp"));//超过上述最大值后保存的临时路径
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
      List<FileItem> list = upload.parseRequest(request);//上传的文件列表
 
      for (FileItem item : list) {
        builder.append(item.getFieldName())
            .append(":")
            .append(item.isFormField() ? item.getString() : item.getName())//判断是不是属性, 如果是属性, 就
            .append("<br>");
        if (!item.isFormField()) {
          File file = new File(root_upload, item.getName());
          builder.append(file.getAbsolutePath()).append("<br>");
          item.write(file);
        }
      }
 
    } catch (FileUploadException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
 
 
    //可以从输入流中读取数据
//    ServletInputStream is = request.getInputStream();
//    byte[] buffer = new byte[8192];
//    int len ;
//    ByteArrayOutputStream bos= new ByteArrayOutputStream();
//    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()) {
//      String name = 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>");
 
  }
 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }
}

web.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
     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>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!