diff --git a/.classpath b/.classpath deleted file mode 100644 index 8f5c07e..0000000 --- a/.classpath +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore deleted file mode 100644 index acd1ac3..0000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -*.class - -# Package Files # -*.jar -*.war -*.ear -/target diff --git a/.project b/.project deleted file mode 100644 index a375ecd..0000000 --- a/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - easy-httpserver - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 1ce660c..0000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,7 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//src/main/resources/velocity.properties=ISO-8859-1 -encoding//src/main/resources/web.properties=UTF-8 -encoding//src/test/java=UTF-8 -encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 6249222..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index e06d208..0000000 --- a/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/README.md b/README.md index ed43d5c..f4fda53 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,9 @@ -easy-httpserver -================= - -简介 ------------------ -一个java实现的简单的web服务器,主要目的是为了理解web服务器的工作原理。http请求的接收和返回使用JDK自带的HttpServer,请求处理和页面解析是自己实现的。目前已经能够支持web服务器一些基本的功能。 - -功能 ------------------ -目前项目已经能够完成一个动态网站的处理,并且采用类似jetty的嵌入启动方式,网站项目只需实现Controller和View页面并引入该项目jar包即可。 -已完成主要功能如下: - - -如何使用 ------------------ -easy-httpserver项目内也有测试代码,可自行研究。这里介绍test-httpserver示例项目的使用,其中已经实现了一些例子,可参照这些例子实现。 - - -项目结构 ------------------ -项目采用eclipse开发,并使用maven构建。 -

~src/main/java
  --org.eh.core
      --annotation
           AnnocationHandler.java   注解处理类
           Controller.java    Controller注解
       RequestMapping    请求方法注解,用来标注Controller中的处理方法
      --common
           Constants.java    常量类,包括系统常量和配置文件对应信息
           ReturnType.java    枚举,返回类型
      --http
           EHHttpHandler.java    httpserver请求核心处理类,完成请求的接收、处理、返回
           EHServer.java    项目启动类,完成服务器启动
       ApplicationContext.java   全局数据和会话相关数据,单例
       HttpSession.java   session会话
      --model
           FileInfo.java    上传文件信息封装
           ResultInfo.java    Controller返回结果
      --util
           FileUploadContentAnalysis.java    上传请求解析类,从中提取表单中的域值和文件信息
           FileUtil.java   文件工具类
           IOUtil.java    IO工具类
           PropertyUtil.java    配置文件工具类
           StringUtil.java    字符串工具类
           VelocityUtil.java    Velocity工具类
      --web
         --controller
              Controller.java    Controller接口,实现类必须继承Controller且标记Controller注解,实现方法必须标记RequestMapping注解
         --view
              ViewHandler.java    View处理类,完成页面文件渲染
~src/main/resources
     velocity.properties
     web.properties

