由于是本人在自己开发的公司项目中节选出来备忘,有关公司信息用***代替掉。
Demo
package ***.servlet.admin; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ***.bll.admin.AccountBL; import ***.entity.account.AccountEntity; import ***.servlet.BaseServlet; @WebServlet("/admin/AccountServlet/*") public class AccountServlet extends BaseServlet { private static final long serialVersionUID = -131314941210248065L; private AccountBL bl; public AccountServlet() { super(); bl = new AccountBL(); } public void getAccountList(HttpServletRequest request, HttpServletResponse response) throws Exception { String keyWord = request.getParameter("keyWord"); String status = request.getParameter("status"); Listlist = bl.getAccountList(keyWord, status); responseList(request, response, list); } }
BaseServlet
import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger;import ***.DataConvertHelper; import ***.helper.ServletHelper; import ***.orm.PageResultSet; import ***.utils.gson.IntegerDefaultAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder;public class BaseServlet extends HttpServlet { private static final long serialVersionUID = -4529495111594034434L; private Logger logger = Logger.getLogger(getClass()); protected Gson gson = new GsonBuilder() .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter()) .registerTypeAdapter(int.class, new IntegerDefaultAdapter()).create(); public BaseServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { String action = ServletHelper.getPathAction(request); ServletHelper.invokeMethod(action, this, request, response); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex.toString()); throw new ServletException(ex.toString()); } } protected PageInfo getPageInfo(HttpServletRequest request) { Integer pageCount = DataConvertHelper.toInteger(request.getParameter("pageCount")); Integer pageSize = DataConvertHelper.toInteger(request.getParameter("pageSize")); PageInfo pageInfo = new PageInfo(); if (pageCount != null) { pageInfo.setPageCount(pageCount.intValue()); } if (pageSize != null) { pageInfo.setPageSize(pageSize.intValue()); } return pageInfo; } protected void responseResultSet(HttpServletRequest request, HttpServletResponse response, PageResultSet> resultSet) { Mapmap = new HashMap (); map.put("rows", resultSet.getList()); map.put("total", resultSet.getTotal()); responseObjectJSON(response, map); } protected void responseReslut(HttpServletResponse response, int record) { if (record > 0) { responseSuccess(response, "Success"); } else { responseError(response, new Exception("No record has been execute")); } } protected void responseSuccess(HttpServletResponse response, String message) { responseResultJSON(response, "Success", message); } protected void responseError(HttpServletResponse response, Exception exception) { try { throw exception; } catch (Exception ex) { ex.printStackTrace(); logger.error(ex.toString()); responseResultJSON(response, "Error", ex.toString()); } } private void responseResultJSON(HttpServletResponse response, String result, String message) { Map map = new HashMap (); map.put("result", result); map.put("message", message); responseObjectJSON(response, map); } protected void responseList(HttpServletRequest request, HttpServletResponse response, List> list) { PageInfo pageInfo = getPageInfo(request); int total = list.size(); if (pageInfo.getPageSize() != 0) { int beginIndex = pageInfo.getPageCount() == 0 ? 0 : (pageInfo.getPageCount() - 1) * pageInfo.getPageSize(); int endIndex = beginIndex + pageInfo.getPageSize(); endIndex = endIndex > total ? total : endIndex; list = list.subList(beginIndex, endIndex); } Map map = new HashMap (); map.put("rows", list); map.put("total", total); responseObjectJSON(response, map); } protected void responseObjectJSON(HttpServletResponse response, Object obj) { try { response.getWriter().write(gson.toJson(obj)); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex.toString()); responseError(response, ex); } } }
ServletHelper
import java.lang.reflect.Method; import java.lang.reflect.Modifier; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletHelper { public static String getPathAction(HttpServletRequest request) { String requestURI = request.getRequestURI(); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); String path = requestURI.replaceAll(contextPath, "").replaceAll(servletPath, ""); // array length must bigger than 1 // sample path="/test/" String action = ""; String[] paths = path.split("/"); if (paths.length > 1) { action = paths[1]; } return action; } public static void invokeMethod(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws Exception { String methodName = ServletHelper.getPathAction(request); ServletHelper.invokeMethod(methodName, servlet, request, response); } public static void invokeMethod(String methodName, HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws Exception { Class> cls = servlet.getClass(); Method[] methods = cls.getMethods(); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers()) && method.getName().toLowerCase().equals(methodName.toLowerCase())) { method.invoke(servlet, request, response); break; } } } }
IntegerDefaultAdapter
package ***.utils.gson; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; public class IntegerDefaultAdapter implements JsonDeserializer{ @Override public Integer deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json.getAsString().equals("") || json.getAsString().equals("null")) { return 0; } try { return json.getAsInt(); } catch (NumberFormatException ex) { ex.printStackTrace(); throw ex; } } }
DataConverHelper
import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; public class DataConvertHelper { public static boolean toBoolean(Object object) { if (isNullOrEmpty(object)) { return false; } else { Class> cls = object.getClass(); if (cls.equals(String.class)) { return Boolean.parseBoolean((String) object); } else if (cls.equals(byte.class) || cls.equals(short.class) || cls.equals(int.class) || cls.equals(long.class) || cls.equals(float.class) || cls.equals(double.class)) { return ((int) object > 0); } else { return (boolean) object; } } } public static BigDecimal toBigDecimal(Object object) { if (isNullOrEmpty(object)) { return null; } else { try { return new BigDecimal(object.toString()); } catch (Exception ex) { ex.printStackTrace(); return null; } } } public static byte toByte(Object object) { return (byte) toLong(object); } public static short toShort(Object object) { return (short) toLong(object); } public static int toInt(Object object) { return (int) toLong(object); } public static long toLong(Object object) { BigDecimal decimal = toBigDecimal(object); return decimal == null ? 0 : decimal.longValue(); } public static float toFloat(Object object) { return (float) toDouble(object); } public static double toDouble(Object object) { BigDecimal decimal = toBigDecimal(object); return decimal == null ? 0 : decimal.doubleValue(); } public static Integer toInteger(Object object) { BigDecimal decimal = toBigDecimal(object); return decimal == null ? null : new Integer(decimal.intValue()); } public static String toString(Object object) { return (object == null) ? "" : object.toString(); } public static String formatDateByDate(Date date) { return formatDate(date, "dd/MM/yyyy"); } public static String formatDateByTime(Date date) { return formatDate(date, "HH:mm:ss"); } public static String formatDate(Date date) { return formatDate(date, "dd/MM/yyyy HH:mm:ss"); } public static String formatDate(Date date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(date); } public static boolean isNullOrEmpty(Object string) { return string == null ? true : isNullOrEmpty(string.toString()); } public static boolean isNullOrEmpty(String string) { return string == null ? true : (string.equals("") ? true : false); } public static boolean isNotNullOrEmpty(Object string) { return !isNullOrEmpty(string); } public static boolean isNotNullOrEmpty(String string) { return !isNullOrEmpty(string); } public staticboolean isCollectionEmpty(Collection col){ return (col == null || col.isEmpty()); } public static boolean isCollectionNotEmpty(Collection col){ return !isCollectionEmpty(col); } public static Date parseDateByString(String text, String format) throws ParseException{ SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.parse(text); } public static Date parseDateByString(String text) throws ParseException{ return parseDateByString(text, "dd/MM/yyyy HH:mm:ss"); } }
另外,需要自己行添加log4j,gson包。