Skip to content

Commit

Permalink
添加Servlet路由
Browse files Browse the repository at this point in the history
  • Loading branch information
刘义 committed Oct 28, 2018
1 parent 1361948 commit 493e057
Show file tree
Hide file tree
Showing 11 changed files with 417 additions and 0 deletions.
122 changes: 122 additions & 0 deletions framework/src/main/java/com/custom/framework/DispatcherServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package com.custom.framework;

import com.custom.framework.bean.Data;
import com.custom.framework.bean.Handler;
import com.custom.framework.bean.Param;
import com.custom.framework.bean.View;
import com.custom.framework.helper.BeanHelper;
import com.custom.framework.helper.ConfigHelper;
import com.custom.framework.helper.ControllerHelper;
import com.custom.framework.helper.HelperLoader;
import com.custom.framework.util.ArrayUtil;
import com.custom.framework.util.CodecUtil;
import com.custom.framework.util.JsonUtil;
import com.custom.framework.util.ReflectionUtil;
import com.custom.framework.util.StreamUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**请求转发器
* @author liuyi
* @date 2018/10/28
*/
public class DispatcherServlet extends HttpServlet {

@Override
public void init(ServletConfig servletConfig) throws ServletException {
//初始化相关 Helper类
HelperLoader.init();
//获取ServletContext对象(用于注册Servlet)
ServletContext servletContext = servletConfig.getServletContext();
//注册处理JSP的Servlet
ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
//注册处理静态资源的默认servlet
ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
}

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求方法与请求路径
String requestMethod = request.getMethod().toLowerCase();
String requestPath = request.getPathInfo();
//获取Action处理器
Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
if (handler != null) {
//获取 Controller 类及其 Bean实例
Class<?> controllerClass = handler.getControllerClass();
Object controllerBean = BeanHelper.getBean(controllerClass);
// 创建请求参数对象
Map<String, Object> paramMap = new HashMap<>();
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
String paramValue = request.getParameter(paramName);
paramMap.put(paramName, paramValue);
}
String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
if (StringUtils.isNotEmpty(body)) {
String[] params = StringUtils.split(body, "&");
if (ArrayUtil.isNotEmpty(params)) {
for (String param : params) {
String[] array =StringUtils.split(param, "=");
if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
String paramName = array[0];
String paramValue = array[1];
paramMap.put(paramName, paramValue);
}
}
}
}

Param param = new Param(paramMap);
//调用Action 方法
Method actionMethod = handler.getActionMethod();
Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
if (result instanceof View) {
//返回 JSP 页面
View view = (View) result;
String path = view.getPath();
if (StringUtils.isNotEmpty(path)) {
if (path.startsWith("/")) {
response.sendRedirect(request.getContextPath() + path);
} else {
Map<String, Object> model = view.getModel();
for (Map.Entry<String,Object> entry : model.entrySet()) {
request.setAttribute(entry.getKey(), entry.getValue());
}
request.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(request, response);
}
} else if (result instanceof Data) {
//返回 JSON 数据
Data data = (Data) result;
Object model = data.getModel();
if (model != null) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
String json = JsonUtil.toJson(model);
writer.write(json);
writer.flush();
writer.close();
}
}
}
}
}

}
18 changes: 18 additions & 0 deletions framework/src/main/java/com/custom/framework/bean/Data.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.custom.framework.bean;

/**
* @author liuyi
* @date 2018/10/28
*/
public class Data {

private Object model;

public Data(Object model) {
this.model = model;
}

public Object getModel() {
return model;
}
}
36 changes: 36 additions & 0 deletions framework/src/main/java/com/custom/framework/bean/Param.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.custom.framework.bean;

import com.custom.framework.util.CastUtil;

import java.util.Map;

