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<Map<String, Object>> userList = userService.getUserList(); ArrayList<User> userArrayList = new ArrayList<>(); for (Map<String, Object> item : userList) { String id = item.get("id").toString(); String username = item.get("user_name").toString(); String photo_old_name = item.get("photo_old_name").toString(); String photo_new_name = item.get("photo_new_name").toString(); User user = new User(id, username, photo_old_name, photo_new_name); userArrayList.add(user); } request.setAttribute("userList", userArrayList); return mapping.findForward("listUser"); } public ActionForward downUserPhoto(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { User user = new User(); user.setId(request.getParameter("id")); UserService userService = new UserService(); List<Map<String, Object>> userList = userService.getUser(user); String photo_old_name = userList.get(0).get("photo_old_name").toString(); String photo_new_name = userList.get(0).get("photo_new_name").toString(); String path = this.getServlet().getServletContext().getRealPath("/file"); response.setContentType("text/html; charset=utf-8"); String urlFileName = URLEncoder.encode(photo_old_name, "utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + urlFileName); InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new FileInputStream(path + "\" + photo_new_name); outputStream = response.getOutputStream(); int len; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } return mapping.findForward("listUser"); } }
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Register</title> </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>error</title> </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>Title</title> </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>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>k.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <display-name>StartSystemListener</display-name> <listener-class>k.filter.StartSystemListener</listener-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<Map<String, Object>> getUserList() { String sql = "SELECT id,user_name,photo_old_name,photo_new_name FROM user_photo;"; List<Map<String, Object>> maps = JdbcUtils.executeQuery(sql); return maps; } public List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> list = executeQuery(sql, null); for (Map<String, Object> map : list) { for (String key : map.keySet()) { System.out.println("Key=" + key + " value=" + map.get(key)); } System.out.println(); } } public static List<Map<String, Object>> executeQuery(String sql) { return executeQuery(sql, null); } public static List<Map<String, Object>> executeQuery(String sql, Object[] parms) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); 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<String, Object> 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()); } }