- - - +learn-1 +=============== + +示例项目第一版 +完成功能如下 +--------------- +* 基本的http请求接收和响应 +* 可以分别处理动态和静态资源请求,对于静态请求直接返回对应资源,对于动态请求处理后返回 +* 简单的模板处理,通过替代符替换的方法实现模板数据渲染 diff --git a/pom.xml b/pom.xml index d87e77b..5ea5db7 100644 --- a/pom.xml +++ b/pom.xml @@ -1,48 +1,40 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.eh.http - easy-httpserver - 0.0.1 - jar + learn-1 + learn-1 + 0.0.1-SNAPSHOT + jar - easy-httpserver - http://maven.apache.org + learn-1 + http://maven.apache.org - - UTF-8 - + + UTF-8 + - - + + commons-logging commons-logging 1.1.3 - - org.apache.velocity - velocity - 1.7 - - - org.apache.velocity - velocity-tools - 2.0 - - - junit - junit - 4.10 - - - + + junit + junit + 4.10 + test + + + easy-httpserver - ${basedir}/src/main/resources + ${basedir}/src/main/view + diff --git a/src/main/java/org/eh/core/annotation/AnnocationHandler.java b/src/main/java/org/eh/core/annotation/AnnocationHandler.java deleted file mode 100644 index 5014dd3..0000000 --- a/src/main/java/org/eh/core/annotation/AnnocationHandler.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.eh.core.annotation; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.eh.core.common.Constants; - -/** - * 注解处理类 - * @author guojing - * @date 2014-3-5 - */ -public class AnnocationHandler { - - /** - * 将所有注解Controller加入Constants.UrlClassMap - * @param parkage 类名(包含包路径) - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void paserControllerAnnocation(String parkage) throws ClassNotFoundException { - List classlist = getPkgClass(parkage); - for (String str : classlist) { - Class c = Class.forName(str); - if (c.isAnnotationPresent(Controller.class)) { - Controller desc = (Controller) c.getAnnotation(Controller.class); - Constants.UrlClassMap.put(desc.url(), str); - } - } - } - - /** - * 获取指定包下的所有类名(包含包名) - * @param parkage 指定包名 - * @return - */ - public List getPkgClass(String parkage) { - String path = Constants.CLASS_PATH + parkage.replace(".", "/") + "/"; - List list = new ArrayList(); - - File file = new File(path); - for (String str : file.list()) { - if (str.endsWith(".class")) { - list.add(parkage + "." + str.replace(".class", "")); - } else if (str.indexOf(".") == -1) { - list.addAll(getPkgClass(parkage + "." + str)); - } - } - - return list; - } - - /** - * 获取类的指定方法 - * @param c - * @param methodName - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Method getMethod(Class c, String methodName) throws NoSuchMethodException, - SecurityException { - Method method = c.getMethod(methodName, Map.class); - return method.isAnnotationPresent(RequestMapping.class) ? method : null; - } -} diff --git a/src/main/java/org/eh/core/annotation/Controller.java b/src/main/java/org/eh/core/annotation/Controller.java deleted file mode 100644 index 53fd38a..0000000 --- a/src/main/java/org/eh/core/annotation/Controller.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.eh.core.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Controller注解 - * @author guojing - * @date 2014-3-5 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Documented -public @interface Controller { - - /** - * controller名,暂时无用 - */ - public String name(); - - /** - * 对应url请求路径,如htp://127.0.0.1/test/list.do 则对应 controller为:/test/,对应方法为:list - */ - public String url(); -} diff --git a/src/main/java/org/eh/core/annotation/RequestMapping.java b/src/main/java/org/eh/core/annotation/RequestMapping.java deleted file mode 100644 index 4d4e66e..0000000 --- a/src/main/java/org/eh/core/annotation/RequestMapping.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.eh.core.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 方法映射注解 - * @author guojing - * @date 2014-3-13 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface RequestMapping { - -} diff --git a/src/main/java/org/eh/core/common/Constants.java b/src/main/java/org/eh/core/common/Constants.java index 00ab418..524d4f3 100644 --- a/src/main/java/org/eh/core/common/Constants.java +++ b/src/main/java/org/eh/core/common/Constants.java @@ -2,13 +2,7 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eh.core.util.PropertyUtil; /** * @@ -16,44 +10,11 @@ * @date 2014-3-3 */ public class Constants { - private static final Log log = LogFactory.getLog(Constants.class); /* 配置信息 */ - public static String PACKAGE_PREFIX = "org.eh.web."; // 包前缀 + public static String CLASS_PATH = "";//classes文件夹路径 public static String VIEW_BASE_PATH = ""; // 路径 public static String STATIC_RESOURCE_PATH = ""; // 静态文件路径 - public static String CLASS_PATH = "";//classes文件夹路径 - - public static Map UrlClassMap = new HashMap(); // url与class映射 - public static Map OTHER_CONFIG_INFO = new HashMap(); // 其他配置信息 public static List STATIC_SUFFIXS = new ArrayList(Arrays.asList(".css", ".js", ".jpg", ".png", ".gif", ".html")); // 静态文件后缀 - - /* 常量值 */ - public static String PROPERTIES_NAME = "web.properties"; // 配置文件名 - public static String PROPERTIES_VELOCITY_NAME = "velocity.properties"; // 配置文件名 - public static String PROPERTIES_CONTROLLER_PACKAGE = "controller.package"; // controller配置文件中属性名 - public static String PROPERTIES_HPPTSERVER_PORT = "httpserver.port"; // 服务端口名 - public static String SESSION_TIMEOUT = "session_timeout"; // 服务端口名 - - public static void loadFromProp(String path) { - Map map = new HashMap(); - try { - map = PropertyUtil.analysisProperties(path); - } catch (Exception e) { - log.error("配置文件不存在!", e); - } - - for (String key : map.keySet()) { - if (key.equals("PACKAGE_PREFIX")) { - PACKAGE_PREFIX = map.get(key).toString(); - } else if (key.equals("VIEW_BASE_PATH")) { - VIEW_BASE_PATH = map.get(key).toString(); - } else if (key.startsWith("url")) { - UrlClassMap.put(key.replace("url", ""), map.get(key).toString()); - } else { - OTHER_CONFIG_INFO.put(key, map.get(key).toString()); - } - } - } } diff --git a/src/main/java/org/eh/core/common/ReturnType.java b/src/main/java/org/eh/core/common/ReturnType.java deleted file mode 100644 index 7055a9b..0000000 --- a/src/main/java/org/eh/core/common/ReturnType.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.eh.core.common; - -/** - * - * @author guojing - * @date 2014-3-7 - */ -public enum ReturnType { - velocity, redirect, json -} diff --git a/src/main/java/org/eh/core/http/ApplicationContext.java b/src/main/java/org/eh/core/http/ApplicationContext.java deleted file mode 100644 index 420ab40..0000000 --- a/src/main/java/org/eh/core/http/ApplicationContext.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.eh.core.http; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.eh.core.util.StringUtil; - -import com.sun.net.httpserver.HttpExchange; - -/** - * 全局数据和会话相关数据,单例 - * @author guojing - * @date 2014-3-17 - */ -public class ApplicationContext { - - private Map appMap = new HashMap(); // ApplicationContext全局数据 - - /** - * 这里自己也有点搞不清sessionMap是不是有必要考虑线程安全 - */ - private ConcurrentMap sessionMap = new ConcurrentHashMap(); // session数据 - - private ApplicationContext(){ - - } - - /** - * 内部类实现单例 - */ - private static class ApplicationContextHolder { - private static ApplicationContext instance = new ApplicationContext(); - } - - public static ApplicationContext getApplicationContext() { - return ApplicationContextHolder.instance; - } - - public void addAttribute(String name, Object value) { - ApplicationContextHolder.instance.appMap.put(name, value); - } - - public Object getAttribute(String name) { - return ApplicationContextHolder.instance.appMap.get(name); - } - - public Map getAllAttribute() { - return ApplicationContextHolder.instance.appMap; - } - - public Set getAllNames() { - return ApplicationContextHolder.instance.appMap.keySet(); - } - - public boolean containsName(String name) { - return ApplicationContextHolder.instance.appMap.containsKey(name); - } - - public void addSession(String sessionId) { - HttpSession httpSession = new HttpSession(); - httpSession.setLastVisitTime(new Date()); - ApplicationContextHolder.instance.sessionMap.put(sessionId, httpSession); - } - - /** - * 获取session - */ - public HttpSession getSession(HttpExchange httpExchange) { - String sessionId = getSessionId(httpExchange); - if (StringUtil.isEmpty(sessionId)) { - return null; - } - HttpSession httpSession = ApplicationContextHolder.instance.sessionMap.get(sessionId); - if (null == httpSession) { - httpSession = new HttpSession(); - ApplicationContextHolder.instance.sessionMap.put(sessionId, httpSession); - } - return httpSession; - } - - /** - * 获取sessionId - */ - public String getSessionId(HttpExchange httpExchange) { - String cookies = httpExchange.getRequestHeaders().getFirst("Cookie"); - String sessionId = ""; - if (StringUtil.isEmpty(cookies)) { - cookies = httpExchange.getResponseHeaders().getFirst("Set-Cookie"); - } - - if (StringUtil.isEmpty(cookies)) { - return null; - } - - String[] cookiearry = cookies.split(";"); - for(String cookie : cookiearry){ - cookie = cookie.replaceAll(" ", ""); - if (cookie.startsWith("EH_SESSION=")) { - sessionId = cookie.replace("EH_SESSION=", "").replace(";", ""); - } - } - - return sessionId; - } - - /** - * 获取所有session - */ - public ConcurrentMap getAllSession() { - return ApplicationContextHolder.instance.sessionMap; - } - - /** - * 设置session最后访问时间 - */ - public void setSessionLastTime(String sessionId) { - HttpSession httpSession = ApplicationContextHolder.instance.sessionMap.get(sessionId); - httpSession.setLastVisitTime(new Date()); - } -} diff --git a/src/main/java/org/eh/core/http/EHHttpHandler.java b/src/main/java/org/eh/core/http/EHHttpHandler.java index a9dc4ce..4698674 100644 --- a/src/main/java/org/eh/core/http/EHHttpHandler.java +++ b/src/main/java/org/eh/core/http/EHHttpHandler.java @@ -3,31 +3,25 @@ import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.net.URI; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.eh.core.annotation.AnnocationHandler; import org.eh.core.common.Constants; -import org.eh.core.common.ReturnType; import org.eh.core.model.ResultInfo; -import org.eh.core.util.FileUploadContentAnalysis; import org.eh.core.util.IOUtil; import org.eh.core.util.StringUtil; -import org.eh.core.web.controller.Controller; +import org.eh.core.web.controller.IndexController; import org.eh.core.web.view.ViewHandler; - import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; /** * 处理Http请求 + * * @author guojing * @date 2014-3-3 */ @@ -39,19 +33,9 @@ public void handle(HttpExchange httpExchange) throws IOException { String path = httpExchange.getRequestURI().getPath(); log.info("Receive a request,Request path:" + path); - // 设置sessionId - String sessionId = ApplicationContext.getApplicationContext() - .getSessionId(httpExchange); - if (StringUtil.isEmpty(sessionId)) { - sessionId = StringUtil.creatSession(); - ApplicationContext.getApplicationContext().addSession(sessionId); - } - - httpExchange.getResponseHeaders().set("Set-Cookie", - "EH_SESSION=" + sessionId + "; path=/"); - // 根据后缀判断是否是静态资源 - String suffix = path.substring(path.lastIndexOf("."), path.length()); + String suffix = path + .substring(path.lastIndexOf("."), path.length()); if (Constants.STATIC_SUFFIXS.contains(suffix)) { byte[] bytes = IOUtil.readFileByBytes(Constants.CLASS_PATH + "static" + path); @@ -67,27 +51,14 @@ public void handle(HttpExchange httpExchange) throws IOException { responseToClient(httpExchange, 200, "

