RegisterAction
package k.action; import k.domain.User; import k.form.UserForm; import k.service.UserService; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.upload.FormFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; public class RegisterAction extends DispatchAction {
public ActionForward fileUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UserForm dynaForm = (UserForm) form; String userName = dynaForm.getUserName(); FormFile formFile = dynaForm.getMyPhoto(); String oldFileName = formFile.getFileName(); System.out.println("==" + userName + "==" + oldFileName + "==" + formFile.getFileSize()); String path = this.getServlet().getServletContext().getRealPath("/file"); File file = new File(path); if (!file.exists()) file.mkdir(); String newfileName = getNewFileName(oldFileName); String newpath = path + "\\" + newfileName; InputStream inputStream = null; FileOutputStream outputStream = null; byte[] bytes = new byte[1024]; int len; try { inputStream = formFile.getInputStream(); outputStream = new FileOutputStream(newpath); while ((len = inputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, len); } User user = new User("", userName, formFile.getFileName(), newfileName); System.out.println(user); if (new UserService().addUser(user)) { return mapping.findForward("registerOk"); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } return mapping.findForward("err"); } private static String getNewFileName(String fileName) { int beginIndex = fileName.lastIndexOf("."); return UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length()); } public ActionForward getUserList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UserService userService = new UserService(); List
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Registertitle> head> <body> <h1>注册页面h1> <form action="${APP_PATH}/register.do?action=fileUpload" method="post" enctype="multipart/form-data"> 名字:<input type="text" name="userName" value="11哈哈"> <br> 头像: <input type="file" name="myPhoto"> <br> <input type="submit" value="submit"> <br> form> body> html>
listUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %> <html> <head> <title>errortitle> head> <body> <h1>用户列表h1> <c:forEach items="${userList}" var="user"> 用户名:${user.userName} <img src="${APP_PATH}/file/${user.photoNewName}" width="300px"> <a href="${APP_PATH}/register.do?action=downUserPhoto&id=${user.id}">点击下载a> <br> c:forEach> body> html>
registerOk.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Titletitle> head> <body> <h1>注册成功h1> <a href="${APP_PATH}/register.do?action=getUserList">用户列表a> body> html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$title> head> <body> <jsp:forward page="WEB-INF/jsp/register.jsp">jsp:forward> body> html>
struts-config.xml
xml version="1.0" encoding="UTF-8"?> DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <global-forwards> <forward name="err" path="/WEB-INF/jsp/err.jsp" redirect="false">forward> global-forwards> <form-beans> <form-bean name="userForm" type="k.form.UserForm"> <form-property name="userName" type="java.lang.String">form-property> <form-property name="myphoto" type="org.apache.struts.upload.FormFile">form-property> form-bean> form-beans> <action-mappings> <action name="userForm" path="/register" parameter="action" type="k.action.RegisterAction" scope="request" attribute="userForm" input="index.jsp" validate="false"> <forward name="registerOk" path="/WEB-INF/jsp/registerOk.jsp">forward> <forward name="listUser" path="/WEB-INF/jsp/listUser.jsp">forward> action> action-mappings> struts-config>
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>actionservlet-name> <servlet-class>org.apache.struts.action.ActionServletservlet-class> <init-param> <param-name>configparam-name> <param-value>/WEB-INF/struts-config.xmlparam-value> init-param> <load-on-startup>2load-on-startup> servlet> <servlet-mapping> <servlet-name>actionservlet-name> <url-pattern>*.dourl-pattern> servlet-mapping> <welcome-file-list> <welcome-file>index.jspwelcome-file> welcome-file-list> <filter> <filter-name>EncodingFilterfilter-name> <filter-class>k.filter.EncodingFilterfilter-class> filter> <filter-mapping> <filter-name>EncodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <listener> <display-name>StartSystemListenerdisplay-name> <listener-class>k.filter.StartSystemListenerlistener-class> listener> web-app>
User
package k.domain; public class User { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } private String userName; private String photoOldName; public User(String id, String userName, String photoOldName, String photoNewName) { this.id = id; this.userName = userName; this.photoOldName = photoOldName; this.photoNewName = photoNewName; } public String getPhotoNewName() { return photoNewName; } public void setPhotoNewName(String photoNewName) { this.photoNewName = photoNewName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhotoOldName() { return photoOldName; } public void setPhotoOldName(String photoOldName) { this.photoOldName = photoOldName; } private String photoNewName; public User() { } }
EncodingFilter
package k.filter; import javax.servlet.*; import javax.servlet.http.HttpServlet; import java.io.IOException; public class EncodingFilter extends HttpServlet implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); // System.out.println("========== set utf-8 ok =========="); filterChain.doFilter(servletRequest, servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
StartSystemListener
package k.filter; import k.utils.WebHelper; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class StartSystemListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //1.将项目上下文路径(request.getContextPath())放置到application域中. ServletContext application = sce.getServletContext(); String app_path = application.getContextPath(); application.setAttribute("APP_PATH", app_path); System.out.println("========== APP_PATH = " + app_path); WebHelper.setApp_Path(app_path); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
UserForm
package k.form; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UserForm extends ActionForm { private String userName; private FormFile myPhoto; public UserForm() { } public UserForm(String userName, FormFile myPhoto) { this.userName = userName; this.myPhoto = myPhoto; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public FormFile getMyPhoto() { return myPhoto; } public void setMyPhoto(FormFile myPhoto) { this.myPhoto = myPhoto; } }
UserService
package k.service; import k.domain.User; import k.utils.JdbcUtils; import java.util.List; import java.util.Map; public class UserService { public boolean addUser(User user) { String sql = "insert into user_photo (user_name,photo_old_name,photo_new_name) VALUES(?,?,?);"; Object[] parms = new Object[]{user.getUserName(), user.getPhotoOldName(), user.getPhotoNewName()}; int a1 = JdbcUtils.executeUpdate(sql, parms); return a1 == 1; } public List> getUserList() { String sql = "SELECT id,user_name,photo_old_name,photo_new_name FROM user_photo;"; List > maps = JdbcUtils.executeQuery(sql); return maps; } public List > getUser(User user) { String sql = "SELECT id,user_name,photo_old_name,photo_new_name FROM user_photo where id=?;"; Object[] parms = new Object[]{user.getId()}; List > maps = JdbcUtils.executeQuery(sql, parms); return maps; } }
JdbcUtils
package k.utils; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class JdbcUtils { private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"; private static String user = "root"; private static String password = "xxxxxx"; public static void main(String[] args) { // String sql = "UPDATE `user` set money=money+10 WHERE `name` =? "; // Object[] parms = new Object[]{"name1"}; // int a1 = executeUpdate(sql, parms); // System.out.println(a1); String sql = "select * from user"; List> list = executeQuery(sql, null); for (Map map : list) { for (String key : map.keySet()) { System.out.println("Key=" + key + "\t value=" + map.get(key)); } System.out.println(); } } public static List > executeQuery(String sql) { return executeQuery(sql, null); } public static List > executeQuery(String sql, Object[] parms) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; List > list = new ArrayList >(); try { conn = JdbcUtils.getConnection(); st = conn.prepareStatement(sql); if (parms != null && parms.length > 0) { for (int i = 0; i < parms.length; i++) { st.setObject(i + 1, parms[i]); } } rs = st.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { Map map = new HashMap<>(); for (int i = 0; i < rsmd.getColumnCount(); i++) { String columnLabel = rsmd.getColumnLabel(i + 1); Object columnValue = rs.getObject(columnLabel); map.put(columnLabel, columnValue); } list.add(map); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.free(rs, st, conn); } return list; } public static int executeUpdate(String sql, Object[] parms) { int res = -1; Connection conn = null; PreparedStatement pst = null; ResultSet set = null; try { conn = getConnection(); pst = conn.prepareStatement(sql); for (int i = 0; i < parms.length; i++) { pst.setObject(i + 1, parms[i]); } res = pst.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { free(set, pst, conn); } return res; } private JdbcUtils() { } static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } public static void free(ResultSet rs, Statement st, Connection conn) { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } }
WebHelper
package k.utils; import java.util.UUID; public class WebHelper { public static String getApp_Path() { return APP_PATH; } public static void setApp_Path(String appPath) { APP_PATH = appPath; } private static String APP_PATH = ""; public static String getNewFileName(String fileName) { int beginIndex = fileName.lastIndexOf("."); return UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length()); } }