带有文件上传的表单数据写入到数据库中(表单带回显功能)

来源:互联网 发布:程序员的未来规划 编辑:程序博客网 时间:2024/05/14 19:32

 index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
 
  <body>
    <h2>用户注册第一步</h2>
    <form name="" action="UserServlet" method="post">
    <table border=1 width=500>
    <tr><td>用户ID:</td><td><input name="uid" type="text"/></td></tr>
    <tr><td>用户名:</td><td><input name="uname" type="text"/></td></tr>
    <tr><td colspan="2"><input type="submit" value="下一步"/></td></tr>
    </table>
    <input name="type" type="hidden" value="1"/>
    </form>
  </body>
</html>

 

second.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'second.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
   
    <h2>用户注册第二步</h2>
    <font color="red"><%=request.getAttribute("note")==null?"":request.getAttribute("note") %></font>
    <form name="" action="UserServlet?type=2" method="post" enctype="multipart/form-data">
    <table border=1 width=500>
    <tr><td>密码:</td><td><input name="password" type="password"/></td></tr>
    <tr><td>确认密码:</td><td><input name="repassword" type="password"/></td></tr>
    <tr><td>性别:</td><td><input name="sex" type="radio" checked="checked" value="男"/>男<input name="sex" type="radio" value="女"/>女</td></tr>
    <tr><td>年龄:</td><td><input name="age" type="text"/></td></tr>
    <tr><td>提示信息:</td><td><select name="remaind"><option>我妈妈的名字</option><option>我的出生地</option></select></td></tr>
    <tr><td>提示答案:</td><td><input name="answer" type="text"/></td></tr>
    <tr><td>联系电话:</td><td><input name="phone" type="text"/></td></tr>
    <tr><td>邮箱:</td><td><input name="email" type="text"/></td></tr>
    <tr><td>接受的信息:</td><td><input name="information" type="checkbox" value="新闻"/>新闻<input name="information" type="checkbox" value="广告"/>广告<input name="information" type="checkbox" value="招聘"/>招聘</td></tr>
    <tr><td>头像:</td><td><input name="profile" type="file"/></td></tr>
    <tr><td colspan="2"><input type="submit" value="完成"/></td></tr>
    </table>
    </form>
  </body>
</html>

 

third.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.qrsx.javabean.Users"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'third.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    <h2>注册信息确认 </h2>
   
    <%Users u=(Users)session.getAttribute("users"); %>
    <form action="UserServlet?type=3" method="post">
    <table border=1 width=500>
    <tr><td>用户ID:</td><td><%=u.getUid() %></td></tr>
    <tr><td>用户名:</td><td><%=u.getUname()%></td></tr>
    <tr><td>密码:</td><td><%=u.getPassword() %></td></tr>
    <tr><td>性别:</td><td><%=u.getSex()%></td></tr>
    <tr><td>年龄:</td><td><%=u.getAge()%></td></tr>
    <tr><td>提示信息:</td><td><%=u.getRemaind()%></td></tr>
    <tr><td>提示答案:</td><td><%=u.getAnswer()%></td></tr>
    <tr><td>联系电话:</td><td><%=u.getPhone()%></td></tr>
    <tr><td>邮箱:</td><td><%=u.getEmail()%></td></tr>
    <tr><td>接受的信息:</td><td><%=u.getInformationstr()%></td></tr>
    <tr><td>头像:</td><td><img alt="" src="images/<%=u.getProfile()%>" width=200 height=200></td></tr>
    <tr><td colspan="2"><input type="submit" value="确认提交"/></td></tr>
    </table>
    </form>
  </body>
</html>

 

error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'error.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    error!<br>
  </body>
</html>

 

success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'error.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
    success!<br>
  </body>
</html>

 

lessonmvc\src\com\qrsx\javabean包

Users.java

package com.qrsx.javabean;

public class Users {

 private int uid;
 
 private String uname;
 
 private String password;
 
 private String repassword;
 
 private String sex;
 
 private int age;
 
 private String remaind;
 
 private String answer;
 
 private String phone;
 
 private String email;
 
 private String[] information;
 
 private String informationstr;
 
 private String profile;

 public int getUid() {
  return uid;
 }

 public void setUid(int uid) {
  this.uid = uid;
 }

 public String getUname() {
  return uname;
 }