页面不存在

"); return; } - - String viewPath = resultInfo.getView(); - if (viewPath.startsWith(ReturnType.redirect.name())) {// redirect跳转 - String redirectUrl = viewPath.replace(ReturnType.redirect.name() + ":", ""); - responseToClient(httpExchange, 302, redirectUrl); - return; - } else if (viewPath.startsWith(ReturnType.json.name())) { // 返回json数据 - String jsonContent = viewPath.replace(ReturnType.json.name() + ":", ""); - responseToClient(httpExchange, 200, jsonContent); - return; - } else if (viewPath.startsWith(ReturnType.velocity.name())) { // 解析对应view并返回 - String content = invokViewHandler(resultInfo); - if (content == null) { - content = ""; - } - responseToClient(httpExchange, 200, content); - return; - } else { - responseToClient(httpExchange, 200, resultInfo.getView()); - return; + + // 解析对应view并返回 + String content = invokViewHandler(resultInfo); + if (content == null) { + content = ""; } + responseToClient(httpExchange, 200, content); + return; } catch (Exception e) { httpExchange.close(); @@ -97,13 +68,17 @@ public void handle(HttpExchange httpExchange) throws IOException { /** * 响应请求 - * @param httpExchange 请求-响应的封装 - * @param code 返回状态码 - * @param msg 返回信息 + * + * @param httpExchange + * 请求-响应的封装 + * @param code + * 返回状态码 + * @param msg + * 返回信息 * @throws IOException */ - private void responseToClient(HttpExchange httpExchange, Integer code, String msg) - throws IOException { + private void responseToClient(HttpExchange httpExchange, Integer code, + String msg) throws IOException { switch (code) { case 200: { // 成功 @@ -135,16 +110,17 @@ private void responseToClient(HttpExchange httpExchange, Integer code, String ms break; } } - + /** * 响应请求,返回静态资源 + * * @param httpExchange * @param code * @param bytes * @throws IOException */ - private void responseStaticToClient(HttpExchange httpExchange, Integer code, byte[] bytes) - throws IOException { + private void responseStaticToClient(HttpExchange httpExchange, + Integer code, byte[] bytes) throws IOException { httpExchange.sendResponseHeaders(code, bytes.length); OutputStream out = httpExchange.getResponseBody(); out.write(bytes); @@ -154,51 +130,14 @@ private void responseStaticToClient(HttpExchange httpExchange, Integer code, byt /** * 调用对应Controller处理业务 + * @throws UnsupportedEncodingException */ - @SuppressWarnings("rawtypes") - private ResultInfo invokController(HttpExchange httpExchange) throws ClassNotFoundException, - InstantiationException, IllegalAccessException, IOException, NoSuchMethodException, - SecurityException, IllegalArgumentException, InvocationTargetException { - String path = httpExchange.getRequestURI().getPath(); - - String classPath = Constants.UrlClassMap.get(path.substring(0, path.lastIndexOf("/") + 1)); - if (classPath == null || classPath.length() == 0) { - return null; - } - Class controllerClass = Class.forName(classPath); - Controller controller = (Controller) controllerClass.newInstance(); - - String methodName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); - //通过反射获取对应方法 - AnnocationHandler annocationHandler = new AnnocationHandler(); - Method method = annocationHandler.getMethod(controllerClass, methodName); - - Map map = null; // 参数 - // 判断表单类型,若是multipart/form-data,则是文件上传;否则做普通处理 - Headers headers = httpExchange.getRequestHeaders(); - // 获取ContentType - String contentType = ""; - if(null != headers.get("Content-type")){ - contentType = headers.get("Content-type").toString().replace("[", "") - .replace("]", ""); - } - - if (contentType.indexOf("multipart/form-data") != -1) { - // 获取content长度 - int length = Integer.parseInt(headers.get("Content-length").toString().replace("[", "") - .replace("]", "")); - map = FileUploadContentAnalysis.parse(httpExchange.getRequestBody(), contentType, - length); - } else { - map = analysisParms(httpExchange); - } - - // 设置session - HttpSession httpSession = ApplicationContext.getApplicationContext().getSession( - httpExchange); - map.put("session", httpSession); + private ResultInfo invokController(HttpExchange httpExchange) throws UnsupportedEncodingException { + // 获取参数 + Map map = analysisParms(httpExchange); - return (ResultInfo) method.invoke(controller, new Object[] { map }); + IndexController controller = new IndexController(); + return controller.process(map); } /** @@ -206,8 +145,7 @@ private ResultInfo invokController(HttpExchange httpExchange) throws ClassNotFou */ private String invokViewHandler(ResultInfo resultInfo) throws IOException { ViewHandler viewHandler = new ViewHandler(); - // return viewHandler.processView(resultInfo); - return viewHandler.processVelocityView(resultInfo); + return viewHandler.processView(resultInfo); } /** @@ -219,13 +157,15 @@ private Map analysisParms(HttpExchange httpExchange) URI requestedUri = httpExchange.getRequestURI(); String queryGet = requestedUri.getRawQuery(); - String queryPost = IOUtil.getRequestContent(httpExchange.getRequestBody()); + String queryPost = IOUtil.getRequestContent(httpExchange + .getRequestBody()); String query = ""; if (!StringUtil.isEmpty(queryGet)) { query = queryGet; } if (!StringUtil.isEmpty(queryPost)) { - query = StringUtil.isEmpty(query) ? queryPost : (query + "&" + queryPost); + query = StringUtil.isEmpty(query) ? queryPost + : (query + "&" + queryPost); } if (StringUtil.isEmpty(query)) { return map; diff --git a/src/main/java/org/eh/core/http/EHServer.java b/src/main/java/org/eh/core/http/EHServer.java index 8d17efb..b731702 100644 --- a/src/main/java/org/eh/core/http/EHServer.java +++ b/src/main/java/org/eh/core/http/EHServer.java @@ -2,15 +2,10 @@ import java.io.IOException; import java.net.InetSocketAddress; -import java.util.Date; -import java.util.Timer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.velocity.app.Velocity; -import org.eh.core.annotation.AnnocationHandler; import org.eh.core.common.Constants; -import org.eh.core.task.SessionCleanTask; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.spi.HttpServerProvider; @@ -28,65 +23,22 @@ public class EHServer { */ public void startServer() throws IOException { log.info("Starting EHServer......"); - log.info("Loading configuration......"); - - //设置classes文件夹路径 - Constants.CLASS_PATH = this.getClass().getResource("/").getPath().replace("bin", "classes"); - // 加载配置文件 - String propPath = Constants.CLASS_PATH + Constants.PROPERTIES_NAME; - Constants.loadFromProp(propPath); - - // 加载注解配置的controller - if (Constants.OTHER_CONFIG_INFO.get(Constants.PROPERTIES_CONTROLLER_PACKAGE) != null) { - AnnocationHandler annocationHandler = new AnnocationHandler(); - try { - annocationHandler.paserControllerAnnocation(Constants.OTHER_CONFIG_INFO.get( - Constants.PROPERTIES_CONTROLLER_PACKAGE).toString()); - } catch (Exception e) { - log.error("加载controller配置出错!", e); - return; - } - } - - // 初始化Velocity模板 - log.info("Initializing velocity......"); - Velocity.init(Constants.CLASS_PATH - + Constants.PROPERTIES_VELOCITY_NAME); - - for (String key : Constants.UrlClassMap.keySet()) { - log.info("Add url-class:" + key + " " + Constants.UrlClassMap.get(key)); - } - - int port = 8899; + //设置路径 + Constants.CLASS_PATH = this.getClass().getResource("/").getPath(); + Constants.VIEW_BASE_PATH = "page"; + Constants.STATIC_RESOURCE_PATH = "static"; + //设置端口号 - String portValue = Constants.OTHER_CONFIG_INFO.get(Constants.PROPERTIES_HPPTSERVER_PORT); - log.info("Set port:" + portValue); - if (portValue != null) { - try { - port = Integer.parseInt(portValue); - } catch (Exception e) { - log.error("端口错误!", e); - return; - } - } + int port = 8899; - //启动session过期清理定时器 - Timer timer = new Timer(); - SessionCleanTask sessionCleanTask = new SessionCleanTask(); - int session_timeout = Integer.parseInt(Constants.OTHER_CONFIG_INFO - .get(Constants.SESSION_TIMEOUT)); - log.info("Initializing SessionCleanTask,the session_out_time is " + session_timeout * 2 - + " minute."); - timer.schedule(sessionCleanTask, new Date(), session_timeout * 60 * 2 * 1000); - // 启动服务器 HttpServerProvider provider = HttpServerProvider.provider(); HttpServer httpserver = provider.createHttpServer(new InetSocketAddress(port), 100); httpserver.createContext("/", new EHHttpHandler()); httpserver.setExecutor(null); httpserver.start(); - log.info("EHServer has started"); + log.info("EHServer is started, listening at 8899."); } /** diff --git a/src/main/java/org/eh/core/http/HttpSession.java b/src/main/java/org/eh/core/http/HttpSession.java deleted file mode 100644 index b117dae..0000000 --- a/src/main/java/org/eh/core/http/HttpSession.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.eh.core.http; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * session数据 - * @author guojing - * @date 2014-3-17 - */ -public class HttpSession { - - Map map = new HashMap(); - - Date lastVisitTime = new Date(); // 最后访问时间 - - public void addAttribute(String name, Object value) { - map.put(name, value); - } - - public Object getAttribute(String name) { - return map.get(name); - } - - public Map getAllAttribute() { - return map; - } - - public Set getAllNames() { - return map.keySet(); - } - - public boolean containsName(String name) { - return map.containsKey(name); - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public Date getLastVisitTime() { - return lastVisitTime; - } - - public void setLastVisitTime(Date lastVisitTime) { - this.lastVisitTime = lastVisitTime; - } - -} diff --git a/src/main/java/org/eh/core/model/FileInfo.java b/src/main/java/org/eh/core/model/FileInfo.java deleted file mode 100644 index b92c684..0000000 --- a/src/main/java/org/eh/core/model/FileInfo.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.eh.core.model; - -/** - * 上传文件信息 - * @author guojing - * @date 2014-3-3 - */ -public class FileInfo { - - private String filename; //文件名 - private String fieldname; // 表单中参数名 - private int length; //文件长度 - private byte[] bytes; //文件字节数组 - - public String getFilename() { - return filename; - } - public void setFilename(String filename) { - this.filename = filename; - } - public int getLength() { - return length; - } - public void setLength(int length) { - this.length = length; - } - public byte[] getBytes() { - return bytes; - } - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } - - public String getFieldname() { - return fieldname; - } - - public void setFieldname(String fieldname) { - this.fieldname = fieldname; - } - - -} diff --git a/src/main/java/org/eh/core/task/SessionCleanTask.java b/src/main/java/org/eh/core/task/SessionCleanTask.java deleted file mode 100644 index 2df93da..0000000 --- a/src/main/java/org/eh/core/task/SessionCleanTask.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.eh.core.task; - -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentMap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eh.core.common.Constants; -import org.eh.core.http.ApplicationContext; -import org.eh.core.http.HttpSession; - -/** - * 定时清理过期session - * @author guojing - * @date 2014-3-17 - */ -public class SessionCleanTask extends TimerTask { - private final Log log = LogFactory.getLog(SessionCleanTask.class); - - @Override - public void run() { - log.info("清理session......"); - ConcurrentMap sessionMap = ApplicationContext.getApplicationContext() - .getAllSession(); - - Iterator> it = sessionMap.entrySet().iterator(); - while (it.hasNext()) { - ConcurrentMap.Entry entry= (Entry) it.next(); - HttpSession httpSession= entry.getValue(); - - Date nowDate = new Date(); - int diff = (int) ((nowDate.getTime() - httpSession.getLastVisitTime().getTime())/1000/60); - - if (diff > Integer.parseInt(Constants.OTHER_CONFIG_INFO.get(Constants.SESSION_TIMEOUT))) { - it.remove(); - } - } - - log.info("清理session结束"); - } -} diff --git a/src/main/java/org/eh/core/util/FileUploadContentAnalysis.java b/src/main/java/org/eh/core/util/FileUploadContentAnalysis.java deleted file mode 100644 index 6b99ed0..0000000 --- a/src/main/java/org/eh/core/util/FileUploadContentAnalysis.java +++ /dev/null @@ -1,194 +0,0 @@ -package org.eh.core.util; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.util.HashMap; -import java.util.Map; - -import org.eh.core.model.FileInfo; - -/** - * 解析content获取上传文件表单信息 - * @author 自己写的老有问题,一怒之下copy了一份。不过这个也有些问题,由于office不同版本的Content-Type格式不固定, 所以office文件上传生成的文件一般会少几个字节,以后有心情了再改吧 - * @date 2014-3-10 - */ -public class FileUploadContentAnalysis { - static final int NONE = 0; - static final int DATAHEADER = 1; - static final int FILEDATA = 2; - static final int FIELDDATA = 3; - static final int MXA_SEGSIZE = 1000 * 1024 * 10; //最大文件长度 - - public static Map parse(InputStream ins, String contentType, int totalLength) - throws IOException { - - FileInfo fileInfo =new FileInfo(); - String fieldname = ""; // 表单域的名称 - String fieldvalue = ""; // 表单域的值 - String filename = ""; // 文件名 - String boundary = ""; // 分界符 - String lastboundary = ""; // 结束符 - String filefieldname = ""; // 文件表单域名 - Map formfields = new HashMap(); - int filesize = 0; // 文件长度 - - int pos = contentType.indexOf("boundary="); - - if (pos != -1) { // 取得分界符和结束符 - pos += "boundary=".length(); - boundary = "--" + contentType.substring(pos); - lastboundary = boundary + "--"; - } - int state = NONE; - // 得到数据输入流reqbuf - DataInputStream in = new DataInputStream(ins); - // 将请求消息的实体送到b变量中 - int totalBytes = totalLength; - if (totalBytes > MXA_SEGSIZE) {// 每批大于10m时 - return null; - } - byte[] b = new byte[totalBytes]; - in.readFully(b); - in.close(); - String reqContent = new String(b, "UTF-8");// - BufferedReader reqbuf = new BufferedReader(new StringReader(reqContent)); - - boolean flag = true; - while (flag == true) { - String s = reqbuf.readLine(); - if ((s == null) || (s.equals(lastboundary))) - break; - - switch (state) { - case NONE: - if (s.startsWith(boundary)) { - state = DATAHEADER; - } - break; - case DATAHEADER: - pos = s.indexOf("filename="); - if (pos == -1) { // 将表单域的名字解析出来 - pos = s.indexOf("name="); - pos += "name=".length() + 1; - s = s.substring(pos); - int l = s.length(); - s = s.substring(0, l - 1); - fieldname = s; - state = FIELDDATA; - } else { - String temp = s; - // 将文件表单参数名解析出来 - pos = s.indexOf("name="); - pos += "name=".length() + 1; - s = s.substring(pos); - int pos1 = s.indexOf("\";"); - filefieldname = s.substring(0, pos1); - - // 将文件名解析出来 - pos = s.indexOf("filename="); - pos += "filename=".length() + 1; - s = s.substring(pos); - int l = s.length(); - s = s.substring(0, l - 1);// 去掉最后那个引号” - pos = s.lastIndexOf("\\"); - s = s.substring(pos + 1); - filename = s; - // 从字节数组中取出文件数组 - pos = byteIndexOf(b, temp, 0); - b = subBytes(b, pos + temp.getBytes().length + 2, b.length);// 去掉前面的部分 - int n = 0; - /** - * 过滤boundary下形如 Content-Disposition: form-data; name="bin"; filename="12.pdf" Content-Type: - * application/octet-stream Content-Transfer-Encoding: binary 的字符串 - */ - while ((s = reqbuf.readLine()) != null) { - if (n == 1) - break; - if (s.equals("")) - n++; - - b = subBytes(b, s.getBytes().length + 2, b.length); - } - pos = byteIndexOf(b, boundary, 0); - if (pos != -1) - b = subBytes(b, 0, pos - 1); - - filesize = b.length - 1; - state = FILEDATA; - } - break; - case FIELDDATA: - s = reqbuf.readLine(); - fieldvalue = s; - formfields.put(fieldname, fieldvalue); - state = NONE; - break; - case FILEDATA: - while ((!s.startsWith(boundary)) && (!s.startsWith(lastboundary))) { - s = reqbuf.readLine(); - if (s.startsWith(boundary)) { - state = DATAHEADER; - break; - } - } - break; - } - } - fileInfo.setFieldname(filefieldname); - fileInfo.setBytes(b); - fileInfo.setFilename(filename); - fileInfo.setLength(filesize); - formfields.put(filefieldname, fileInfo); - return formfields; - - } - - // 字节数组中的INDEXOF函数,与STRING类中的INDEXOF类似 - public static int byteIndexOf(byte[] b, String s, int start) { - return byteIndexOf(b, s.getBytes(), start); - } - - // 字节数组中的INDEXOF函数,与STRING类中的INDEXOF类似 - public static int byteIndexOf(byte[] b, byte[] s, int start) { - int i; - if (s.length == 0) { - return 0; - } - int max = b.length - s.length; - if (max < 0) - return -1; - if (start > max) - return -1; - if (start < 0) - start = 0; - search: for (i = start; i <= max; i++) { - if (b[i] == s[0]) { - int k = 1; - while (k < s.length) { - if (b[k + i] != s[k]) { - continue search; - } - k++; - } - return i; - } - } - return -1; - } - - // 用于从一个字节数组中提取一个字节数组 - public static byte[] subBytes(byte[] b, int from, int end) { - byte[] result = new byte[end - from]; - System.arraycopy(b, from, result, 0, end - from); - return result; - } - - // 用于从一个字节数组中提取一个字符串 - public static String subBytesString(byte[] b, int from, int end) { - return new String(subBytes(b, from, end)); - } - -} diff --git a/src/main/java/org/eh/core/util/PropertyUtil.java b/src/main/java/org/eh/core/util/PropertyUtil.java deleted file mode 100644 index 7a8cdbd..0000000 --- a/src/main/java/org/eh/core/util/PropertyUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.eh.core.util; - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * 配置文件工具类 - * @author guojing - * @date 2014-3-4 - */ -public class PropertyUtil { - private static final Log log = LogFactory.getLog(PropertyUtil.class); - public static Map analysisProperties(String path) { - Map map = new HashMap(); - Properties props = new Properties(); - try { - InputStream in = new BufferedInputStream(new FileInputStream(path)); - props.load(in); - for (String key : props.stringPropertyNames()) { - map.put(key, props.get(key).toString()); - } - } catch (Exception e) { - log.error("配置文件解析错误:", e); - } - return map; - } -} diff --git a/src/main/java/org/eh/core/util/VelocityUtil.java b/src/main/java/org/eh/core/util/VelocityUtil.java deleted file mode 100644 index 08c5f3b..0000000 --- a/src/main/java/org/eh/core/util/VelocityUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.eh.core.util; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Map; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; - -/** - * Velocity解析类 - * @author guojing - * @date 2014-3-10 - */ -public class VelocityUtil { - - /** - * 渲染Velocity模板 - * @param path - * @param map - */ - public static String mergeTemplate(String path, Map map) throws IOException { - VelocityContext vc = new VelocityContext(); - if (null != map) { - for (String key : map.keySet()) { - vc.put(key, map.get(key)); - } - } - StringWriter w = new StringWriter(); - Velocity.mergeTemplate(path, "utf-8", vc, w); - String content = w.toString(); - w.close(); - return content; - } -} diff --git a/src/main/java/org/eh/core/web/controller/IndexController.java b/src/main/java/org/eh/core/web/controller/IndexController.java new file mode 100644 index 0000000..45b7816 --- /dev/null +++ b/src/main/java/org/eh/core/web/controller/IndexController.java @@ -0,0 +1,19 @@ +package org.eh.core.web.controller; + +import java.util.Map; + +import org.eh.core.model.ResultInfo; + +/** + * 主页对应的contoller + * @author guojing + */ +public class IndexController implements Controller{ + + public ResultInfo process(Map map){ + ResultInfo result =new ResultInfo(); + result.setView("index"); + result.setResultMap(map); + return result; + } +} diff --git a/src/main/java/org/eh/core/web/view/ViewHandler.java b/src/main/java/org/eh/core/web/view/ViewHandler.java index 1a1bbab..c0548bd 100644 --- a/src/main/java/org/eh/core/web/view/ViewHandler.java +++ b/src/main/java/org/eh/core/web/view/ViewHandler.java @@ -3,11 +3,9 @@ import java.io.IOException; import org.eh.core.common.Constants; -import org.eh.core.common.ReturnType; import org.eh.core.model.ResultInfo; import org.eh.core.util.IOUtil; import org.eh.core.util.StringUtil; -import org.eh.core.util.VelocityUtil; /** * 处理页面信息 @@ -20,7 +18,6 @@ public class ViewHandler { * 处理View模板,只提供建单变量(格式${XXX})替换,已废弃 * @return */ - @Deprecated public String processView(ResultInfo resultInfo) { // 获取路径 String path = analysisViewPath(resultInfo.getView()); @@ -44,48 +41,16 @@ public String processView(ResultInfo resultInfo) { return content; } - - /** - * 处理Velocity模板 - * @param resultInfo - * @return - * @throws IOException - */ - public String processVelocityView(ResultInfo resultInfo) throws IOException { - if (StringUtil.isEmpty(resultInfo.getView())) { - return ""; - } - - // 获取路径 - String path = analysisVelocityViewPath(resultInfo.getView()); - String content = VelocityUtil.mergeTemplate(path, resultInfo.getResultMap()); - - if (StringUtil.isEmpty(content)) { - return ""; - } - - return content; - } - + /** * 解析路径(根据Controller返回ResultInfo的view),已废弃 * @param viewPath * @return */ - @Deprecated private String analysisViewPath(String viewPath) { String path = Constants.CLASS_PATH - + (Constants.VIEW_BASE_PATH == null ? "/" : Constants.VIEW_BASE_PATH) + + (Constants.VIEW_BASE_PATH == null ? "/" : Constants.VIEW_BASE_PATH+"/") + viewPath + ".page"; return path; } - - /** - * 解析velocity路径(根据Controller返回ResultInfo的view) - */ - private String analysisVelocityViewPath(String viewPath) { - String path = Constants.VIEW_BASE_PATH + "/" - + viewPath.replace(ReturnType.velocity.name() + ":", "") + ".vm"; - return path; - } } diff --git a/src/main/resources/velocity.properties b/src/main/resources/velocity.properties deleted file mode 100644 index db5a5ec..0000000 --- a/src/main/resources/velocity.properties +++ /dev/null @@ -1,2 +0,0 @@ -resource.loader=class -class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader \ No newline at end of file diff --git a/src/main/resources/web.properties b/src/main/resources/web.properties deleted file mode 100644 index 897b070..0000000 --- a/src/main/resources/web.properties +++ /dev/null @@ -1,20 +0,0 @@ -#包前缀 -PACKAGE_PREFIX=org.eh.web - -#模板页面根路径(相对classes文件夹,项目src/main/view下) -VIEW_BASE_PATH=page - -#静态资源路劲(相对classes文件夹,项目src/main/view下) -STATIC_RESOURCE_PATH=static - -#端口 -httpserver.port=8888 - -#controller包路径,配置后可通过annocation直接配置 -controller.package=com.gj.web.controller - -#url与controller类对应关系 -#url/list=com.gj.web.controller.MyController - -#session超时时间(分钟) -session_timeout = 10 \ No newline at end of file diff --git a/src/main/view/page/index.page b/src/main/view/page/index.page new file mode 100644 index 0000000..77b4b2c --- /dev/null +++ b/src/main/view/page/index.page @@ -0,0 +1,12 @@ + + + + + +

