用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

小蜜锋    -  云代码空间

—— 技术宅拯救世界!

广东海洋大学体育馆管理系统 开发日记(11)——控制器(Action)

2013-01-30|3464阅||

摘要:控制器(Action)实质上是一个Servlet,负责接收前台上传的数据,以及根据不同的动作请求分发到不同的服务组件。

        因为本项目有用户前台和管理员后台,所以控制器分别放在两个包里,方便管理。用户前台的控制器对应com.gym.user.action,管理员后台的控制器对应com.gym.admin.action。
        
IndexAction.java
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来匹配,所以用了比较笨的办法,一个个判断,例如用户控制器:

UserAction.java
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;
			}

		}

	}
}
         除此之外还要查询是否用户在线,如果在线,前端需要显示当前用户名;如果不在线,则显示注册 / 登录,另外如果不在线点击个人中心将会自动跳转到登录页面。检测是否在线的代码封装到一个工具类中,代码如下:
CheckOnline.java
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来分发,状态标志为全大写的常量名。常量工具类代码如下:

Constant.java
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中可以根据不同的错误代码显示不同的错误消息,调用方法如下:

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>
效果如图所示:



        其他的控制器也是类似,不一一列举了,源码将在最后一篇文章里上传。


        


顶 10踩 2收藏
文章评论
    发表评论

    个人资料

    • 昵称: 小蜜锋
    • 等级: 高级设计师
    • 积分: 7088
    • 代码: 757 个
    • 文章: 360 篇
    • 随想: 211 条
    • 访问: 1263 次
    • 关注

    标签

    设计模式(4)java(9)命名规范(2)广告创意(1)愤怒的小鸟(1)游戏(5)jsp(1)配置(1)Surface(1)windows(1)javabean(1)设计方法(1)开发工具(2)web(4)大数据(2)GPU(1)硬盘(1)内部结构(1)黑客(1)窃取(1)编码(1)解决方法(1)php(28)mysql(9)数据库备份(1)数据库还原(1)命令(2)数据库(1)安装(1)2012(2)世界末日(3)仙剑5前传(1)默哀(1)电源(1)女生(1)装饰器模式(2)古剑奇谭(1)电脑桌(1)史上最牛(1)编程语言(2)小米(3)电视机顶盒(1)营销策略(1)Android(8)手势(1)诺亚方舟(1)Eclipse(1)汽车(1)操作系统(1)软件(1)互联网(5)大事记(1)设计师(2)壁纸(1)古剑奇谭2(1)古剑奇谭网络版(1)云计算(2)服务器(1)框架(2)Socket(1)jquery(1)构造函数执行顺序(1)火车票(1)3D(1)数据中心(2)正则表达式(2)Web前端(1)开发框架(1)系统瘫痪(1)12306(2)cpu(1)javascript(2)开发日记(15)体育馆管理系统(15)网页设计(1)CSS3(3)腾讯(3)小游戏(1)interface(1)平板(2)面试(2)设计(5)摄影(2)数据挖掘(1)钢琴谱(1)情人节(1)陈欧体(1)程序员(3)漫画(1)UserAgent(1)iPhone(2)NoSQL(1)ui(9)越狱(1)指南(1)abstract(1)css(3)git(2)八核(2)三星(1)linux(11)数据类型(1)html5(2)UML(2)perftools(1)创意(1)logo(1)色谱(1)响应式(5)Metro(2)虚拟机(1)jvm(1)垃圾回收(1)left(1)join(1)连接查询(1)溯源系统(1)Override(1)SAE(2)WordPress(1)指针(1)链表(1)系统分析师(1)中间件(1)corba(1)static(1)无线(1)监控(1)iPad(1)Apache(2)比特币(2)命名规则(1)手机支付(1)curl(3)笔记(1)导航(1)thinkphp(1)异常导致本地路径泄漏(1)web设计(1)网络安全(1)诗句(1)4K对齐(1)代码库(1)色彩(1)动画片(1)struts2(3)漏洞(5)确认框(1)心情驿站(1)ArscEditor(1)resources.(1)apktool(1)AppKey(1)新浪微博(1)app(5)广告(3)赚钱(1)响应式布局(1)html(1)淘宝(2)微信(1)重构(5)缓存(1)破解(1)后门(1)七夕(1)SEO(2)概念设计(1)面向对象(1)bootstrap(1)性能(2)优化(1)iis(1)爬虫(1)采集(1)算法(2)文本相似度(2)cto(1)js(1)fsockopen(1)扁平化设计(2)网页(1)心情(7)小米电视(1)开箱(1)励志(2)招聘(3)命名(1)notepad++(1)python(1)配色(3)扁平化(4)ps(2)搞笑(2)创业(3)渲染(1)电影(1)模板(1)微博(1)企业家(1)公司(1)总结(1)前端(1)运营(1)变形(1)svn(4)教程(3)搜狗(1)泄密(1)双11(1)天猫(1)UC(1)启动界面(1)光棍节(1)双十一(2)物流(1)备份(1)更新(1)插入(1)插件(2)jsTree(1)(1)海量数据(1)分辨率(1)草图(1)手绘(1)速度(1)文本处理(1)实习(1)感想(1)文件(1)简历(1)65.49.2.17(1)yum(1)解决办法(1)阿里云(2)推广(1)来往(1)春运(1)LBS(1)gb2312(1)utf-8(1)log4j(1)详解(1)收购(1)私服(1)TortoiseGi(1)post(1)异常(2)flappyBird(1)应用创新大赛(1)宙斯杯(1)学习方法(1)xp(1)退役(1)安全(1)技术贴(1)flash(1)刷机(1)京东(1)电商(1)Tomcat(1)JDK(1)免费(1)长投影(1)图标(1)Photoshop(1)云端集成开发环境(1)软件开发(1)可视化(1)工具(2)OpenSSL(1)Heartbleed(1)vsftp(1)中国知网(1)学术论文(1)免费下载(1)开发(1)手册(1)速查表(1)追随战略(1)sdk(1)文章(1)发布(1)文件管理(1)沙画(1)动效(2)原型(1)感悟人生(1)哲理(1)Bash(1)类图(1)知识管理(1)Console(1)调试命令(1)rpm(1)报错(1)挂载(1)数据盘(1)云主机(1)产品经理(1)原型设计(1)mql4(1)mt4(1)ea(1)程序化交易(1)CURLOPT_PO(1)阿里云​(1)CentOS6(2)OpenSSH(1)漏洞修复(2)升级(1)安骑士(1)链克(1)

    站长推荐