 public void setUname(String uname) {
  this.uname = uname;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getRepassword() {
  return repassword;
 }

 public void setRepassword(String repassword) {
  this.repassword = repassword;
 }

 public String getSex() {
  return sex;
 }

 public void setSex(String sex) {
  this.sex = sex;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getRemaind() {
  return remaind;
 }

 public void setRemaind(String remaind) {
  this.remaind = remaind;
 }

 public String getAnswer() {
  return answer;
 }

 public void setAnswer(String answer) {
  this.answer = answer;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String[] getInformation() {
  return information;
 }

 public void setInformation(String[] information) {
  this.information = information;
 }

 public String getInformationstr() {
  return informationstr;
 }

 public void setInformationstr(String informationstr) {
  this.informationstr = informationstr;
 }

 public String getProfile() {
  return profile;
 }

 public void setProfile(String profile) {
  this.profile = profile;
 }
 
 
}

 

lessonmvc\src\com\qrsx\servlet包

UserServlet.java

package com.qrsx.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.PreparedStatement;
import com.qrsx.javabean.Users;
import com.qrsx.util.DBUtil;
import com.qrsx.util.ImgWriteUtil;
import com.qrsx.util.UploadUtil;

public class UserServlet extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public UserServlet() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  this.doPost(request, response);
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //对post请求设置编码
  request.setCharacterEncoding("utf-8");
  response.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  HttpSession session=request.getSession();
  
  String type=request.getParameter("type");
  
  if("1".equals(type)){
   String uid=request.getParameter("uid");
   String uname=request.getParameter("uname");
   PrintWriter out=response.getWriter();
   if(uid.equals("") || uname.equals("")){
    out.print("<script language='javascript'>");
    out.print("alert('uid或用户名不能为空!');");
    out.print("window.location.href='index.jsp';");
    out.print("</script>");
   }else{
    Users u=new Users();
    u.setUid(Integer.parseInt(uid.toString()));
    u.setUname(uname);
    
    session.setAttribute("users", u);
    
    response.sendRedirect("second.jsp");
   }
  }else if("2".equals(type)){
   //获得除上传文件域以外的普通文本域的值
      UploadUtil uploadUtil=new UploadUtil(request);
      String password=uploadUtil.getParameter("password");
      String repassword=uploadUtil.getParameter("repassword");
      String sex=uploadUtil.getParameter("sex");
      String age=uploadUtil.getParameter("age");
      String remaind=uploadUtil.getParameter("remaind");
      String answer=uploadUtil.getParameter("answer");
      String phone=uploadUtil.getParameter("phone");
      String email=uploadUtil.getParameter("email");
      List<String> information=uploadUtil.getParameterValues("information");
      //获得上传文件的原始名字
      BufferedInputStream inputStream=uploadUtil.getInputStream("profile");
      String fileName=uploadUtil.getFileName("profile");
      System.out.print("原始文件名:"+fileName);
     
      Calendar calendar =Calendar.getInstance();
   String name=String.valueOf(calendar.getTimeInMillis())+fileName.substring(fileName.lastIndexOf("."));
   System.out.print("新文件名:"+name);
   
   String filepath=request.getRealPath("/images")+"/"+name;
   System.out.print("上传文件的保存地址和新名称:"+filepath);
   //读取原文件的内容写入到新文件中,即:完成文件的内容复制
   File file=new File(filepath);
   OutputStream outStream=new FileOutputStream(file);
   BufferedOutputStream outputStream =new BufferedOutputStream(outStream);
   ImgWriteUtil imgUtil=new ImgWriteUtil();
   imgUtil.writeImg(inputStream, outputStream);
   
   Users u=new Users();
   if(session.getAttribute("users")!=null)
    u=(Users)session.getAttribute("users");
   u.setPassword(password);
   u.setSex(sex);
   u.setAge(age.toString()==null?0:Integer.parseInt(age.toString()));
   u.setAnswer(answer);
   u.setEmail(email);
   u.setPhone(phone);
   u.setProfile(name);
   u.setRemaind(remaind);
   String informationstr="";
   for(String str:information){
    informationstr=informationstr+str+" ";
   }
   u.setInformationstr(informationstr);
   
   session.setAttribute("users", u);
   
   //结果页面的专向
   response.sendRedirect("third.jsp");
  }else if("3".equals(type)){
   Users u=(Users)session.getAttribute("users");
   
   Connection conn=DBUtil.getConnection();
   String sql="insert into " +
   "tb_users(uid,uname,password,sex,age,remaind,answer,phone,email,information,profile)" +
   " values(?,?,?,?,?,?,?,?,?,?,?)";
   try {
    PreparedStatement pstmt=conn.prepareStatement(sql);
    pstmt.setInt(1,u.getUid());
    pstmt.setString(2, u.getUname());
    pstmt.setString(3, u.getPassword());
    pstmt.setString(4, u.getSex());
    pstmt.setInt(5, u.getAge());
    pstmt.setString(6, u.getRemaind());
    pstmt.setString(7, u.getAnswer());
    pstmt.setString(8, u.getPhone());
    pstmt.setString(9, u.getEmail());
    pstmt.setString(10, u.getInformationstr());
    pstmt.setString(11, u.getProfile());
    pstmt.execute();
   } catch (SQLException e) {
    e.printStackTrace();
    response.sendRedirect("error.jsp");
   }
   response.sendRedirect("success.jsp");
   
  }
  
   
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

 

 

lessonmvc\src\com\qrsx\util包

DBUtil.java

package com.qrsx.util;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
 private static final String DRIVERCLASS="com.mysql.jdbc.Driver";
 private static final String JDBCURL="jdbc:mysql://localhost:3306/test";
 private static final String USERNAME="root";
 private static final String USERPASS="";
 private static Connection connection=null;
 private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
 
 static{
  try {
   dataSource.setDriverClass(DRIVERCLASS);
  } catch (PropertyVetoException e) {
   e.printStackTrace();
  }           
  dataSource.setJdbcUrl(JDBCURL);
  dataSource.setUser(USERNAME);                                 
  dataSource.setPassword(USERPASS);                                 
  // the settings below are optional -- c3p0 can work with defaults
  // 设置初始连接池的大小! 
        dataSource.setInitialPoolSize(2); 
        // 设置连接池的最小值!  
        dataSource.setMinPoolSize(1); 
        // 设置连接池的最大值!  
        dataSource.setMaxPoolSize(10); 
        // 设置连接池中的最大Statements数量! 
        dataSource.setMaxStatements(50); 
        // 设置连接池的最大空闲时间! 
        dataSource.setMaxIdleTime(60);
 }
 /**
  * 得到一个数据库的链接
  * @return
  */
 public static Connection getConnection(){
  try {
   connection=dataSource.getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  
  return connection;
 }
 /**
  *  将数据库的连接归还连接池
  */
 public static void closeConnection(){
  if(connection!=null)
  try {
   connection.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}

 

ImgWriteUtil.java

/**
 * 写入图片
 */
package com.qrsx.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ImgWriteUtil {

 public void writeImg(BufferedInputStream bis, BufferedOutputStream bos) {// 写入图片
  int len = 0;
  try {
   byte[] buffer = new byte[2048];
   while ((len = bis.read(buffer)) > 0) {
    bos.write(buffer, 0, len);
   }
  } catch (FileNotFoundException exception) {
   exception.printStackTrace();
   throw new RuntimeException("创建文件时出错!");
  } catch (IOException exception) {
   exception.printStackTrace();
   throw new RuntimeException("读写文件时出错!");
  } finally {
   try {
    if (bos != null) {
     bos.close();
    }
    if (bis != null) {
     bis.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

 

UploadUtil.java

package com.qrsx.util;
/**
 * 工具类 ,FileUpload 完成上传文件。
 * 需要commons-fileupload.jar 和 commons-io.jar  支持。
 */
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadUtil {
 private ServletFileUpload servletFileUpload;
 private List<FileItem> fileItems;

 @SuppressWarnings("unchecked")
 public UploadUtil(HttpServletRequest request) {
  FileItemFactory fileItemFactory = new DiskFileItemFactory();
  servletFileUpload = new ServletFileUpload(fileItemFactory);
  try {
   fileItems = servletFileUpload.parseRequest(request);
  } catch (FileUploadException e) {
   e.printStackTrace();
  }
 }
 /**
  * 解析得到 fieldName 的值
  * @param fieldName
  * @return
  */
 public String getParameter(String fieldName) {
  return this.getParameter(fieldName, "utf-8");
 }
 /**
  * 解析得到 fieldName 的值
  * @param fieldName
  * @param encoding
  * @return
  */
 public String getParameter(String fieldName, String encoding) {
  String value = null;
  if (fileItems != null) {
   for (FileItem fileItem : fileItems) {
    String name = fileItem.getFieldName();
    if ((fileItem.isFormField())&&(name != null) && (fieldName.equals(name))) {
     try {
      value = fileItem.getString(encoding);
     } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
     }
    }
   }
  }
  return value;
 }
 /**
  * 解析得到 fieldName 的值 (集合类型)
  * @param fieldName
  * @return
  */
 public List<String> getParameterValues(String fieldName){
  return this.getParameterValues(fieldName, "utf-8");
 }
 /**
  * 解析得到 fieldName 的值 (集合类型)
  * @param fieldName
  * @param encoding
  * @return
  */
 public List<String>getParameterValues(String fieldName,String encoding){
  List<String>list=new ArrayList<String>();
  if(fileItems!=null){
   for(FileItem fileItem:fileItems){
    String name = fileItem.getFieldName();
    if((fileItem.isFormField())&&(name!=null)&&fieldName.equals(name)){
     try {
      String value = fileItem.getString(encoding);
      list.add(value);
     } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
     }
     
    }
   }
  }
  if((list!=null)&&(list.size()>0)){
   return list;
  }
  return null;
 }
 /**
  * 解析得到 上传文件的 输入流
  * @param fieldName
  * @return
  */
 public BufferedInputStream getInputStream(String fieldName){
  BufferedInputStream bufferedInputStream=null;
  if(fileItems!=null){
   for(FileItem fileItem:fileItems){
    String name = fileItem.getFieldName();
    if((!fileItem.isFormField())&&(name!=null)&&fieldName.equals(name)){
     try {
      InputStream inputStream=fileItem.getInputStream();
      bufferedInputStream=new BufferedInputStream(inputStream);
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
  }
  return bufferedInputStream;
 }
 /**
  * 解析得到上传文件的名称。
  * @param fieldName
  * @return
  */
 public String getFileName(String fieldName){
  String fileName=null;
  if(fileItems!=null){
   for(FileItem fileItem:fileItems){
    String name = fileItem.getFieldName();
    if((!fileItem.isFormField())&&(name!=null)&&fieldName.equals(name)){
     fileName=fileItem.getName();
    }
   }
  }
  return fileName;
 }
}