Hello,${name}

+ + + \ No newline at end of file diff --git a/src/main/view/static/js/test.js b/src/main/view/static/js/test.js new file mode 100644 index 0000000..43d363e --- /dev/null +++ b/src/main/view/static/js/test.js @@ -0,0 +1,3 @@ +function hello(){ + console.log("hello!") +} \ No newline at end of file diff --git a/src/main/view/static/pic/tx.jpg b/src/main/view/static/pic/tx.jpg new file mode 100644 index 0000000..7bf50f3 Binary files /dev/null and b/src/main/view/static/pic/tx.jpg differ diff --git a/src/test/java/org/eh/core/annotation/AnnotationHandlerTest.java b/src/test/java/org/eh/core/annotation/AnnotationHandlerTest.java deleted file mode 100644 index fe2d5f5..0000000 --- a/src/test/java/org/eh/core/annotation/AnnotationHandlerTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.eh.core.annotation; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Map; - -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-13 - */ -public class AnnotationHandlerTest { - - @Test - @SuppressWarnings("rawtypes") - public void testMethods() { - try { - Class c = Class.forName("org.eh.core.controller.Test1Controller"); - Method[] methods = c.getMethods(); - for (Method method : methods) { - if (method.isAnnotationPresent(RequestMapping.class)) { - System.out.println(method.getName()); - org.eh.core.web.controller.Controller controller = (org.eh.core.web.controller.Controller) c - .newInstance(); - method.invoke(controller, new Object[] { null }); - } - } - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testMethod() { - try { - Class c = Class.forName("org.eh.core.controller.Test1Controller"); - Method methods = c.getMethod("add", Map.class); - System.out.println(methods.getName()); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } - } -} diff --git a/src/test/java/org/eh/core/controller/Test1Controller.java b/src/test/java/org/eh/core/controller/Test1Controller.java deleted file mode 100644 index 5e611ed..0000000 --- a/src/test/java/org/eh/core/controller/Test1Controller.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.eh.core.controller; - -import java.util.Map; - -import org.eh.core.annotation.RequestMapping; -import org.eh.core.web.controller.Controller; - -/** - * - * @author guojing - * @date 2014-3-5 - */ -@org.eh.core.annotation.Controller(name = "test1", url = "/test/show") -public class Test1Controller implements Controller { - - @RequestMapping - public String add(Map map) { - System.out.println("aaa"); - return null; - } -} diff --git a/src/test/java/org/eh/core/controller/Test2Controller.java b/src/test/java/org/eh/core/controller/Test2Controller.java deleted file mode 100644 index e1045d5..0000000 --- a/src/test/java/org/eh/core/controller/Test2Controller.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.eh.core.controller; - -import org.eh.core.annotation.Controller; - -/** - * - * @author guojing - * @date 2014-3-5 - */ -@Controller(name = "test2", url = "/test/list") -public interface Test2Controller { - -} diff --git a/src/test/java/org/eh/core/controller/TestAnnocation.java b/src/test/java/org/eh/core/controller/TestAnnocation.java deleted file mode 100644 index 109ef27..0000000 --- a/src/test/java/org/eh/core/controller/TestAnnocation.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.eh.core.controller; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-5 - */ -public class TestAnnocation { - - @Test - public void getAnnontion() { - List list = getPkgClass("org.eh.core.controller"); - System.out.println(Arrays.toString(list.toArray())); - } - - public List getPkgClass(String parkage) { - String path = this.getClass().getResource("/").getPath() + parkage.replace(".", "/") + "/"; - List list = new ArrayList(); - - File file = new File(path); - for(String str :file.list()){ - if (str.endsWith(".class")) { - list.add(parkage + "." + str.replace(".class", "")); - } else if (str.indexOf(".") == -1) { - list.addAll(getPkgClass(parkage + "." + str)); - } - } - - return list; - } -} diff --git a/src/test/java/org/eh/core/controller/pss/Test3Controller.java b/src/test/java/org/eh/core/controller/pss/Test3Controller.java deleted file mode 100644 index 28839db..0000000 --- a/src/test/java/org/eh/core/controller/pss/Test3Controller.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.eh.core.controller.pss; - -import org.eh.core.annotation.Controller; - -/** - * - * @author guojing - * @date 2014-3-5 - */ -@Controller(name = "test3", url = "/test/send") -public class Test3Controller { - -} diff --git a/src/test/java/org/eh/core/other/StringTest.java b/src/test/java/org/eh/core/other/StringTest.java deleted file mode 100644 index 630765c..0000000 --- a/src/test/java/org/eh/core/other/StringTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.eh.core.other; - -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-6 - */ -public class StringTest { - - @Test - public void testSub() { - // String path = "test/path/list.do"; - // String suffix = path.substring(path.lastIndexOf("."), path.length()); - System.out.println(System.getProperty("user.dir")); - } -} diff --git a/src/test/java/org/eh/core/util/FileUtilTest.java b/src/test/java/org/eh/core/util/FileUtilTest.java deleted file mode 100644 index 419e1e8..0000000 --- a/src/test/java/org/eh/core/util/FileUtilTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.eh.core.util; - -import org.eh.core.common.Constants; -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-4 - */ -public class FileUtilTest { - - @Test - public void TestRead() { - String path = Constants.CLASS_PATH - + "org/eh/web/view/test/myinfo.page"; - String content = IOUtil.readFile(path); - System.out.println(content); - } - -} diff --git a/src/test/java/org/eh/core/util/PropertyUtilTest.java b/src/test/java/org/eh/core/util/PropertyUtilTest.java deleted file mode 100644 index 2ec031e..0000000 --- a/src/test/java/org/eh/core/util/PropertyUtilTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.eh.core.util; - -import org.eh.core.common.Constants; -import org.eh.core.common.ReturnType; -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-4 - */ -public class PropertyUtilTest { - - @Test - public void testResd() { - PropertyUtil.analysisProperties(Constants.CLASS_PATH - + "web.properties"); - } - - @Test - public void testReflect() { - System.out.println(ReturnType.redirect.name()); - } -} diff --git a/src/test/java/org/eh/velocity/VelocityTest.java b/src/test/java/org/eh/velocity/VelocityTest.java deleted file mode 100644 index 89e360b..0000000 --- a/src/test/java/org/eh/velocity/VelocityTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.eh.velocity; - -import java.io.StringWriter; -import java.util.Properties; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.junit.Test; - -/** - * - * @author guojing - * @date 2014-3-10 - */ -public class VelocityTest { - - @Test - public void testVelocity() { - Properties p =new Properties(); - p.setProperty("resource.loader", "class"); - p.setProperty("class.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - - Velocity.init(p); - VelocityContext vc = new VelocityContext(); - vc.put("name", "guojing"); - StringWriter w = new StringWriter(); -// Velocity.mergeTemplate("org/eh/velocity/test.vm", "utf-8", vc, w); - System.out.println(w); - } -} diff --git a/src/test/java/org/eh/velocity/test.vm b/src/test/java/org/eh/velocity/test.vm deleted file mode 100644 index ccf2d93..0000000 --- a/src/test/java/org/eh/velocity/test.vm +++ /dev/null @@ -1 +0,0 @@ -hello!$!{name}。 \ No newline at end of file diff --git a/src/test/java/org/eh/web/controller/Test1Controller.java b/src/test/java/org/eh/web/controller/Test1Controller.java deleted file mode 100644 index 926ef10..0000000 --- a/src/test/java/org/eh/web/controller/Test1Controller.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.eh.web.controller; - -import org.eh.core.annotation.Controller; - -/** - * - * @author guojing - * @date 2014-3-5 - */ -@Controller(name = "test1", url = "/test/mark") -public class Test1Controller { - -} diff --git a/src/test/java/org/eh/web/controller/TestController.java b/src/test/java/org/eh/web/controller/TestController.java deleted file mode 100644 index cc53eb0..0000000 --- a/src/test/java/org/eh/web/controller/TestController.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.eh.web.controller; - -import java.util.HashMap; -import java.util.Map; - -import org.eh.core.model.ResultInfo; -import org.eh.core.web.controller.Controller; - -/** - * - * @author guojing - * @date 2014-3-3 - */ -public class TestController implements Controller { - - public ResultInfo process(Map parms) { - ResultInfo resultInfo = new ResultInfo(); - Map map = new HashMap(); - map.put("name", parms.get("name")); - map.put("msg", parms.get("msg")); - - resultInfo.setResultMap(map); - resultInfo.setView("test/myinfo"); - return resultInfo; - } - -} diff --git a/src/test/java/org/eh/web/view/test/myinfo.page b/src/test/java/org/eh/web/view/test/myinfo.page deleted file mode 100644 index c7fbbc5..0000000 --- a/src/test/java/org/eh/web/view/test/myinfo.page +++ /dev/null @@ -1,7 +0,0 @@ - - - - -

${msg},${name}

- - \ No newline at end of file diff --git a/target/classes/web.properties b/target/classes/web.properties deleted file mode 100644 index 897b070..0000000 --- a/target/classes/web.properties +++ /dev/null @@ -1,20 +0,0 @@ -#包前缀 -PACKAGE_PREFIX=org.eh.web - -#模板页面根路径(相对classes文件夹,项目src/main/view下) -VIEW_BASE_PATH=page - -#静态资源路劲(相对classes文件夹,项目src/main/view下) -STATIC_RESOURCE_PATH=static - -#端口 -httpserver.port=8888 - -#controller包路径,配置后可通过annocation直接配置 -controller.package=com.gj.web.controller - -#url与controller类对应关系 -#url/list=com.gj.web.controller.MyController - -#session超时时间(分钟) -session_timeout = 10 \ No newline at end of file diff --git a/target/maven-archiver/pom.properties b/target/maven-archiver/pom.properties deleted file mode 100644 index 87bbb17..0000000 --- a/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Thu Mar 27 22:41:48 CST 2014 -version=0.0.1 -groupId=org.eh.http -artifactId=easy-httpserver