Java doGet, doPost 방법 및 파일 업로드 인스턴스 코드

Java doGet, doPost 방법 및 파일 업로드
index.html

<!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

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://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>

읽어주셔서 감사합니다. 여러분에게 도움이 되었으면 좋겠습니다. 본 사이트에 대한 지지에 감사드립니다!

좋은 웹페이지 즐겨찾기