欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-11 19:48:13
java doget, dopost方法和文件上传 index.html

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>

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