回顾:
form表单、Servlet、dbutils、Filter、EL表达式、JSTL标签
一、管理员登录
admin/login.jsp
<form action="/dami/user" method="post">
<input type="hidden" name="method" value="adminLogin">
<ul>
<li><span color="red">${msg}</span></li>
<li><input name="username" type="text" class="loginuser" value="" onclick="JavaScript:this.value=''"/></li>
<li><input name="password" type="password" class="loginpwd" value="" onclick="JavaScript:this.value=''"/></li>
<li><input name="" type="submit" class="loginbtn" value="登录" onclick="javascript:window.location='main.html'" /><label><input name="" type="checkbox" value="" checked="checked" />记住密码</label><label><a href="#">忘记密码?</a></label></li>
</ul>
</form>
先看WEB-INF目录下访问UserServlet是什么地址栏路径
Servlet:
//管理员登录
protected void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//2、调用业务
UserService us = new UserService();
User user = us.adminLogin(username,password);
//3、结果展示
if(user != null) {
//登录成功
response.sendRedirect("/dami/admin/main.jsp");
}else {
//登录失败 跳转到login.jsp
request.setAttribute("msg", "用户名密码错误或者不是管理员身份");
request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
}
}
Service:
public User adminLogin(String username, String password) {
return ud.adminLogin(username,password);
}
Dao:
public User adminLogin(String username, String password) {
String sql = "SELECT * FROM USER WHERE username= ? AND PASSWORD = ? AND manager = ?";
Object [] param = {username,password,1};
try {
return qr.query(sql, new BeanHandler<User>(User.class),param);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
域对象:
request:作用范围:一次请求范围内有效
session:作用范围:一次会话(多次请求)
问题:在index.jsp页面中显示 用户的问题
if(user != null) {
request.getSession().setAttribute("user", user);
//登录成功
response.sendRedirect("/dami/admin/main.jsp");
}
在index.jsp中用EL表达式取:
${user.username} 早上好,欢迎使用信息管理系统
二、 管理员退出
思考:
1、点击退出直接跳转到/admin/login.jsp
2、点击退出执行UserServlet,在UserServlet的方法中,移除session中的user信息,然后跳转到登录页面
问题:移除session中用户信息时使用下面哪种方式?
request.getSession().invalidate();//session对象销毁了
request.getSession().removeAttribute("user");//选用
代码实现:
top.jsp
<li><a href="/dami/user?method=adminLogout" target="_parent">退出</a></li>
Servlet:
//管理员退出
protected void adminLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().removeAttribute("user");
//跳转到登录页面
response.sendRedirect("/dami/admin/login.jsp");
}
三、用户列表查询
思路:和查询员工列表一样
代码实现:
left.jsp
<li class="active"><cite></cite><a href="/dami/user?method=selectUlist" target="rightFrame">用户管理</a><i></i></li>
Servlet:
//查询所有用户
protected void selectUlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据(暂无)
//2、调用业务
UserService us = new UserService();
List<User> ulist = us.selectUlist();
//3、结果的展示
request.setAttribute("ulist", ulist);
request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
}
Service:
public List<User> selectUlist() {
// TODO Auto-generated method stub
return ud.selectUlist();
}
Dao:
public List<User> selectUlist() {
String sql = "select * from user";
try {
return qr.query(sql, new BeanListHandler<User>(User.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
user_list.jsp数据的显示:
<c:if test="${not empty ulist}">
<c:forEach items="${ulist}" var="u" varStatus="vs">
<tr>
<td><input name="ids" type="checkbox" value=""/></td>
<td>${vs.count}</td>
<td>${u.name}</td>
<td>
<c:if test="${u.sex ==1}">男</c:if>
<c:if test="${u.sex ==0}">女</c:if>
</td>
<td>${u.phone_number}</td>
<td>${u.area}</td>
<td>
<c:if test="${u.manager ==1}">管理员</c:if>
<c:if test="${u.manager ==0}">普通用户</c:if>
</td>
<td>${u.username}</td>
<td style="text-align: center;">
<img src="/xm_upload/${u.photo}" width="80" height="50" alt="" />
</td>
<td>
</td>
</tr>
</c:forEach>
</c:if>
四、用户分页的显示
分析图:
Mysql的分页的Sql:
/*
需求:每页显示两条数据
limit:分页的关键字 之后跟两个参数
参数1:起始索引 从0开始 计算的
参数2:每页显示的条数
*/
#第一页
SELECT * FROM USER LIMIT 0,2;
#第二页
SELECT * FROM USER LIMIT 2,2;
#第三页
SELECT * FROM USER LIMIT 4,2;
核心点:limit 后两个参数
两个公式:
- 计算起始索引
起始索引 = (当前页 - 1) * 每页显示的条数
每页显示的条数:一般给一个固定的值
当前页:从页面传过来 - 计算总页数
总页数 = 总记录数 % 每页显示的条数 == 0 ? (总记录数 / 每页显示的条数) : (总记录数 / 每页显示的条数 +1)
总记录:select count(*) from user
每页显示的条数:设置好了
代码实现:
left.jsp:
<li class="active"><cite></cite><a href="/dami/user?method=selectUlist&pageNumber=1" target="rightFrame">用户管理</a><i></i></li>
Servlet:
//查询所有用户
protected void selectUlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据(暂无)
//获取当前页
String pageNumber = request.getParameter("pageNumber");
PageBean<User> pb = new PageBean<User>();
pb.setPageNumber(Integer.parseInt(pageNumber));
pb.setPageSize(2);
//2、调用业务
UserService us = new UserService();
pb = us.selectUlist(pb);
//3、结果的展示
request.setAttribute("pb", pb);
request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
}
Service:
public PageBean<User> selectUlist(PageBean<User> pb) {
List<User> ulist = ud.selectUlist(pb);
pb.setResult(ulist);
//查询总记录数
int totalCount = ud.selecCount();
pb.setTotalCount(totalCount);
return pb;
}
Dao:
public List<User> selectUlist(PageBean<User> pb) {
String sql = "select * from user limit ?,?";
try {
Object [] param = {pb.getStartIndex(),pb.getPageSize()};
return qr.query(sql, new BeanListHandler<User>(User.class),param);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//查询总记录数
public int selecCount() {
String sql = "select count(*) from user";
try {
Long count = (Long) qr.query(sql, new ScalarHandler());
return count.intValue();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
user_list.jsp
<c:if test="${not empty pb.result}">
<c:forEach items="${pb.result}" var="u" varStatus="vs">
<div class="pagin">
<div class="message">共<i class="blue">${pb.totalCount}</i>条记录,当前显示第 <i class="blue">${pb.pageNumber} </i>页</div>
<ul class="paginList">
<li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=1">首页</a></li>
<c:if test="${pb.pageNumber != 1}">
<li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.pageNumber-1}">上一页</a></li>
</c:if>
<!--索引页 -->
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${i}">${i}</a></li>
</c:forEach>
<c:if test="${pb.pageNumber != pb.totalPage}">
<li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.pageNumber+1}">下一页</a></li>
</c:if>
<li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.totalPage}">尾页</a></li>
</ul>
</div>
总结:
- 分页的sql limit
- 两个分页的计算公式
- PageBean的作用 (封装分页相关的数据)
- 分页条的使用
五、修改用户的权限
分析图:
代码实现:
user_list.jsp
<td>
<c:if test="${u.manager ==1}">
<a href="/dami/user?method=updateRole&manager=0&uid=${u.uid}"><font color="red">修改为普通用户</font></a>
</c:if>
<c:if test="${u.manager ==0}">
<a href="/dami/user?method=updateRole&manager=1&uid=${u.uid}"><font color="green">修改为管理员</font></a>
</c:if>
</td>
Servelt:
//修改用户的权限
protected void updateRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据
String manager = request.getParameter("manager");
String uid = request.getParameter("uid");
//2、调用业务
UserService us = new UserService();
int row = us.updateRole(manager,uid);
//3、结果的展示
response.sendRedirect("/dami/user?method=selectUlist&pageNumber=1");
}
Service:
public int updateRole(String manager, String uid) {
return ud.updateRole(manager,uid);
}
Dao:
public int updateRole(String manager, String uid) {
String sql ="update user set manager = ? where uid = ?";
Object [] param = {manager,uid};
try {
return qr.update(sql, param);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
六、批量删除
6.1 全选效果的实现
思路分析图:
代码实现:
user_list.jsp
<th><input id="checkbox_main" type="checkbox" onclick="quan()"/></th>
<td><input name="ids" class="ids" type="checkbox" value=""/></td>
<script type="text/javascript">
//全选效果
function quan(){
//1、获取全选框的选中状态 true:选中 false:未选中
var flag = $("#checkbox_main").prop("checked");
//2、获取所有复选框元素对象
var idsEle = $(".ids");
//3、将复选框的checked的值设置flag
idsEle.prop("checked",flag);
}
</script>
6.2 批量删除
思路分析:
代码实现:
user_list.jsp
<li onclick="batchDelete()" id="batchDelete" style="cursor: pointer;"><span><img src="${pageContext.request.contextPath}/admin/images/t03.png" /></span>批量删除</li>
<script>
//批量删除
function batchDelete(){
if(!confirm("是否确定要批量删除?")){
return;
}
//1、获取所有被选中的复选框对象
var idsEle = $(".ids:checked");
var ids = "";
//2、遍历元素对象
idsEle.each(function(){
//获取复选框的value值
var id = this.value;
//拼接id值
ids += ","+id;
})
//截取ids ,6,5,4
ids = ids.substring(1); // 6,5,4
//向服务器发送ids值
location.href = "/dami/user?method=batchDelete&ids="+ids;
}
</script>
//location:服务器地址栏的地址
Servlet:
//批量删除
protected void batchDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据
String ids = request.getParameter("ids");
//2、调用业务
UserService us = new UserService();
int row = us.batchDelete(ids);
//3、结果的展示
if(row >0) {
response.sendRedirect("/dami/user?method=selectUlist&pageNumber=1");
}else {
response.getWriter().write("删除失败!!!!");
}
}
Service:
public int batchDelete(String ids) {
// TODO Auto-generated method stub
return ud.batchDelete(ids);
}
Dao:
public int batchDelete(String ids) {
String sql = "delete from user where uid in ("+ids+")";
try {
return qr.update(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
!!
七、分类管理的分页查询
思路:和用户的分页查询一样
商品分类表category:
CREATE TABLE `category` (
`cid` INT(10) PRIMARY KEY AUTO_INCREMENT,#主键自增
`cname` VARCHAR(50) NOT NULL,#分类名称
`state` INT(1) DEFAULT NULL,#状态 是否启用 1:启用 0:不启用
`order_number` INT(5) DEFAULT NULL,#排序号
`description` VARCHAR(100) DEFAULT NULL,#分类描述
`create_time` DATETIME # 创建时间
);
状态 是否启用 1:启用 0:不启用
为什么不删掉:方便以后看
和表对应的Category类、dao、service、servlet
代码略
八、添加分类
category_list.jsp
<li onclick="toAdd()" style="cursor: pointer;" id="add_category"><span><img src="${pageContext.request.contextPath}/admin/images/t01.png" /></span>添加类别</li>
<script type="text/javascript">
//跳转到category_add.jsp
function toAdd(){
location.href = "/dami/admin/category_add.jsp";
}
</script>
category_add.jsp
注意:将页面给的status修改state
<form action="/dami/category" method="post">
<input type="hidden" name="method" value="addCategory">
<input name="state" type="radio"
Servlet:
//添加分类
protected void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1、获取数据
//获取表单中的数据
Map<String, String[]> map = request.getParameterMap();
//创建User对象
Category category = new Category();
//BeanUtils工具类(将map中的数据封装到User对象中)
BeanUtils.populate(category, map);
//2、调用业务
CategoryService cs = new CategoryService();
cs.addCategory(category);
//3、结果的展示
response.sendRedirect("/dami/category?method=selectClist&pageNumber=1");
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Service:
public void addCategory(Category category) {
cd.addCategory(category);
}
Dao:
public void addCategory(Category c) {
String sql = "insert into category values(?,?,?,?,?,?)";
Object [] param = {null,c.getCname(),c.getState(),c.getOrder_number(),
c.getDescription(),c.getCreate_time()};
try {
qr.update(sql, param);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
九、修改分类信息
9.1 跳转16数据的回显
分析:
- 要在category_update.jsp 显示该分类的信息
- 根据cid查询分类信息 select * from categroy where cid = ?
- 传参数:cid的值
代码实现:
category_list.jsp
<a href="/dami/category?method=toUpdate&cid=${c.cid}">修改</a>
Servlet:
//跳转到category_update.jsp
protected void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取数据
String cid = request.getParameter("cid");
//2、调用业务
CategoryService cs = new CategoryService();
Category category = cs.selectByCid(cid);
//3、结果的展示
request.setAttribute("category", category);
request.getRequestDispatcher("/admin/category_update.jsp").forward(request, response);
}
Service:
public Category selectByCid(String cid) {
// TODO Auto-generated method stub
return cd.selectByCid(cid);
}
Dao:
public Category selectByCid(String cid) {
String sql = "select * from category where cid = ?";
try {
return qr.query(sql, new BeanHandler<Category>(Category.class),cid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
category_update.jsp
注意:在value中用el表达式
<li><label>类别名称</label><input name="cname" type="text" value="${category.cname}" class="dfinput" /><i>类别名称不能超过30个字符</i></li>
<li><label>是否启用</label>
<cite>
<input name="status" type="radio" value="1" <c:if test="${category.state == 1}">checked</c:if>/>是
<input name="status" type="radio" value="0" <c:if test="${category.state ==0}">checked</c:if>/>否
</cite>
</li>
省略....
问题:什么情况下直接跳转到页面、什么情况下需要请求服务器?
标准:看在跳转的页面中要不要回显数据
9.2 修改分类信息
分析:
- sql:update category cname =? ,state =?,order_number = ?,description =?,create_time =?
where cid = ? - 和添加分类信息传参数的区别
添加时:主键是自增的,所以不用传参cid
修改时:需要传参cid
代码实现:
category_update.jsp
<form action="/dami/category" method="post">
<input type="hidden" name="cid" value="${category.cid}">
<input type="hidden" name="method" value="updateCategory">
<input name="state" type="radio"
Servlet:
//修改分类
protected void updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1、获取数据
//获取表单中的数据
Map<String, String[]> map = request.getParameterMap();
//创建User对象
Category category = new Category();
//BeanUtils工具类(将map中的数据封装到User对象中)
BeanUtils.populate(category, map);
//2、调用业务
CategoryService cs = new CategoryService();
cs.updateCategory(category);
//3、结果的展示
response.sendRedirect("/dami/category?method=selectClist&pageNumber=1");
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Service:
public void updateCategory(Category category) {
cd.updateCategory(category);
}
Dao:
public void updateCategory(Category c) {
String sql = "update category set cname =?,state =?,order_number = ?,description =?,create_time"
+ "=? where cid = ?";
Object [] params = {c.getCname(),c.getState(),c.getOrder_number(),
c.getDescription(),c.getCreate_time(),c.getCid()};
try {
qr.update(sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}