小蜜锋 - 云代码空间
—— 技术宅拯救世界!
package com.gym.user.action; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gym.user.service.impl.MatchServiceImpl; public class IndexAction extends HttpServlet { /** * The doGet method of the servlet. <br> * * 访问根目录默认跳转到index.jsp * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MatchServiceImpl matchServiceImpl = new MatchServiceImpl(); List list = (List) matchServiceImpl.queryMatch(); RequestDispatcher dispatcher = request .getRequestDispatcher("index.jsp"); request.setAttribute("matchList", list); dispatcher.forward(request, response); } }控制器中的doGet一般只负责显示页面,也就是调用各个模块的jsp文件;doPost一般只负责数据的处理,以及跳转到成功或失败页面。上面代码中的matchServiceImpl.queryMatch();就是调用赛事服务组件中的查询赛事方法,把返回的list对象放到request对象中,供jsp模板遍历输出,遍历代码如下:
<c:forEach items="${requestScope.matchList}" var="list"> <li> <span class="title"><a href="match/index.html?mid=${list.getmId() }">${list.getmName()} </a> </span> <span class="time">${list.getmDate()}</span> </li> </c:forEach>以上的控制器只是负责显示主页,但其他模块的控制器需要执行不同的操作,比如用户控制器,需要执行显示用户信息页面,显示修改密码页面,修改密码,修改个人信息等动作,这就需要一个标记来判断需要执行哪一个动作了。用String action = request.getParameter("action");获取用户需要执行的动作,然后判断if(action.equals("xxx")) { },分别写对应执行的代码即可。由于java1.6以及之前的版本都不支持switch中使用String来匹配,所以用了比较笨的办法,一个个判断,例如用户控制器:
package com.gym.user.action; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gym.model.UserModel; import com.gym.user.service.impl.UserServiceImpl; import com.gym.utils.CheckOnline; import com.gym.utils.Constant; import com.gym.utils.Md5; public class UserAction extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String action = request.getParameter("action"); // 检查用户是否在线 if (!CheckOnline.isUserOnline(request)) { response.sendRedirect("../login.html"); return; } String userId = request.getSession().getAttribute("uId").toString(); UserServiceImpl userServiceImpl = new UserServiceImpl(); if (action == null) { // 显示个人中心首页 UserModel userModel = userServiceImpl.queryUserInfoById(userId); List userList = new ArrayList(); userList.add(userModel); RequestDispatcher dispatcher = request .getRequestDispatcher("/usercenter/index.jsp"); request.setAttribute("userList", userList); dispatcher.forward(request, response); } else if (action.equals("alterinfo")) { // 显示修改个人信息页面 UserModel userModel = userServiceImpl.queryUserInfoById(userId); List userList = new ArrayList(); userList.add(userModel); RequestDispatcher dispatcher = request .getRequestDispatcher("/usercenter/alterinfo.jsp"); request.setAttribute("userList", userList); dispatcher.forward(request, response); } else if (action.equals("resetpwd")) { // 显示修改密码页面 RequestDispatcher dispatcher = request .getRequestDispatcher("/usercenter/resetpwd.jsp"); dispatcher.forward(request, response); } else if (action.equals("mybook")) { UserModel userModel = new UserModel(); userModel.setuId((String) request.getSession().getAttribute("uId")); List myGroundBookList = userServiceImpl.queryMyBook(userModel); RequestDispatcher dispatcher = request .getRequestDispatcher("/usercenter/mybook.jsp"); request.setAttribute("myGroundBookList", myGroundBookList); dispatcher.forward(request, response); } else if (action.equals("myrent")) { UserModel userModel = new UserModel(); userModel.setuId((String) request.getSession().getAttribute("uId")); List myEquipmentRentList = userServiceImpl.queryMyRent(userModel); RequestDispatcher dispatcher = request .getRequestDispatcher("/usercenter/myrent.jsp"); request.setAttribute("myEquipmentRentList", myEquipmentRentList); dispatcher.forward(request, response); } else { RequestDispatcher dispatcher = request .getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String action = request.getParameter("action"); // 检查用户是否在线 if (!CheckOnline.isUserOnline(request)) { response.sendRedirect("../login.html"); return; } String userId = request.getSession().getAttribute("uId").toString(); UserServiceImpl userServiceImpl = new UserServiceImpl(); UserModel userModel = new UserModel(); if (action == null) { } else if (action.equals("alter")) { // 执行修改个人信息动作 userModel.setuId(userId); userModel.setuEmail(request.getParameter("email")); userModel.setuIdCard(request.getParameter("idcard")); userModel.setuPhone(request.getParameter("phone")); userModel.setuName(request.getParameter("name")); switch (userServiceImpl.alterUserInfo(userModel)) { case Constant.SUCCESS: request.getSession() .setAttribute("uName", userModel.getuName()); // 更新session response.sendRedirect("../success.jsp"); break; case Constant.ERROR: response.sendRedirect("../error.jsp?errorCode=" + Constant.ERROR); break; default: break; } } else if (action.equals("resetpwd")) { // 执行修改密码动作 userModel.setuId(userId); String oldPwd = request.getParameter("oldpwd"); String newPwd1 = request.getParameter("newpwd1"); String newPwd2 = request.getParameter("newpwd2"); switch (userServiceImpl.alterUserPwd(userModel, oldPwd, newPwd1, newPwd2)) { case Constant.SUCCESS: request.getSession() .setAttribute("uName", userModel.getuName()); // 更新session request.getSession().setAttribute("uId", userModel.getuId()); // 更新session response.sendRedirect("../success.jsp"); break; case Constant.ERROR: response.sendRedirect("../error.jsp?errorCode=" + Constant.ERROR); break; case Constant.USERPWDERROR: response.sendRedirect("../error.jsp?errorCode=" + Constant.USERPWDERROR); break; case Constant.PASSWORDDIFFER: response.sendRedirect("../error.jsp?errorCode=" + Constant.PASSWORDDIFFER); break; default: break; } } } }除此之外还要查询是否用户在线,如果在线,前端需要显示当前用户名;如果不在线,则显示注册 / 登录,另外如果不在线点击个人中心将会自动跳转到登录页面。检测是否在线的代码封装到一个工具类中,代码如下:
package com.gym.utils; import javax.servlet.http.HttpServletRequest; /** * 检查是否在线 * * @author Feng * */ public class CheckOnline { public static boolean isAdminOnline(HttpServletRequest request) { Object aIdSession = request.getSession().getAttribute("aId"); if (aIdSession == null) { return false; } else { return true; } } public static boolean isUserOnline(HttpServletRequest request) { Object uIdSession = request.getSession().getAttribute("uId"); if (uIdSession == null) { return false; } else { return true; } } }检查是否在线的方法:
// 检查用户是否在线 if (!CheckOnline.isUserOnline(request)) { response.sendRedirect("../login.html");// 不在线,跳转到登录页面 return; }控制器中每一个操作都会返回不同的状态,比如成功,失败,用户名错误,密码错误,用户名不存在......为了方便管理,这些状态码都统一封装在一个常量类中。状态码用int类型,方便控制器用switch来分发,状态标志为全大写的常量名。常量工具类代码如下:
package com.gym.utils; /** * 常量类 * * @author Feng * */ public class Constant { public static final int SUCCESS = 1000; // 操作成功 public static final int ERROR = 1001; // 未知错误 public static final int NOTONLINE = 1002; // 未登录 public static final int PASSWORDDIFFER = 1003; // 两次输入密码不一致 public static final int PERMISSIONDENIED = 1004; // 权限不足 public static final int USEREXIST = 1010; // 用户存在 public static final int USERNOTEXIST = 1011; // 用户不存在 public static final int USERPWDERROR = 1012; // 用户密码错误 public static final int ADMINEXIST = 1020; // 管理员存在 public static final int ADMINNOTEXIST = 1021; // 管理员不存在 public static final int ADMINPWDERROR = 1022; // 管理员密码错误 public static final int PARAMEMPTY = 1030; // 必填参数为空错误 public static final int TIMEERROR = 1031; // 日期时间错误 public static final int TIMECLASH = 1032; // 预定或租借时间冲突 public static final int GROUNDINVALID = 1040; // 场地无效 public static final int EQUIPMENTINVALID = 1041; // 器材无效 public static final int HASNOTBOOK = 1050; // 您没有预定此场地 public static final int HASNOTRENT = 1051; // 您没有租借此器材 public static final int NOTBOOKSTATUS = 1060; // 非预定状态 public static final int NOTUSESTATUS = 1061; // 非使用状态 }操作成功一般只显示“操作成功!”,而操作错误则会把错误代码通过url形式发送给jsp模版,response.sendRedirect("../error.jsp?errorCode=" + Constant.ERROR); error.jsp中可以根据不同的错误代码显示不同的错误消息,调用方法如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <%@ page language="java" import="java.util.HashMap" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; HashMap msgParam = new HashMap(); msgParam.put("1000", "操作成功"); msgParam.put("1001", "未知错误"); msgParam.put("1002", "未登录"); msgParam.put("1003", "两次输入密码不一致"); msgParam.put("1004", "权限不足"); msgParam.put("1010", "用户存在"); msgParam.put("1011", "用户不存在"); msgParam.put("1012", "用户密码错误"); msgParam.put("1020", "管理员存在"); msgParam.put("1021", "管理员不存在"); msgParam.put("1022", "管理员密码错误"); msgParam.put("1030", "必填参数为空"); msgParam.put("1031", "日期时间错误"); msgParam.put("1032", "预定或租借时间冲突"); msgParam.put("1040", "场地无效"); msgParam.put("1041", "器材无效"); msgParam.put("1050", "您没有预定此场地"); msgParam.put("1051", "您没有租借此器材"); msgParam.put("1060", "非预定状态"); msgParam.put("1061", "非使用状态"); %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>出错啦 - 广东海洋大学体育馆网上系统</title> <link href="css/nav.css" rel="stylesheet" type="text/css" /> <script src="js/nav.js" type="text/javascript"></script> <script src="js/focus.js" type="text/javascript"></script> <link href="css/common.css" rel="stylesheet" type="text/css" /> </head> <body> <%@ include file="include/header.jsp"%> <div id="main"> <div id="row_1"> <div class="error-message"> <p>错误代码:<%=request.getParameter("errorCode")%> </p> <p>错误原因: <% out.print(msgParam.get(request.getParameter("errorCode")));%> </p> </div> </div> </div> <script> var def = "0"; </script> <%@ include file="include/footer.jsp"%> </body> </html>效果如图所示: