JavaWeb项目开发案例精粹-第4章博客网站系统-002辅助类及配置文件
1.
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <servlet> 8 <servlet-name>Connector</servlet-name> 9 <servlet-class> 10 com.sanqing.fckeditor.ConnectorServlet 11 </servlet-class> 12 <load-on-startup>1</load-on-startup> 13 </servlet> 14 <servlet-mapping> 15 <servlet-name>Connector</servlet-name> 16 <url-pattern> 17 /user/fckeditor/editor/filemanager/connectors/* 18 </url-pattern> 19 </servlet-mapping> 20 <welcome-file-list> 21 <welcome-file>/login.jsp</welcome-file> 22 </welcome-file-list> 23 <filter> 24 <filter-name>struts2</filter-name> 25 <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 26 </filter> 27 <filter-mapping> 28 <filter-name>struts2</filter-name> 29 <url-pattern>*.action</url-pattern> 30 </filter-mapping> 31 <filter-mapping> 32 <filter-name>struts2</filter-name> 33 <url-pattern>*.jsp</url-pattern> 34 </filter-mapping> 35 36 <listener> 37 <listener-class> 38 org.springframework.web.context.ContextLoaderListener 39 </listener-class> 40 </listener> 41 <context-param> 42 <param-name>contextConfigLocation</param-name> 43 <param-value>classpath:applicationContext*.xml</param-value> 44 </context-param> 45 </web-app>
2.applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> 6 <!-- 定义数据源 --> 7 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 8 <property name="driverClassName"> 9 <value>com.mysql.jdbc.Driver</value> 10 </property> 11 <property name="url"> 12 <value>jdbc:mysql://localhost:3306/db_blog</value> 13 </property> 14 <property name="username"> 15 <value>root</value> 16 </property> 17 <property name="password"> 18 <value>1234</value> 19 </property> 20 </bean> 21 22 <!-- 定义SessionFactory --> 23 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 24 <property name="dataSource"> 25 <ref bean="dataSource"/> 26 </property> 27 <property name="hibernateProperties"> 28 <props> 29 <prop key="hibernate.dialect"> 30 org.hibernate.dialect.MySQLDialect 31 </prop> 32 <prop key="hibernate.show_sql">false</prop> 33 </props> 34 </property> 35 <property name="mappingResources"> 36 <list> 37 <value>com/sanqing/po/User.hbm.xml</value> 38 <value>com/sanqing/po/Article.hbm.xml</value> 39 <value>com/sanqing/po/BlogInfo.hbm.xml</value> 40 <value>com/sanqing/po/Critique.hbm.xml</value> 41 <value>com/sanqing/po/Dianjiliang.hbm.xml</value> 42 </list> 43 </property> 44 </bean> 45 46 <!-- 定义HibernateTemplate --> 47 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> 48 <property name="sessionFactory"> 49 <ref bean="sessionFactory"/> 50 </property> 51 </bean> 52 53 <!-- 配置DAO组件 --> 54 <bean id="userDAO" class="com.sanqing.dao.UserDAOImpl"> 55 <property name="hibernateTemplate"> 56 <ref bean="hibernateTemplate"/> 57 </property> 58 </bean> 59 60 <!-- 配置业务逻辑组件 --> 61 <bean id="userService" class="com.sanqing.service.UserServiceImpl"> 62 <property name="userDAO"> 63 <ref bean="userDAO"/> 64 </property> 65 </bean> 66 67 <!-- 配置RegisterAction --> 68 <bean id="registerAction" class="com.sanqing.action.Register" scope="prototype"> 69 <property name="userService"> 70 <ref bean="userService"/> 71 </property> 72 </bean> 73 74 <!-- 配置LoginAction --> 75 <bean id="loginAction" class="com.sanqing.action.Login" scope="prototype"> 76 <property name="userService"> 77 <ref bean="userService"/> 78 </property> 79 </bean> 80 81 <!-- 配置DAO组件 --> 82 <bean id="blogInfoDAO" class="com.sanqing.dao.BlogInfoDAOImpl"> 83 <property name="hibernateTemplate"> 84 <ref bean="hibernateTemplate"/> 85 </property> 86 </bean> 87 88 <!-- 配置业务逻辑组件 --> 89 <bean id="blogInfoService" class="com.sanqing.service.BlogInfoServiceImpl"> 90 <property name="blogInfoDAO"> 91 <ref bean="blogInfoDAO"/> 92 </property> 93 </bean> 94 95 <!-- 配置EditBlogInfo Action --> 96 <bean id="editeBlogInfo" class="com.sanqing.action.EditBlogInfo" scope="prototype"> 97 <property name="blogInfoService"> 98 <ref bean="blogInfoService"/> 99 </property> 100 </bean> 101 102 <!-- 配置GetBlogInfo Action --> 103 <bean id="GetBlogInfo" class="com.sanqing.action.GetBlogInfo" scope="prototype"> 104 <property name="blogInfoService"> 105 <ref bean="blogInfoService"/> 106 </property> 107 </bean> 108 109 <!-- 配置ArticleDAO --> 110 <bean id="articleDAO" class="com.sanqing.dao.ArticleDAOImpl"> 111 <property name="hibernateTemplate"> 112 <ref bean="hibernateTemplate"/> 113 </property> 114 </bean> 115 116 <!-- 配置ArticleService --> 117 <bean id="articleService" class="com.sanqing.service.ArticleServiceImpl"> 118 <property name="articleDAO"> 119 <ref bean="articleDAO"/> 120 </property> 121 <property name="critiqueDAO"> 122 <ref bean="critiqueDAO"/> 123 </property> 124 </bean> 125 126 <!-- AddArticle Action --> 127 <bean id="addArticle" class="com.sanqing.action.AddArticle" scope="prototype"> 128 <property name="articleService"> 129 <ref bean="articleService"/> 130 </property> 131 </bean> 132 133 <!-- ShowUserAllArticle Action --> 134 <bean id="showUserAllArticle" class="com.sanqing.action.ShowUserAllArticle" scope="prototype"> 135 <property name="articleService"> 136 <ref bean="articleService"/> 137 </property> 138 </bean> 139 140 <!-- ShowAllArticle Action --> 141 <bean id="showAllArticle" class="com.sanqing.action.ShowAllArticle" scope="prototype"> 142 <property name="articleService"> 143 <ref bean="articleService"/> 144 </property> 145 </bean> 146 147 <!-- 配置dianjiliangDAO --> 148 <bean id="dianjiliangDAO" class="com.sanqing.dao.DianjiliangDAOImpl"> 149 <property name="hibernateTemplate"> 150 <ref bean="hibernateTemplate"/> 151 </property> 152 </bean> 153 154 <!-- 配置dianjiliangService --> 155 <bean id="dianjiliangService" class="com.sanqing.service.DianjiliangServiceImpl"> 156 <property name="dianjiliangDAO"> 157 <ref bean="dianjiliangDAO"/> 158 </property> 159 </bean> 160 161 162 163 164 <!-- 配置critiqueDAO --> 165 <bean id="critiqueDAO" class="com.sanqing.dao.CritiqueDAOImpl"> 166 <property name="hibernateTemplate"> 167 <ref bean="hibernateTemplate"/> 168 </property> 169 </bean> 170 171 <!-- 配置critiqueService --> 172 <bean id="critiqueService" class="com.sanqing.service.CritiqueServiceImpl"> 173 <property name="critiqueDAO"> 174 <ref bean="critiqueDAO"/> 175 </property> 176 </bean> 177 178 <!-- AddCritique Action --> 179 <bean id="addCritique" class="com.sanqing.action.AddCritique" scope="prototype"> 180 <property name="critiqueService"> 181 <ref bean="critiqueService"/> 182 </property> 183 </bean> 184 185 <!-- ShowArticle Action --> 186 <bean id="showArticle" class="com.sanqing.action.ShowArticle" scope="prototype"> 187 <property name="articleService"> 188 <ref bean="articleService"/> 189 </property> 190 <property name="dianjiliangService"> 191 <ref bean="dianjiliangService"/> 192 </property> 193 <property name="critiqueService"> 194 <ref bean="critiqueService"/> 195 </property> 196 <property name="blogInfoService"> 197 <ref bean="blogInfoService"/> 198 </property> 199 </bean> 200 201 <!-- ShowRss Action --> 202 <bean id="showRSS" class="com.sanqing.action.ShowRSS" scope="prototype"> 203 <property name="articleService"> 204 <ref bean="articleService"/> 205 </property> 206 </bean> 207 </beans>
3.
1 <?xml version="1.0" encoding="UTF-8" ?> 2 3 <!DOCTYPE struts PUBLIC 4 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 5 "http://struts.apache.org/dtds/struts-2.0.dtd"> 6 7 <struts> 8 <constant name="struts.i18n.encoding" value="gb2312"></constant> 9 <constant name="struts.custom.i18n.resources" value="myMessage"></constant> 10 <package name="struts2" extends="struts-default"> 11 <interceptors> 12 <interceptor name="userInterceptor" class="com.sanqing.interceptor.UserInterceptor"></interceptor> 13 </interceptors> 14 15 <action name="register" class="registerAction"> 16 <result name="success">/success.jsp</result> 17 <result name="error">/error.jsp</result> 18 <result name="input">/register.jsp</result> 19 </action> 20 21 <action name="login" class="loginAction"> 22 <result name="success">/success.jsp</result> 23 <result name="error">/error.jsp</result> 24 <result name="input">/login.jsp</result> 25 </action> 26 27 <action name="editBlogInfo" class="editeBlogInfo"> 28 <result name="success" type="chain">getBlogInfo</result> 29 <result name="error">/error.jsp</result> 30 <result name="input">/user/editbloginfo.jsp</result> 31 </action> 32 33 <action name="getBlogInfo" class="GetBlogInfo"> 34 <result name="success">/user/editbloginfo.jsp</result> 35 <result name="error">/error.jsp</result> 36 </action> 37 38 <action name="addArticle" class="addArticle"> 39 <result name="success" type="chain">showUserAllArticle</result> 40 <result name="error">/error.jsp</result> 41 <result name="login" type="redirect">/login.jsp</result> 42 <interceptor-ref name="userInterceptor"></interceptor-ref> 43 <interceptor-ref name="defaultStack"></interceptor-ref> 44 </action> 45 46 <action name="showUserAllArticle" class="showUserAllArticle"> 47 <result name="success">/user/showUserAllArticle.jsp</result> 48 </action> 49 50 <action name="showAllArticle" class="showAllArticle"> 51 <result name="success">/showAllArticle.jsp</result> 52 </action> 53 54 <action name="showArticle" class="showArticle"> 55 <result name="success">/user/showArticle.jsp</result> 56 </action> 57 58 <action name="addCritique" class="addCritique"> 59 <result name="success" type="chain">showArticle</result> 60 </action> 61 62 <action name="photoUpload" class="com.sanqing.action.PhotoUpload"> 63 <result name="success" type="chain">showPhoto</result> 64 <result name="input">/user/showphoto.jsp</result> 65 <!-- 配置fileUpload拦截器 --> 66 <interceptor-ref name="fileUpload"> 67 <!-- 配置允许上传文件类型 --> 68 <param name="allowedTypes">image/bmp,image/pjpeg,image/gif,image/png</param> 69 <!-- 配置允许上传文件大小最大值 --> 70 <param name="maximumSize">512000</param> 71 </interceptor-ref> 72 <result name="login" type="redirect">/login.jsp</result> 73 <interceptor-ref name="userInterceptor"></interceptor-ref> 74 <interceptor-ref name="defaultStack"></interceptor-ref> 75 </action> 76 77 <action name="showPhoto" class="com.sanqing.action.ShowPhoto"> 78 <result name="success">/user/showphoto.jsp</result> 79 </action> 80 81 <action name="showRSS" class="showRSS"> 82 <result name="success">/rss.xml</result> 83 </action> 84 </package> 85 </struts>
4.fckeditor.properties
1 connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl 2 connector.userPathBuilderImpl=com.fckeditor.fckeditor.MyUserPath
5.myMessage.properties
1 struts.messages.error.content.type.not.allowed =\u4E0D\u5141\u8BB8\u4E0A\u4F20\u7684\u6587\u4EF6
6.rss.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" 3 xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" 4 xmlns:dc="http://purl.org/dc/elements/1.1/" 5 xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" 6 xmlns:wfw="http://wellformedweb.org/CommentAPI/" 7 xmlns:slash="http://purl.org/rss/1.0/modules/slash/"> 8 9 <channel> 10 <title>北风博客网</title> 11 <link>http://localhost:8080/BFblogDemo07/login.jsp</link> 12 <description>专注于IT培训</description> 13 <item> 14 <title>测试RSS</title> 15 <link>http://localhost:8080/BFblogDemo07/login.jsp</link> 16 <description>测试RSS,成功</description> 17 <author>lifengxing</author> 18 <pubDate>Thu, 19 Mar 2009 02:46:00 GMT</pubDate> 19 </item> 20 </channel> 21 </rss>
7.
1 package com.sanqing.interceptor; 2 3 import java.util.Map; 4 5 import com.opensymphony.xwork2.Action; 6 import com.opensymphony.xwork2.ActionContext; 7 import com.opensymphony.xwork2.ActionInvocation; 8 import com.opensymphony.xwork2.interceptor.AbstractInterceptor; 9 10 public class UserInterceptor extends AbstractInterceptor { 11 12 public String intercept(ActionInvocation invocation) throws Exception { 13 ActionContext context =invocation.getInvocationContext(); 14 //获得session 15 Map session = context.getContext().getSession(); 16 String username = (String) session.get("username"); 17 //判断用户合法性 18 if(username == null || "".equals(username)) { 19 //返回用户登陆页面 20 return Action.LOGIN; 21 } else { 22 //进行下一步操作,没有拦截 23 return invocation.invoke(); 24 } 25 } 26 27 }
8.
1 package com.sanqing.fckeditor; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpSession; 5 6 import net.fckeditor.requestcycle.UserPathBuilder; 7 8 public class MyUserPath implements UserPathBuilder { 9 10 public String getUserFilesPath(HttpServletRequest request) { 11 //返回一个路径,这个路径就是用户的目录 12 HttpSession session = request.getSession(); 13 String username = (String) session.getAttribute("username"); 14 return "/userfiles/" + username; 15 } 16 17 }
9.
1 /* 2 * FCKeditor - The text editor for Internet - http://www.fckeditor.net 3 * Copyright (C) 2003-2008 Frederico Caldeira Knabben 4 * 5 * == BEGIN LICENSE == 6 * 7 * Licensed under the terms of any of the following licenses at your 8 * choice: 9 * 10 * - GNU General Public License Version 2 or later (the "GPL") 11 * http://www.gnu.org/licenses/gpl.html 12 * 13 * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") 14 * http://www.gnu.org/licenses/lgpl.html 15 * 16 * - Mozilla Public License Version 1.1 or later (the "MPL") 17 * http://www.mozilla.org/MPL/MPL-1.1.html 18 * 19 * == END LICENSE == 20 */ 21 package com.sanqing.fckeditor; 22 23 import java.io.File; 24 import java.io.IOException; 25 import java.io.PrintWriter; 26 import java.util.List; 27 import java.util.UUID; 28 29 import javax.servlet.ServletException; 30 import javax.servlet.http.HttpServlet; 31 import javax.servlet.http.HttpServletRequest; 32 import javax.servlet.http.HttpServletResponse; 33 34 import net.fckeditor.connector.Messages; 35 import net.fckeditor.handlers.CommandHandler; 36 import net.fckeditor.handlers.ConnectorHandler; 37 import net.fckeditor.handlers.ExtensionsHandler; 38 import net.fckeditor.handlers.RequestCycleHandler; 39 import net.fckeditor.handlers.ResourceTypeHandler; 40 import net.fckeditor.response.UploadResponse; 41 import net.fckeditor.response.XmlResponse; 42 import net.fckeditor.tool.Utils; 43 import net.fckeditor.tool.UtilsFile; 44 import net.fckeditor.tool.UtilsResponse; 45 46 import org.apache.commons.fileupload.FileItem; 47 import org.apache.commons.fileupload.FileItemFactory; 48 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 49 import org.apache.commons.fileupload.servlet.ServletFileUpload; 50 import org.apache.commons.io.FilenameUtils; 51 import org.slf4j.Logger; 52 import org.slf4j.LoggerFactory; 53 54 /** 55 * Servlet to upload and browse files.<br /> 56 * 57 * This servlet accepts 4 commands which interact with the server-side 58 * filesystem.<br /> 59 * The allowed commands are: 60 * <ul> 61 * <li><code>GetFolders</code>: Retrieves a list of folders in the current 62 * folder</li> 63 * <li><code>GetFoldersAndFiles</code>: Retrives a list of files and folders 64 * in the current folder</li> 65 * <li><code>CreateFolder</code>: Creates a new folder in the current folder</li> 66 * <li><code>FileUpload</code>: Stores an uploaded file into the current 67 * folder. (must be sent with POST)</li> 68 * </ul> 69 * 70 * @version $Id: ConnectorServlet.java 2101 2008-06-22 22:00:48Z mosipov $ 71 */ 72 public class ConnectorServlet extends HttpServlet { 73 74 private static final long serialVersionUID = -5742008970929377161L; 75 private static final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class); 76 77 /** 78 * Initialize the servlet: <code>mkdir</code> <DefaultUserFilesPath> 79 */ 80 public void init() throws ServletException, IllegalArgumentException { 81 String realDefaultUserFilesPath = getServletContext().getRealPath( 82 ConnectorHandler.getDefaultUserFilesPath()); 83 84 File defaultUserFilesDir = new File(realDefaultUserFilesPath); 85 UtilsFile.checkDirAndCreate(defaultUserFilesDir); 86 87 logger.info("ConnectorServlet successfully initialized!"); 88 } 89 90 /** 91 * Manage the <code>GET</code> requests (<code>GetFolders</code>, 92 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/> 93 * 94 * The servlet accepts commands sent in the following format:<br/> 95 * <code>connector?Command=<CommandName>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> 96 * <p> 97 * It executes the commands and then returns the result to the client in XML 98 * format. 99 * </p> 100 */ 101 public void doGet(HttpServletRequest request, HttpServletResponse response) 102 throws ServletException, IOException { 103 logger.debug("Entering ConnectorServlet#doGet"); 104 105 response.setCharacterEncoding("UTF-8"); 106 response.setContentType("application/xml; charset=UTF-8"); 107 response.setHeader("Cache-Control", "no-cache"); 108 PrintWriter out = response.getWriter(); 109 110 String commandStr = request.getParameter("Command"); 111 String typeStr = request.getParameter("Type"); 112 String currentFolderStr = request.getParameter("CurrentFolder"); 113 114 logger.debug("Parameter Command: {}", commandStr); 115 logger.debug("Parameter Type: {}", typeStr); 116 logger.debug("Parameter CurrentFolder: {}", currentFolderStr); 117 118 XmlResponse xr; 119 120 if (!RequestCycleHandler.isEnabledForFileBrowsing(request)) 121 xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING); 122 else if (!CommandHandler.isValidForGet(commandStr)) 123 xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND); 124 else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) 125 xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE); 126 else if (!UtilsFile.isValidPath(currentFolderStr)) 127 xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER); 128 else { 129 CommandHandler command = CommandHandler.getCommand(commandStr); 130 ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); 131 132 String typePath = UtilsFile.constructServerSidePath(request, resourceType); 133 String typeDirPath = getServletContext().getRealPath(typePath); 134 135 File typeDir = new File(typeDirPath); 136 UtilsFile.checkDirAndCreate(typeDir); 137 138 File currentDir = new File(typeDir, currentFolderStr); 139 140 if (!currentDir.exists()) 141 xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME); 142 else { 143 144 xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse 145 .constructResponseUrl(request, resourceType, currentFolderStr, true, 146 ConnectorHandler.isFullUrl())); 147 148 if (command.equals(CommandHandler.GET_FOLDERS)) 149 xr.setFolders(currentDir); 150 else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES)) 151 xr.setFoldersAndFiles(currentDir); 152 else if (command.equals(CommandHandler.CREATE_FOLDER)) { 153 String newFolderStr = UtilsFile.sanitizeFolderName( 154 new String(request.getParameter("NewFolderName").getBytes("ISO8859-1"),"UTF-8") 155 ); 156 logger.debug("Parameter NewFolderName: {}", newFolderStr); 157 158 File newFolder = new File(currentDir, newFolderStr); 159 int errorNumber = XmlResponse.EN_UKNOWN; 160 161 if (newFolder.exists()) 162 errorNumber = XmlResponse.EN_ALREADY_EXISTS; 163 else { 164 try { 165 errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK 166 : XmlResponse.EN_INVALID_FOLDER_NAME; 167 } catch (SecurityException e) { 168 errorNumber = XmlResponse.EN_SECURITY_ERROR; 169 } 170 } 171 xr.setError(errorNumber); 172 } 173 } 174 } 175 176 out.print(xr); 177 out.flush(); 178 out.close(); 179 logger.debug("Exiting ConnectorServlet#doGet"); 180 } 181 182 /** 183 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> 184 * 185 * The servlet accepts commands sent in the following format:<br /> 186 * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> 187 * with the file in the <code>POST</code> body.<br /> 188 * <br> 189 * It stores an uploaded file (renames a file if another exists with the 190 * same name) and then returns the JavaScript callback. 191 */ 192 @SuppressWarnings("unchecked") 193 public void doPost(HttpServletRequest request, HttpServletResponse response) 194 throws ServletException, IOException { 195 logger.debug("Entering Connector#doPost"); 196 197 response.setCharacterEncoding("UTF-8"); 198 response.setContentType("text/html; charset=UTF-8"); 199 response.setHeader("Cache-Control", "no-cache"); 200 PrintWriter out = response.getWriter(); 201 202 String commandStr = request.getParameter("Command"); 203 String typeStr = request.getParameter("Type"); 204 String currentFolderStr = request.getParameter("CurrentFolder"); 205 206 logger.debug("Parameter Command: {}", commandStr); 207 logger.debug("Parameter Type: {}", typeStr); 208 logger.debug("Parameter CurrentFolder: {}", currentFolderStr); 209 210 UploadResponse ur; 211 212 // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' 213 // are empty 214 if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { 215 commandStr = "QuickUpload"; 216 currentFolderStr = "/"; 217 } 218 219 if (!RequestCycleHandler.isEnabledForFileUpload(request)) 220 ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, 221 Messages.NOT_AUTHORIZED_FOR_UPLOAD); 222 else if (!CommandHandler.isValidForPost(commandStr)) 223 ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); 224 else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) 225 ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); 226 else if (!UtilsFile.isValidPath(currentFolderStr)) 227 ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; 228 else { 229 ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); 230 231 String typePath = UtilsFile.constructServerSidePath(request, resourceType); 232 String typeDirPath = getServletContext().getRealPath(typePath); 233 234 File typeDir = new File(typeDirPath); 235 UtilsFile.checkDirAndCreate(typeDir); 236 237 File currentDir = new File(typeDir, currentFolderStr); 238 239 if (!currentDir.exists()) 240 ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; 241 else { 242 243 String newFilename = null; 244 FileItemFactory factory = new DiskFileItemFactory(); 245 ServletFileUpload upload = new ServletFileUpload(factory); 246 //设置编码格式 247 upload.setHeaderEncoding("UTF-8"); 248 try { 249 250 List<FileItem> items = upload.parseRequest(request); 251 252 // We upload only one file at the same time 253 FileItem uplFile = items.get(0); 254 String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); 255 String filename = FilenameUtils.getName(rawName); 256 String baseName = FilenameUtils.removeExtension(filename); 257 String extension = FilenameUtils.getExtension(filename); 258 //文件名自动替换 259 filename = UUID.randomUUID().toString() + "."+ extension; 260 261 262 if (!ExtensionsHandler.isAllowed(resourceType, extension)) 263 ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); 264 else { 265 266 // construct an unique file name 267 File pathToSave = new File(currentDir, filename); 268 int counter = 1; 269 while (pathToSave.exists()) { 270 newFilename = baseName.concat("(").concat(String.valueOf(counter)) 271 .concat(")").concat(".").concat(extension); 272 pathToSave = new File(currentDir, newFilename); 273 counter++; 274 } 275 276 if (Utils.isEmpty(newFilename)) 277 ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse 278 .constructResponseUrl(request, resourceType, currentFolderStr, 279 true, ConnectorHandler.isFullUrl()).concat(filename)); 280 else 281 ur = new UploadResponse(UploadResponse.SC_RENAMED, 282 UtilsResponse.constructResponseUrl(request, resourceType, 283 currentFolderStr, true, ConnectorHandler.isFullUrl()) 284 .concat(newFilename), newFilename); 285 286 // secure image check 287 if (resourceType.equals(ResourceTypeHandler.IMAGE) 288 && ConnectorHandler.isSecureImageUploads()) { 289 if (UtilsFile.isImage(uplFile.getInputStream())) 290 uplFile.write(pathToSave); 291 else { 292 uplFile.delete(); 293 ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); 294 } 295 } else 296 uplFile.write(pathToSave); 297 298 } 299 } catch (Exception e) { 300 ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); 301 } 302 } 303 304 } 305 306 out.print(ur); 307 out.flush(); 308 out.close(); 309 310 logger.debug("Exiting Connector#doPost"); 311 } 312 313 }
10.
1 package com.sanqing.rss; 2 3 import java.io.BufferedWriter; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.util.List; 7 8 import com.sanqing.po.Article; 9 10 public class CreateRss { 11 public static void publishRss(List<Article> list, String filePath) { 12 try { 13 FileWriter fw = new FileWriter(filePath); //文件输出流 14 BufferedWriter bw = new BufferedWriter(fw); //缓冲流 15 bw.write("<?xml version=\"1.0\" encoding=\"gbk\"?>\r\n"); //写入头部声明 16 bw.write("<rss version=\"2.0\" xmlns:atom=\"" + 17 "http://www.w3.org/2005/Atom\"\r\n"); 18 bw.write("xmlns:cf=\"http://www.microsoft.com/" + 19 "schemas/rss/core/2005\"\r\n"); 20 bw.write("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\r\n"); 21 bw.write("xmlns:trackback=\"http://madskills.com/public/" + 22 "xml/rss/module/trackback/\"\r\n"); 23 bw.write("xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\r\n"); 24 bw.write("xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\r\n>"); 25 bw.write("<channel>\r\n"); //频道信息 26 bw.write("<title>求贤人才博客网</title>\r\n"); //标题 27 bw.write("<link>http://localhost:8080/JavaPrj_4/login.jsp</link>\r\n"); //链接地址 28 bw.write("<description>专注于软件人才的培养</description>\r\n"); //频道描述 29 for(Article art : list) { 30 bw.write("<item>\r\n"); //栏目 31 bw.write("<title>" + art.getTitle()+"</title>\r\n"); //栏目标题 32 bw.write("<link>http://localhost:8080/JavaPrj_4/user/" + 33 "showArticle.action?id = " + art.getId() + "</link>\r\n"); //栏目链接地址 34 bw.write("<description>" + art.getContent() + "</description>\r\n");//栏目描述 35 bw.write("<author>" + art.getUsername() + "</author>\r\n"); //作者 36 bw.write("<pubDate>" + art.getDate() + "</pubDate>\r\n"); //发布时间 37 bw.write("</item>\r\n"); 38 } 39 bw.write("</channel>\r\n"); 40 bw.write("</rss>\r\n"); 41 //关闭流 42 bw.close(); 43 fw.close(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 }
11.
1 package com.sanqing.fenye; 2 3 public class Page { 4 // 1.每页显示数量(everyPage) 5 private int everyPage; 6 // 2.总记录数(totalCount) 7 private int totalCount; 8 // 3.总页数(totalPage) 9 private int totalPage; 10 // 4.当前页(currentPage) 11 private int currentPage; 12 // 5.起始点(beginIndex) 13 private int beginIndex; 14 // 6.是否有上一页(hasPrePage) 15 private boolean hasPrePage; 16 // 7.是否有下一页(hasNextPage) 17 private boolean hasNextPage; 18 19 public Page(int everyPage, int totalCount, int totalPage, int currentPage, 20 int beginIndex, boolean hasPrePage, boolean hasNextPage) { 21 this.everyPage = everyPage; 22 this.totalCount = totalCount; 23 this.totalPage = totalPage; 24 this.currentPage = currentPage; 25 this.beginIndex = beginIndex; 26 this.hasPrePage = hasPrePage; 27 this.hasNextPage = hasNextPage; 28 } 29 30 //构造函数,默认 31 public Page(){} 32 33 //构造方法,对所有属性进行设置 34 35 36 public int getEveryPage() { 37 return everyPage; 38 } 39 40 public void setEveryPage(int everyPage) { 41 this.everyPage = everyPage; 42 } 43 44 public int getTotalCount() { 45 return totalCount; 46 } 47 48 public void setTotalCount(int totalCount) { 49 this.totalCount = totalCount; 50 } 51 52 public int getTotalPage() { 53 return totalPage; 54 } 55 56 public void setTotalPage(int totalPage) { 57 this.totalPage = totalPage; 58 } 59 60 public int getCurrentPage() { 61 return currentPage; 62 } 63 64 public void setCurrentPage(int currentPage) { 65 this.currentPage = currentPage; 66 } 67 68 public int getBeginIndex() { 69 return beginIndex; 70 } 71 72 public void setBeginIndex(int beginIndex) { 73 this.beginIndex = beginIndex; 74 } 75 76 public boolean isHasPrePage() { 77 return hasPrePage; 78 } 79 80 public void setHasPrePage(boolean hasPrePage) { 81 this.hasPrePage = hasPrePage; 82 } 83 84 public boolean isHasNextPage() { 85 return hasNextPage; 86 } 87 88 public void setHasNextPage(boolean hasNextPage) { 89 this.hasNextPage = hasNextPage; 90 } 91 92 }
12.
1 package com.sanqing.fenye; 2 /* 3 * 分页信息辅助类 4 */ 5 public class PageUtil { 6 7 public static Page createPage(int everyPage,int totalCount,int currentPage) { 8 everyPage = getEveryPage(everyPage); 9 currentPage = getCurrentPage(currentPage); 10 int totalPage = getTotalPage(everyPage, totalCount); 11 int beginIndex = getBeginIndex(everyPage, currentPage); 12 boolean hasPrePage = getHasPrePage(currentPage); 13 boolean hasNextPage = getHasNextPage(totalPage, currentPage); 14 return new Page(everyPage, totalCount, totalPage, currentPage, 15 beginIndex, hasPrePage, hasNextPage); 16 } 17 18 public static Page createPage(Page page,int totalCount) { 19 int everyPage = getEveryPage(page.getEveryPage()); 20 int currentPage = getCurrentPage(page.getCurrentPage()); 21 int totalPage = getTotalPage(everyPage, totalCount); 22 int beginIndex = getBeginIndex(everyPage, currentPage); 23 boolean hasPrePage = getHasPrePage(currentPage); 24 boolean hasNextPage = getHasNextPage(totalPage, currentPage); 25 return new Page(everyPage, totalCount, totalPage, currentPage, 26 beginIndex, hasPrePage, hasNextPage); 27 } 28 29 //设置每页显示记录数 30 public static int getEveryPage(int everyPage) { 31 return everyPage == 0 ? 10 : everyPage; 32 } 33 34 //设置当前页 35 public static int getCurrentPage(int currentPage) { 36 return currentPage == 0 ? 1 : currentPage; 37 } 38 39 //设置总页数,需要总记录数,每页显示多少 40 public static int getTotalPage(int everyPage,int totalCount) { 41 int totalPage = 0; 42 if(totalCount % everyPage == 0) { 43 totalPage = totalCount / everyPage; 44 } else { 45 totalPage = totalCount / everyPage + 1; 46 } 47 return totalPage; 48 } 49 50 //设置起始点,需要每页显示多少,当前页 51 public static int getBeginIndex(int everyPage,int currentPage) { 52 return (currentPage - 1) * everyPage; 53 } 54 55 //设置是否有上一页,需要当前页 56 public static boolean getHasPrePage(int currentPage) { 57 return currentPage == 1 ? false : true; 58 } 59 60 //设置是否有下一个,需要总页数和当前页 61 public static boolean getHasNextPage(int totalPage, int currentPage) { 62 return currentPage == totalPage || totalPage == 0 ? false : true; 63 } 64 65 }
13.
1 package com.sanqing.fenye; 2 3 import java.util.List; 4 5 public class Result { 6 private Page page; 7 private List list; 8 public Page getPage() { 9 return page; 10 } 11 public void setPage(Page page) { 12 this.page = page; 13 } 14 public List getList() { 15 return list; 16 } 17 public void setList(List list) { 18 this.list = list; 19 } 20 21 22 }
14.
You can do anything you set your mind to, man!