简要说明一下程序架构:
后台:先上图
第一篇文章中提到过,使用的Guice,那么跳转怎么弄得呢,自己借鉴写的,哈哈,核心跳转类ActionController,继承了HttpServlet,用于完成请求的处理和跳转,贴部分代码
package com.ginger.framework.dispatcher;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ginger.auth.util.WebConstants;
import com.ginger.framework.action.Action;
import com.ginger.framework.exception.FrameworkException;
import com.ginger.framework.exception.RequestParameterException;
import com.ginger.framework.main.GuiceServlet;
import com.ginger.framework.util.JsonUtil;
import com.google.inject.Injector;
/**
* Action控制器类
*/
public class ActionController extends HttpServlet {
private static final long serialVersionUID = -7320695308722530659L;
// Action前缀
private String actionPath = "";
// 过滤的url
private String url_login = "";
private String url_logout = "";
// logger对象
protected Log logger = LogFactory.getLog(ActionController.class);
public void init() throws ServletException {
super.init();
// 获取Action路径
actionPath = getServletContext().getInitParameter("path_of_action");
if (null != actionPath && !actionPath.endsWith(".")) {
actionPath += ".";
}
url_login = getServletContext().getInitParameter("url_login");
url_logout = getServletContext().getInitParameter("url_logout");
logger.info("Action path: " + actionPath);
logger.info("过滤url: " + url_login + "; " + url_logout);
}
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
doCommand(arg0, arg1);
}
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
doCommand(arg0, arg1);
}
/**
* 处理HTTP请求
*
* @param req
* HttpServletRequest , Request
* @param res
* HttpServletResponse , Response
* @throws ServletException
* @throws IOException
*/
protected void doCommand(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Injector injector = GuiceServlet.getInjector();
String username = "test";
try {
try {
res.setCharacterEncoding("UTF-8");
// 获取obj对象
String obj = req.getParameter("obj");
// 把所要请求的Action打印到日志中
// 把当前用户名,请求Action的时间以及请求的Action的名字打印到日志中
logger.info("[" + username + "] Session ID :[" + req.getRequestedSessionId() + "]");
logger.info("[" + username + "] Remote Host :[" + req.getRemoteAddr() + "]");
logger.info("[" + username + "] User-Agent :[" + req.getHeader("User-Agent") + "]");
logger.info("[" + username + "] execute Action is :[" + obj + "] Start");
String operType = req.getParameter("operType");
String url = obj + "_" + operType;
//sesson超时
/*if (!url_login.equals(url) && !url_logout.equals(url)) {
this.preHandle(req, res);
}*/
if (url_login.equals(url) || url_logout.equals(url)) {
//this.preHandle(req, res);
} else {
//this.sessionValidate(req, res);
}
if (obj == null || obj.equals("")) {
throw new RequestParameterException("");
}
// 获取提交方式,可以为ajax或common,默认为ajax
String method = req.getParameter("method");
if (method == null) {
method = "ajax";
}
// 获取动作,可以是validate或execute,默认是execute
String todo = req.getParameter("todo");
if (todo == null) {
todo = "execute";
}
// 设置上下文环境
ActionContext ac = ActionContext.getContext();
ac.setServletContext(this.getServletContext());
ac.setSession(req.getSession());
ac.setRequest(req);
ac.setResponse(res);
ac.setParameter(req.getParameterMap());
ac.setLocale(req.getLocale());
String classname = actionPath + obj;
// 通过反射,获取class类
Class c = Thread.currentThread().getContextClassLoader().loadClass(classname);
// 执行Action动作
Object executeResult;
if ("execute".equalsIgnoreCase(todo)) {
try {
Action proxyAction = (Action) injector.getInstance(c);
executeResult = proxyAction.execute();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
if ("ajax".equalsIgnoreCase(method)) {
PrintWriter out = res.getWriter();
if (executeResult instanceof String) {
out.write(executeResult.toString());
} else {
out.write(JsonUtil.toJson(executeResult));
}
out.close();
} else if ("common".equalsIgnoreCase(method)) {
return;
}
}
logger.info("[" + username + "] execute Action is :[" + obj + "] End");
} catch (RequestParameterException e) {
logger.error(e.getMessage(), e);
throw new FrameworkException("");
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(), e);
throw new FrameworkException("");
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new FrameworkException("");
}
} catch (FrameworkException e) {
logger.error(e.getMessage(), e);
showError(req, res);
}
}
/**
* 处理错误信息
*
* @param req
* HttpServletRequest , Request对象
* @param res
* HttpServletResponse , Response对象
* @throws ServletException
* @throws IOException
*/
protected void showError(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String page = "page.error";
getServletContext().getRequestDispatcher(page).forward(req, res);
}
/**
* 验证用户登陆拦截器
*
* @author
* @date 2011-3-13 下午09:02:00
*/
public void sessionValidate(HttpServletRequest request, HttpServletResponse response) {
// 如果session中没有user对象
if (null == request.getSession().getAttribute(WebConstants.CURRENT_USER)) {
String requestedWith = request.getHeader("x-requested-with");
// ajax请求
if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
response.setHeader("session-status", "timeout");
try {
response.getWriter().print(WebConstants.TIME_OUT);
return;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
该Servlet类实现了前台请求类的实例化,当然对应的Action类要实现对应的接口才行,Action接口类很简单
package com.ginger.framework.action;
import java.util.List;
/**
* Action接口,用户动作的抽象
*
*/
public interface Action {
/**
* Action的执行方法,执行具体的业务逻辑
*
* @return Object
* @throws Exception
*/
public Object execute() throws Exception;
/**
* Action的校验方法,校验用户的输入是否正确֤
*
* @return List , 错误信息
* @throws Exception
*/
public List validate() throws Exception;
}
对应Action实现类
package com.ginger.auth.action.authority;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ginger.auth.obj.authority.BaseRoles;
import com.ginger.auth.obj.common.Criteria;
import com.ginger.auth.obj.common.ExceptionReturn;
import com.ginger.auth.obj.common.ExtGridReturn;
import com.ginger.auth.obj.common.ExtPager;
import com.ginger.auth.obj.common.ExtReturn;
import com.ginger.auth.service.authority.BaseRolesService;
import com.ginger.framework.action.Action;
import com.ginger.framework.dispatcher.ActionContext;
/**
* 角色
*
*/
public class RoleAction implements Action {
private static final Log logger = LogFactory.getLog(RoleAction.class);
HttpServletRequest request = ActionContext.getContext().getRequest();
@Inject
private BaseRolesService baseRolesService;
public Object execute() throws Exception {
String operType = request.getParameter("operType");
if ("all".equals(operType)) {
return this.all();
}
if ("save".equals(operType)) {
return this.save();
}
if ("del".equals(operType)) {
return this.delete();
}
return new ExtReturn(false, "找不到方法!");
}
public List validate() throws Exception {
// TODO Auto-generated method stub
return null;
}
/**
* 查找所有的角色
*/
public Object all() {
String roleName = request.getParameter("roleName");
ExtPager pager = new ExtPager();
Criteria criteria = new Criteria();
// 设置分页信息
if (pager.getLimit() != null && pager.getStart() != null) {
criteria.setOracleEnd(pager.getLimit() + pager.getStart());
criteria.setOracleStart(pager.getStart());
}
// 排序信息
if (StringUtils.isNotBlank(pager.getDir()) && StringUtils.isNotBlank(pager.getSort())) {
criteria.setOrderByClause(pager.getSort() + " " + pager.getDir());
}
if (StringUtils.isNotBlank(roleName)) {
criteria.put("roleNameLike", roleName);
}
List<BaseRoles> list = this.baseRolesService.selectByExample(criteria);
int total = this.baseRolesService.countByExample(criteria);
logger.debug("total:{}" + total);
return new ExtGridReturn(total, list);
}
/**
* 保存角色信息
*/
public Object save() {
try {
BaseRoles role = new BaseRoles();
String roleId = request.getParameter("roleId");
role.setRoleId(roleId);
String roleName = request.getParameter("roleName");
role.setRoleName(roleName);
String roleDesc = request.getParameter("roleDesc");
role.setRoleDesc(roleDesc);
if (StringUtils.isBlank(role.getRoleName())) {
return new ExtReturn(false, "角色名称不能为空!");
}
String result = this.baseRolesService.saveRole(role);
if ("01".equals(result)) {
return new ExtReturn(true, "保存成功!");
} else if ("00".equals(result)) {
return new ExtReturn(false, "保存失败!");
} else {
return new ExtReturn(false, result);
}
} catch (Exception e) {
logger.error("Exception: ", e);
return new ExceptionReturn(e);
}
}
/**
* 删除该角色
*/
public Object delete() {
try {
String roleId = request.getParameter("roleId");
if (StringUtils.isBlank(roleId)) {
return new ExtReturn(false, "角色主键不能为空!");
}
Criteria criteria = new Criteria();
criteria.put("roleId", roleId);
String result = this.baseRolesService.deleteByPrimaryKey(criteria);
if ("01".equals(result)) {
return new ExtReturn(true, "删除成功!");
} else if ("00".equals(result)) {
return new ExtReturn(false, "删除失败!");
} else {
return new ExtReturn(false, result);
}
} catch (Exception e) {
logger.error("Exception: ", e);
return new ExceptionReturn(e);
}
}
}
代替了Struts2,变得简答,灵活,自己想怎么搞都行。
Dao层使用了MyBatis,配合Guice,完美的实现了依赖注入和注解事务管理,一切变得如此简单,先到这。