/**
* 请求参数对象
* @author liuyi
* @date 2018/10/28
*/
public class Param {

private Map<String, Object> paramMap;

public Param(Map<String, Object> paramMap) {
this.paramMap = paramMap;
}

/**
* 根据参数名获取 long 型参数值
* @param name
* @return
*/
public long getLong(String name) {
return CastUtil.castLong(paramMap.get(name));
}

/**
* 获取所有字段信息
* @return
*/
public Map<String, Object> getMap() {
return paramMap;
}
}
39 changes: 39 additions & 0 deletions framework/src/main/java/com/custom/framework/bean/View.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.custom.framework.bean;

import java.util.HashMap;
import java.util.Map;
/**
* 返回视图对象
* @author liuyi
* @date 2018/10/28
*/
public class View {

/**
* 视图路径
*/
private String path;

/**
* 模型数据
*/
private Map<String, Object> model;

public View(String path) {
this.path = path;
model = new HashMap<>();
}

public View adModel(String key, Object value) {
model.put(key, value);
return this;
}

public String getPath() {
return path;
}

public Map<String, Object> getModel() {
return model;
}
}
63 changes: 63 additions & 0 deletions framework/src/main/java/com/custom/framework/util/CastUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.custom.framework.util;

import org.apache.commons.lang3.StringUtils;

/**
* 数据转型工具类
* @author liuyi
* @date 2018/10/28
*/
public class CastUtil {


/**
* 转为long类型
* @param obj
* @return
*/
public static long castLong(Object obj){
return CastUtil.castLong(obj,0);
}

/**
* 转为long
* @param obj
* @param defaultValue
* @return
*/
public static long castLong(Object obj,long defaultValue){
long value = defaultValue;
if (obj!=null){
String strValue = castString(obj);
if (StringUtils.isNotEmpty(strValue)){
try{
value = Long.parseLong(strValue);
}catch (NumberFormatException e){
value = defaultValue;
}
}
}
return value;
}

/**
* 转为String
* @param obj
* @return
*/
public static String castString(Object obj){
return CastUtil.castString(obj,"");
}

/**
* 转为String
* @param obj
* @param defaultValue
* @return
*/
public static String castString(Object obj,String defaultValue){
return obj!=null?String.valueOf(obj):defaultValue;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@


/**
* 类加载器工具类
* @author liuyi
* @date 2018/10/15
*/
Expand Down
49 changes: 49 additions & 0 deletions framework/src/main/java/com/custom/framework/util/CodecUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.custom.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* 编码与解码操作工具类
* @author liuyi
* @date 2018/10/28
*/
public final class CodecUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(CodecUtil.class);

/**
* 将URL编码
* @param source
* @return
*/
public static String encodeURL(String source) {
String target;
try {
target = URLEncoder.encode(source, "UTF-8");
} catch (Exception e) {
LOGGER.error("encode url failure", e);
throw new RuntimeException(e);
}
return target;
}

/**
* 将URL解码
* @param source
* @return
*/
public static String decodeURL(String source) {
String target;
try {
target = URLDecoder.decode(source, "UTF-8");
} catch (Exception e) {
LOGGER.error("dencode url failure", e);
throw new RuntimeException(e);
}
return target;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Set;

/**
* 结合工具类
* @author liuyi
* @date 2018/10/27
*/
Expand Down
49 changes: 49 additions & 0 deletions framework/src/main/java/com/custom/framework/util/JsonUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.custom.framework.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* JSON 工具类
* @author liuyi
* @date 2018/10/28
*/
public final class JsonUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

/**
* 将POJO转为JSON
*/
public static <T> String toJson(T obj) {
String json;
try {
json = OBJECT_MAPPER.writeValueAsString(obj);
} catch (Exception e) {
LOGGER.error("convert POJO to JSON failure", e);
throw new RuntimeException(e);
}
return json;
}

/**
* 将JSON转为POJO
* @param json
* @param type
* @param <T>
* @return
*/
public static <T> T fromJson(String json, Class<T> type) {
T pojo;
try {
pojo = OBJECT_MAPPER.readValue(json, type);
} catch (Exception e) {
LOGGER.error("convert JSON to POJO failure", e);
throw new RuntimeException(e);
}
return pojo;
}
}
Loading

0 comments on commit 493e057

Please sign in to comment.