Servlet_表单处理

  1、超链接传参数

jsp页
<
a href="processing?name=张三&age=21">Servlet处理超链接</a>  //需要的参数直接加在访问地址后面
selvet页
  //
doGet()方法在处理中文乱码时不能直接request请求对象直接设置编码,而要通过字符串的构造方法。name = new String(name.getBytes("ISO8859-1"),"UTF-8"); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String age = request.getParameter("age"); //name = new String(name.getBytes("ISO8859-1"),"UTF-8");//编码转换//响应出现中文乱码这样设置response.setContentType("text/html;charset=utf-8"); response.setContentType("text/html;charset=utf-8"); response.getWriter().write("name:"+name+" age:"+age); }

   2、普通表单

<form action="processing" method="post">
        姓名:<input type="text" name="name"><br><br>
        年龄:<input type="text" name="age"><br>
        <input type="reset" value="取消">
        <input type="submit" value="提交"> 
    </form>
//doPost()在编码设置上与doGet()稍有差别,可以直接用请求对象设置。
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//设置请求对象编码
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        response.setContentType("text/html;charset=utf-8");//设置响应对象的文本类型以及编码
        response.getWriter().write("name:"+name+"  age:"+age); 
    }

  3、带有文件上传的表单

<form action="UploadServlet" method="post" enctype="multipart/form-data">
        姓名:<input type="text" name="name"><br><br>
        年龄:<input type="text" name="age"><br><br>
        上传:<input type="file" name="file"><br>
        <input type="reset" value="取消">
        <input type="submit" value="提交"> 
    </form>
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        process(req,resp);
    }
    private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        resp.getWriter().write("<strong>name:"+name+"<br>age:"+age+"<br></strong>");
        Part part = req.getPart("file");
        saveUpload(part);
        resp.getWriter().write("<h3>文件上传成功!</h3>");
    }
    private void saveUpload(Part part) {
        String fileName = getFileName(part);
        fileName = "file_"+System.nanoTime()+"_"+fileName;//防止文件名相同冲突
        
        ServletContext cxt = getServletContext();
        String realPath = cxt.getRealPath("/");  //获取路径
        File file = new File(realPath+"upload");
        if(!file.exists()){
            file.mkdirs();
        }
        File upFile = new File(file,fileName);
        FileOutputStream fos = null;
        InputStream is = null;
        byte[] buf = new byte[1024];
        int flag = -1;
        try {
            fos = new FileOutputStream(upFile);
            is = part.getInputStream();
            while((flag = is.read(buf, 0, 1024))!=-1){
                fos.write(buf, 0, flag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String getFileName(Part part) {
//查看头部文件 用于在后面取出上传文件名
// Iterator<String> it = part.getHeaderNames().iterator(); // while(it.hasNext()){ // String name = it.next(); // System.out.println(name+":"+part.getHeader(name));//从这里我们可以知道filename在最后 // } String header = part.getHeader("content-disposition");//获取头文件的参数 String[] arr = header.split("filename=");    //以filename=分割header return arr[arr.length-1].replace("\"", "");   //返回数组arr[]最后一个元素,并把""去掉 } }

这里还需要注意web.xml的配置

<multipart-config>
          <max-file-size>51200</max-file-size>   
          <max-request-size>52224</max-request-size>
          <file-size-threshold>4096</file-size-threshold>
      </multipart-config>

 

posted @ 2017-03-17 17:55  cx_davis  阅读(276)  评论(0编辑  收藏  举报