本实例大致流程:基于jsp页面,通过servlet传递数据调用方法,利用service更改数据库.
本文重点分析的是其中的两个小方法add()和delete(),来反映出反射机制的一个具体作用:减少Servlet文件的个数.
利用反射减少Servlet文件个数的步骤:
1 必须对每次请求进行标示,表示这个动作是什么
2 对每个标示进行判断,然后在同一个Servlet调用与标示对应的方法
第一种方法是一个Servlet文件对应一个动作
第二种利用反射机制的方法是把每个动作写成一个方法,而不是一个单独Servlet,然后把这些方法统一封装到一个Servlet中,然后根据动作调用相应的方法,对数据进行增,删,改,查,验证等
3 注意,第一种方法中Servlet的名字要统一改成第二种方法中统一了的Servlet的名字
添加用户的界面:
用户列表界面:
用户信息修改界面:
步骤一:.jsp文件中代码调用方法
<td>
<a href=‘admin/UserServlet?action=modify&id=<%=user.getId()%>‘>修改</a>
<a href=‘admin/UserServlet?action=delete&id=<%=user.getId() %>‘>删除</a>
</td>
步骤二:Servlet获取数据
第一种Servlet方式:
protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("list".equals(action)) {
list(request, response);
} else if ("add".equals(action)) {
add(request, response);
} else if ("modify".equals(action)) {
modify(request, response);
} else if ("modified".equals(action)) {
modified(request, response);
} else if ("validate".equals(action)) {
validate(request, response);
} else if ("delete".equals(action)) {
delete(request, response);
}
public void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {...}
...
...
}
第二种Servlet方式:利用反射机制
反射机制(继承给子类):
//问题:没有办法调用子类中的方法,但是在程序运行以后,都会有对象,就可以通过反射,调用对象中的方法
public class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service (HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
String action = request.getParameter("action");
Class clazz = this.getClass();
// 在运行的时候,通过java.lang.Class对应本类的对象
Class[] types = {
HttpServletRequest.class,HttpServletResponse.class
}; //都是对应类的Class的对象
Object[] objs = {request,response};
try {
Method method = clazz.getMethod(action, types);
method.invoke(this, objs);
//this:代表当前的对象,objs是上面Service传递过来的参数,需要传递到子类中那些方法中
//Method method = clazz.getDeclaredMethod(action, types); //不支持继承,上面之所以可以用this是因为支持继承
//this就是代表了当时的那个子类对象
} catch (Exception e) {
e.printStackTrace();
}
}
子类代码:
public class UserServlet extends BaseServlet {
public static final long serialVersionUID = 1L;
public UserServlet() {
super();
}
public void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获得客户端提交的数据
String name = request.getParameter("name");
String password = request.getParameter("password");
String valid = request.getParameter("valid");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
//把数据用User对象封装
User user = new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setPhone(phone);
user.setTime_stamp(new Timestamp(new Date().getTime()));
//调用UserSerce类中方法,将用户对象传入到UserService类中
UserService userService = UserService.getInstance();
userService.addUser(user);
this.getServletContext().getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
}
public void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
String id = request.getParameter("id");
UserService userService = UserService.getInstance();
userService.delete(Integer.parseInt(id));
this.getServletContext().getRequestDispatcher("/admin/user_list.jsp")
.forward(request, response);
}
...
...
}
步骤三:通过Service更改数据库
使用单例模式:双检查模式
private UserService() {
}
public static UserService getInstance() {
if (userService == null) {
synchronized (UserService.class) {
if (userService == null) {
userService = new UserService();
}
}
}
return userService;
}
public void addUser(User user) {
Connection conn = DB.getConnection();
PreparedStatement pstmt = null;
String sql = "insert into cms_user(name,password,valid,email,phone,time_stamp) values (?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setString(2, user.getPassword());
pstmt.setInt(3, user.getValid());
pstmt.setString(4, user.getEmail());
pstmt.setString(5, user.getPhone());
pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));
// pstmt.setTimestamp(6, new
// Timestamp(user.getTime_stamp().getTime()));
// 执行语句到数据库
pstmt.executeUpdate();
DB.commit(conn);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(pstmt);
try {
if (conn != null) {
conn.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public void delete(int id) {
String sql = "delete from cms_user where id=?";
Connection conn = DB.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
DB.close(pstmt);
DB.commit(conn);
DB.close(conn);
}
...
...
}
项目中要用到的工具类部分代码:
/**
* DB.java 是一个JDBC链接类
* @version 0.1 目的是进行数据库链接测试,先在mian()方法里面进行测试,然后在写入方法
* @version 0.2 完善整个DB类,把所有常见的DB操作全部完成
*/
public class DB {
//最原始的测试方式
public static void main(String[] args) {
Connection conn = DB.getConnection();
System.out.println(conn);
}
/**
* get connection
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "c##cms", "cms");
conn.setAutoCommit(false);//打开了事务机制
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(PreparedStatement pstmt) {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* close db connection
* @param conn
*/
public static void close(Connection conn) {
try {
if (conn != null) {
conn.close();
}
// DBConnectionPool.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* close resultSet
* @param rs
*/
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 失败以后回滚的方法
* @param conn
*/
public static void rollback(Connection conn) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
/**
* 手动提交的方法
* @param conn
*/
public static void commit(Connection conn) {
if (conn != null) {
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//分页
public class PageList {
// 1 每页显示的条数: pageSize
private int pageSize = Constant.PAGESIZE;
// 2总共有多少条记录: rowCount;
private int rowCount;
// 3当前页码数:pageNum;
private int pageNum;
// 4总页码数:pageCount;
private int pageCount;
// 5保存具体数据的集合
private List list;
public PageList() {
super();
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
@Override
public String toString() {
return "PageList [pageSize=" + pageSize + ", rowCount=" + rowCount
+ ", pageNum=" + pageNum + ", pageCount=" + pageCount + "]";
}
}
项目中要用到的.jsp文件部分代码:
<!--用户添加-->
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<title>用户添加</title>
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/validator/component.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/navbar/nav.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/table/skin.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/time/skin.css" />
<script type="text/javascript" src="jscript/time/calendar.js"></script>
<script type="text/javascript" src="jscript/time/calendar-zh.js"></script>
<script type="text/javascript" src="jscript/time/calendar-setup.js"></script>
<script type="text/javascript" src="jscript/common.js"></script>
<script type="text/javascript" src="jscript/validator/form_validator.js" /></script>
<style type="text/css">
body, table, td, select, textarea, input {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
<div id="main">
<form name="backuserform" method="post" action="admin/UserAddServlet"
onSubmit=‘return submitForm(document.forms[0]);‘>
<table class="standard">
<thead>
<tr>
<th align="center" colspan="2">用户添加</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">用户名</td>
<td align="left"><input name="name" type="text" TABINDEX="1"
id="name" />
<div class="Info">
<div id="name_info"></div>
</div></td>
</tr>
<tr>
<td align="left">用户密码</td>
<td align="left"><input name="password" type="password"
value="" TABINDEX="2" id="password" />
<div class="Info">
<div id="password_info"></div>
</div></td>
</tr>
<tr>
<td align="left">角色</td>
<td align="left"><select name="role" TABINDEX="4" id="role">
<option value="1">超级管理员</option>
</select>
<div class="Info">
<div id="role_info"></div>
</div></td>
</tr>
<tr>
<td align="left">是否有效</td>
<td align="left"><select name="valid" TABINDEX="3" id="valid">
<option value="1">有效</option>
<option value="0">无效</option>
</select>
<div class="Info">
<div id="valid_info"></div>
</div></td>
</tr>
<tr>
<td align="left">EMAIL</td>
<td align="left"><input name="email" type="text" value=""
TABINDEX="5" id="email" />
<div class="Info">
<div id="email_info"></div>
</div></td>
</tr>
<tr>
<td align="left">电话</td>
<td align="left"><input name="phone" type="text" value=""
TABINDEX="6" id="phone" />
<div class="Info">
<div id="phone_info"></div>
</div></td>
</tr>
<tr>
<td colspan="2" align="center"><input class="submitButton"
type="submit" TABINDEX="7" name="submit" value="提 交">
<input type="button" name="返回" class="submitButton" value="返回"
onclick="history.back();"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" style="text-align: left"></td>
</tr>
</tfoot>
</table>
</form>
</div>
</body>
</html>
<!--用户列表-->
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<%@ page import="user.*" %>
<%@ page import="util.*" %>
<%
String path = request.getContextPath();//
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
//获得网站根目录:WebContent
%>
<html>
<head>
<base href="<%=basePath%>" />
<title>backuser</title>
<style type="text/css">
body,table,td,select,textarea,input {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
}
</style>
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/validator/component.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/navbar/nav.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/table/skin.css" />
<link rel="stylesheet" type="text/css" title="xp"
href="css/skins/xp/time/skin.css" />
<script type="text/javascript">
function turn(frm, oper, totalpage, curpage, msg) {
if (oper == ‘first‘) {
if (curpage == 1) {
return;
}
frm.pagenum.value = 1;
frm.submit();
return;
} else if (oper == ‘prev‘) {
if (curpage == 1) {
return;
}
frm.pagenum.value = (curpage - 1);
frm.submit();
return;
} else if (oper == ‘next‘) {
if (curpage >= totalpage) {
return;
}
frm.pagenum.value = (curpage + 1);
frm.submit();
return;
} else if (oper == ‘last‘) {
if (curpage >= totalpage) {
return;
}
frm.pagenum.value = totalpage;
frm.submit();
return;
} else if (oper == ‘jump‘) {
var jpage = document.getElementById("jumpto");
var jpagev = curpage;
if (jpage.value == ""
|| !(jpage.value.search(/^(-|\+)?\d+$/) != -1)) {
alert(msg);
jpage.focus();
jpage.select();
return;
} else {
jpagev = parseInt(jpage.value);
}
if (jpagev == curpage || jpagev > totalpage || jpagev <= 0) {
return;
}
frm.pagenum.value = jpagev;
frm.submit();
return;
}
}
</script>
</head>
<%
PageList pageList = (PageList)request.getAttribute("pageList");
if(pageList == null){
pageList = new PageList();
}
// List userList = (List)request.getAttribute("userList"); //获得userList对象
List userList = (List)pageList.getList();
if(userList == null){
userList = new ArrayList(); //为了不报错而已
}
%>
<body>
<div id="main">
<form name="sportform" method="post"
action="admin/UserServlet?action=list">
<table class="sadminheading" style="top-margin: 10">
<tr>
<td nowrap class="admintitle" colspan="3" align="center">
用户列表
</td>
</tr>
<tr>
<td align="left" width="10%">
用户名:
</td>
<td align="left" width="40%">
<input name="name" type="text" />
</td>
<td align="right">
<input type="submit" name="提交" value="提交"/>
<input type="hidden" name="pagenum" value="" />
<input type="hidden" name="pagerows" value="" />
</td>
</tr>
</table>
</form>
<table class="standard">
<thead>
<tr>
<th>
id
</th>
<th>
用户名
</th>
<th>
用户密码
</th>
<th>
角色
</th>
<th>
email
</th>
<th>
是否有效
</th>
<th>
电话
</th>
<th>
操作
</th>
</tr>
</thead>
<tbody>
<!-- ****遍历出每个用户信息_开始***** -->
<%
for(Iterator i = userList.iterator(); i.hasNext();){
User user = (User) i.next();
%>
<tr>
<td>
<%=user.getId() %>
</td>
<td>
<%=user.getName() %>
</td>
<td>
<%=user.getPassword() %>
</td>
<td>
--NoRole--
</td>
<td>
<%=user.getEmail() %>
</td>
<td>
<%=user.getValid() %>
</td>
<td>
<%=user.getPhone() %>
</td>
<td>
<a href=‘admin/UserServlet?action=modify&id=<%=user.getId()%>‘>修改</a>
<a href=‘admin/UserServlet?action=delete&id=<%=user.getId() %>‘>删除</a>
</td>
</tr>
<%
}
%>
<!-- ****遍历出每个用户信息_结束***** -->
<tr>
<td colspan="8">
No data found
</td>
</tr>
</tbody>
<tfoot>
<tr>
<!--
选定一个元素,监听一个事件,绑定一个函数,在函数中执行一段代码,在代码找对象改属性
-->
<td colspan="3" style="text-align: left">
<%= pageList.getPageNum() %>/<%= pageList.getPageCount()%> 总记录数 <%= pageList.getRowCount() %></td>
<td colspan="5" align="right">
<%if(pageList.getPageCount() >1){ %>
<%if(pageList.getPageNum() >1){ %>
<%if(pageList.getPageNum() < pageList.getPageCount()){ %>
<a href="#"
onclick="turn(document.forms[0],‘first‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">第一页</a>
<a href="#"
onclick="turn(document.forms[0],‘prev‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">上一页</a>
<a href="#"
onclick="turn(document.forms[0],‘next‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">下一页</a>
<a href="#"
onclick="turn(document.forms[0],‘last‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">最后一页</a>
<%}else{ %>
<a href="#"
onclick="turn(document.forms[0],‘first‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">第一页</a>
<a href="#"
onclick="turn(document.forms[0],‘prev‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">上一页</a>
<%} %>
<%}else { %>
<a href="#"
onclick="turn(document.forms[0],‘next‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">下一页</a>
<a href="#"
onclick="turn(document.forms[0],‘last‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">最后一页</a>
<%} %>
<%} %>
go <input type="text" name="cpage" size="5" id="jumpto" /> <a
href="#" onclick="turn(document.forms[0],‘jump‘,‘<%=pageList.getPageCount() %>‘,‘<%=pageList.getPageNum() %>‘,‘‘);return false;">go</a>
</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>