Java进阶-案例训练(十六)(商城项目(1))
文章所需资料下载sql导入:1.3项目结构搭建如何创建servlet?测试(1)之前的写法首先创建test.jsp然后创建TestServlet.java运行如下:http://localhost:8080/xiaomi/test.jsp(1)创建BaseServlet.java,并且将TestServlet 继承改为BaseServlet修改UserServlet.java继承方式为最终效果:将
需求
功能:
前台展示(用户用的)
后台管理(管理员)
1、用户模块
用户注册 | 手机验证码登录 | 用户后台管理(修改删除)
2、商品分类模块
后台CRUD | 分页功能
3、商品模块
后台商品的CRUD | 商品信息前台展示功能 | 图片上传功能 | 前台商品详情页展示
4、购物车模块
购物车商品维护及商品操作 | 结算功能
5、订单模块
支付状态维护 | 订单CRUD | 订单跟踪
6、支付宝支付模块
一、案例结构搭建
1.1 原型导入
1.2 进行数据库的导入
sql导入:
create datatabase xiaomi,
use xiaomi;
CREATE TABLE `user` (
`uid` INT(10) PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`sex` INT(1),
`phone_number` VARCHAR(20) UNIQUE,
`area` VARCHAR(100),
`manager` INT(1),
`username` VARCHAR(50) UNIQUE,
`password` VARCHAR(50) NOT NULL,
`photo` VARCHAR(100),
`create_time` TIMESTAMP
)
INSERT INTO `user`(`uid`,`name`,`sex`,`phone_number`,`area`,`manager`,`username`,`password`,`photo`,`create_time`) VALUES (14,'常儒家',1,'13227021989','中国·深圳',1,'changrujia','123456','df16be65-38a0-4bdf-9a5d-dad6580f6315Koala.jpg','2022-12-24 14:50:38'),(15,'雷豪',1,'15877641041','中国·上海',1,'leihao','123456','4f77005e-8ca3-41f0-bc71-9ec8cb304ed9Chrysanthemum.jpg','2022-12-24 14:51:22'),(16,'班长',1,'13369164010','中国·西安',0,'admin','123','f969e01e-83e1-4188-9740-6fb958b05f41Penguins.jpg','2022-12-24 14:52:25'),(17,'刘毅',1,'18092974058','中国·深圳',1,'liuyi','888888','d340a75d-7d37-4a1b-a36d-788d934609aeLighthouse.jpg','2021-12-24 15:22:53'),(18,'侯双乐',1,'15249045475','中国·珠海',1,'houshuangle','111','9fdc4f2c-fefa-4008-86a6-7120a699f559Jellyfish.jpg','2021-12-24 15:23:26'),(19,'张柯雷',1,'18829897524','中国·香港',1,'zhangkelei','111','9973b0e5-4fe6-46f9-bd32-43829e21c373Tulips.jpg','2021-12-24 15:24:01');
1.3 项目结构搭建
二、通用Servlet工具搭建
2.1、抛出需求
一个项目有大量的模块: 用户模块, 商品模块, 分类模块, 订单模块…
一个模块下还有大量的功能: 用户模块下: 用户注册, 用户登录, 用户退出, 校验用户名…
如何创建servlet?
- 一个功能对应一个servlet
好处: 一个功能对应一个servlet, 开发方便快捷
缺点: 太多的servlet会影响服务器的执行效率
- 一个项目对应一个servlet
缺点: 开发 维护都非常困难
- 一个模块对应一个servlet
2.2、一个Servlet对应一个模块
doGet和doPost的执行流程:
2.3、优化代码-提升可维护性
测试
(1)之前的写法
首先创建test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/test?method=register">用户注册</a><br/>
<a href="${pageContext.request.contextPath}/test?method=login">用户登录</a><br/>
<a href="${pageContext.request.contextPath}/test?method=loginOut">用户退出</a>
</body>
</html>
然后创建TestServlet.java
package com.zql.web.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test")
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String method = request.getParameter("method");
/*if("register".equals(method)) {
//用户注册
register(request,response);
}else if("login".equals(method)) {
//用户登录
login(request,response);
}else if("loginOut".equals(method)) {
//用户退出
loginOut(request,response);
}else{
System.out.println("没有此方法");
}*/
//使用反射形式实现
Class clazz = this.getClass();
Method m = clazz.getMethod(method, HttpServletRequest.class,HttpServletResponse.class);
m.invoke(this,request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//用户退出
public void loginOut(HttpServletRequest request, HttpServletResponse response) {
System.out.println("用户退出了");
}
//用户登录
public void login(HttpServletRequest request, HttpServletResponse response) {
System.out.println("用户登录了");
}
//用户注册
public void register(HttpServletRequest request, HttpServletResponse response) {
System.out.println("用户注册了");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
运行如下:http://localhost:8080/xiaomi/test.jsp
2.4、优化代码-提升开发便捷性
(1)创建BaseServlet.java,并且将TestServlet 继承改为BaseServletpublic class TestServlet extends BaseServlet {
package com.zql.web.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* author:Daniel
* version:1.0
*/
public class BaseServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取方法
String method = request.getParameter("method");
//使用反射进行优化
Class clazz = this.getClass();
Method m = clazz.getMethod(method, HttpServletRequest.class,HttpServletResponse.class);
//封装请求转发
String path = (String) m.invoke(this,request,response);
if(path != null && !"".equals(path)) {
request.getRequestDispatcher(path).forward(request, response);
}
} catch (Exception e) {
System.out.println("没有此方法");
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
修改UserServlet.java 继承方式为public class UserServlet extends BaseServlet {
2.5、优化代码-提升开发便捷性及效率-封装请求转发
最终效果:将会跳转到 login.jsp页面。
三、校验手机号和用户名唯一
自己随意添加几条数据来做校验验证
3.1 校验手机号唯一
(1)register.jsp(案例代码也可下载(文件一))
直接copy 😐 register.jsp 案例代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<link rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="sign_background">
<div class="sign_background_in">
<div class="sign_background_no1">
<a href="index.html"><img src="img/logo.jpg" alt=""></a>
</div>
<div class="sign_background_no2">注册小米帐号</div>
<div class="sign_background_no3">
<font color='red'></font>
<div class="sign_background_no5">
<!-- enctype="multipart/form-data" -->
<form id="f4" method="post">
<table style="width: 500px;" border="0" cellspacing="0">
<tr>
<td width="25%" class="_left">姓名:</td>
<td><input type="text" name="name"><span id="s_name"></span></td>
</tr>
<tr>
<td width="25%" class="_left">性别:</td>
<td>
男<input type="radio" name="sex" checked="checked" value="1">
女<input type="radio" name="sex" value="0">
</td>
</tr>
<tr>
<td width="25%" class="_left">电话号码:</td>
<td><input type="text" id="phone_number" name="phone_number" >
<span id="s_phone_number"></span></td>
</tr>
<tr>
<td width="25%" class="_left">所在地区:</td>
<td><input type="text" name="area"></td>
</tr>
<tr>
<td width="25%" class="_left">用户名:</td>
<td><input type="text" id="username" name="username" ><span id="s_username"></span></td>
</tr>
<tr>
<td width="25%" class="_left">密码:</td>
<td><input type="password" id="password" name="password" ><span id="s_password"></span></td>
</tr>
<tr>
<td width="25%" class="_left">上传头像:</td>
<td><input type="file" name="photo"></td>
</tr>
</table>
<div class="sign_background_no6" id="btn" >立即注册</div>
</form>
</div>
</div>
<div class="sign_background_no7">注册帐号即表示您同意并愿意遵守小米 <span>用户协议</span>和<span>隐私政策</span> </div>
</div>
<div class="sign_background_no8"><img src="img/sign01.jpg" alt=""></div>
</div>
</body>
</html>
编写js代码:
<script type="text/javascript">
/*检验手机号唯一*/
$(function() {
$("#phone_number").blur(function() {
var phone_number = $("#phone_number").val();
alert(phone_number);
$.post("${pageContext.request.contextPath}/user",{"method":"checkPhoneNumber","phone_number":phone_number},
function(data) {
alert(data);
})
});
})
</script>
(2)从上述TestServlet.java中拷贝一个类似方法到UserServlet.java中:
UserServlet.java
package com.zql.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zql.pojo.User;
import com.zql.service.UserService;
import com.zql.service.impl.UserServiceImpl;
@WebServlet("/user")
public class UserServlet extends BaseServlet{
//检验手机号是否唯一
//用户退出
public String checkPhoneNumber(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String phone_number = request.getParameter("phone_number");
System.out.println(phone_number);
UserService us = new UserServiceImpl();
User user = us.checkPhoneNumber(phone_number);
String msg = "";
if(user != null) {
msg="true";
}else {
msg="false";
}
response.getWriter().write(msg);
return null;
}
}
(3) UserService.java
package com.zql.service;
import java.sql.SQLException;
import com.zql.pojo.User;
/**
* author:Daniel
* version:1.0
*/
public interface UserService {
//检验手机号是否唯一
User checkPhoneNumber(String phone_number) throws Exception;
}
(4) UserServiceImpl.java
package com.zql.service.impl;
import java.sql.SQLException;
import com.zql.dao.UserDao;
import com.zql.dao.impl.UserDaoImpl;
import com.zql.pojo.User;
import com.zql.service.UserService;
/**
* author:Daniel
* version:1.0
*/
public class UserServiceImpl implements UserService{
UserDao ud = new UserDaoImpl();
@Override
public User checkPhoneNumber(String phone_number)throws Exception {
//检验手机号是否唯一
return ud.checkPhoneNumber(phone_number);
}
}
(5) UserDao.java
package com.zql.dao;
import java.sql.SQLException;
import com.zql.pojo.User;
/**
* author:Daniel
* version:1.0
*/
public interface UserDao {
//检验手机号是否唯一
User checkPhoneNumber(String phone_number) throws Exception;
}
(6) UserDaoImpl.java
package com.zql.dao.impl;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.zql.dao.UserDao;
import com.zql.pojo.User;
import com.zql.utils.C3P0Utils;
/**
* author:Daniel
* version:1.0
*/
public class UserDaoImpl implements UserDao{
//检验手机号是否唯一
@Override
public User checkPhoneNumber(String phone_number) throws Exception {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from user where phone_number = ?";
return qr.query(sql, new BeanHandler<User>(User.class),phone_number);
}
}
(7) register.jsp
<script type="text/javascript">
/*检验手机号唯一*/
$(function() {
$("#phone_number").blur(function() {
var phone_number = $("#phone_number").val();
alert(phone_number);
$.post("${pageContext.request.contextPath}/user",{"method":"checkPhoneNumber","phone_number":phone_number},
function(data) {
//alert(data);
if(data == "true"){
$("#s_phone_number").html("<font color='red'>此号码被占用</font>");
}
if(data == "false"){
$("#s_phone_number").html("<font color='green'>此号码可以使用</font>");
}
})
});
})
</script>
检验手机号码完整 register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<link rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
/*检验手机号唯一*/
$(function() {
$("#phone_number").blur(function() {
var phone_number = $("#phone_number").val();
alert(phone_number);
$.post("${pageContext.request.contextPath}/user",{"method":"checkPhoneNumber","phone_number":phone_number},
function(data) {
//alert(data);
if(data == "true"){
$("#s_phone_number").html("<font color='red'>此号码被占用</font>");
}
if(data == "false"){
$("#s_phone_number").html("<font color='green'>此号码可以使用</font>");
}
})
});
})
</script>
</head>
<body>
<div class="sign_background">
<div class="sign_background_in">
<div class="sign_background_no1">
<a href="index.html"><img src="img/logo.jpg" alt=""></a>
</div>
<div class="sign_background_no2">注册小米帐号</div>
<div class="sign_background_no3">
<font color='red'></font>
<div class="sign_background_no5">
<!-- enctype="multipart/form-data" -->
<form id="f4" method="post">
<table style="width: 500px;" border="0" cellspacing="0">
<tr>
<td width="25%" class="_left">姓名:</td>
<td><input type="text" name="name"><span id="s_name"></span></td>
</tr>
<tr>
<td width="25%" class="_left">性别:</td>
<td>
男<input type="radio" name="sex" checked="checked" value="1">
女<input type="radio" name="sex" value="0">
</td>
</tr>
<tr>
<td width="25%" class="_left">电话号码:</td>
<td><input type="text" id="phone_number" name="phone_number" >
<span id="s_phone_number"></span></td>
</tr>
<tr>
<td width="25%" class="_left">所在地区:</td>
<td><input type="text" name="area"></td>
</tr>
<tr>
<td width="25%" class="_left">用户名:</td>
<td><input type="text" id="username" name="username" ><span id="s_username"></span></td>
</tr>
<tr>
<td width="25%" class="_left">密码:</td>
<td><input type="password" id="password" name="password" ><span id="s_password"></span></td>
</tr>
<tr>
<td width="25%" class="_left">上传头像:</td>
<td><input type="file" name="photo"></td>
</tr>
</table>
<div class="sign_background_no6" id="btn" >立即注册</div>
</form>
</div>
</div>
<div class="sign_background_no7">注册帐号即表示您同意并愿意遵守小米 <span>用户协议</span>和<span>隐私政策</span> </div>
</div>
<div class="sign_background_no8"><img src="img/sign01.jpg" alt=""></div>
</div>
</body>
</html>
运行结果显示:
3.2 校验用户名唯一
面向复制开发: 修改校验"电话号码"为"用户名"即可
register.jsp
/*校验用户名唯一*/
$("#username").blur(function() {
var username = $("#username").val();
//alert(username);
$.post("${pageContext.request.contextPath}/user",{"method":"checkUsername","username":username},
function(data) {
//alert(data);
if(data == "true"){
$("#s_username").html("<font color='red'>此用户名被占用</font>");
}
if(data == "false"){
$("#s_username").html("<font color='green'>此用户名可以使用</font>");
}
})
});
UserServlet.java
/*校验用户名唯一*/
public String checkUsername(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String username = request.getParameter("username");
System.out.println(username);
UserService us = new UserServiceImpl();
User user = us.checkUsername(username);
String msg = "";
if(user != null) {
msg="true";
}else {
msg="false";
}
response.getWriter().write(msg);
return null;
}
UserService.java
/*校验用户名唯一*/
User checkUsername(String username) throws Exception;
UserServiceImpl.java
/*校验用户名唯一*/
@Override
public User checkUsername(String username) throws Exception {
return ud.checkUsername(username);
}
UserDao.java
/*校验用户名唯一*/
User checkUsername(String username) throws Exception;
UserDaoImpl.java
/*校验用户名唯一*/
@Override
public User checkUsername(String username) throws Exception {
String sql = "select * from user where username = ?";
return qr.query(sql, new BeanHandler<User>(User.class),username);
}
最终结果显示
四、用户注册和文件上传
4.1 用户注册
(1)register.jsp
第一处添加:
/*用户注册*/
$("#btn").click(function(){
$("#f4").submit();
});
第二处添加
action="${pageContext.request.contextPath}/user?method=register"
(2)UserServlet.java
/*用户注册*/
public String register(HttpServletRequest request, HttpServletResponse response) throws Exception{
//System.out.println(111);
//处理数据
try {
Map<String, String[]> map = request.getParameterMap();
User user = new User();
BeanUtils.populate(user, map);
user.setCreate_time(new Date().toLocaleString());
us.register(user);
response.getWriter().write("<h3>恭喜您注册成功,5秒后将跳转登录页面</h3>");
response.setHeader("refresh", "5;url=/xiaomi/login.jsp");
} catch (Exception e) {
response.getWriter().write("<h3>不好意思,注册失败!!</h3>");
response.setHeader("refresh", "4;url=/xiaomi/register.jsp");
e.printStackTrace();
}
return null;
}
(3)UserService.java
/*用户注册*/
void register(User user) throws Exception;
UserServiceImpl.java
/*用户注册*/
@Override
public void register(User user) throws Exception {
ud.register(user);
}
(4)UserDao.java
/*用户注册*/
void register(User user) throws Exception;
UserDaoImpl.java
/*用户注册*/
@Override
public void register(User user) throws Exception {
String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
Object[] params = {null,user.getName(),user.getSex(),user.getPhone_number()
,user.getArea(),user.getManager(),user.getUsername(),user.getPassword(),
user.getPhoto(),user.getCreate_time()};
qr.update(sql, params);
}
注册成功显示(数据库会增加所注册信息)
注册失败显示:
4.2 文件上传
浏览器三步走:
- type=”file”
- 提交方式必须是post
- 表单上加这个属性
服务器三步走:
- 新建upload文件夹
- 需要加注解
@MultipartConfig
- 获取资源对象和图片名称(步骤看代码及注释标注)
- 上传图片(步骤看代码及注释标注)
UserServlet.java
/*用户注册*/
public String register(HttpServletRequest request, HttpServletResponse response) throws Exception{
//System.out.println(111);
//处理数据
try {
Map<String, String[]> map = request.getParameterMap();
User user = new User();
BeanUtils.populate(user, map);
//创建时间
user.setCreate_time(new Date().toLocaleString());
//文件(图片)上传
//Content-Disposition: form-data; name="photo"; filename="logo2.png" //f12浏览器获得
Part part = request.getPart("photo");
//System.out.println(part);//org.apache.catalina.core.ApplicationPart@7de43dc1
String header = part.getHeader("Content-Disposition");
//System.out.println(header);//form-data; name="photo"; filename="logo2.png"
String fileName = header.substring(header.indexOf("filename")+10, header.length()-1);
//System.out.println(substring);//logo2.png
String path = request.getServletContext().getRealPath("/upload");
//System.out.println(path); //项目下新建得upload在tomcat下得路径
part.write(path+"\\"+fileName);
//us.register(user);
//response.getWriter().write("<h3>恭喜您注册成功,5秒后将跳转登录页面</h3>");
//response.setHeader("refresh", "5;url=/xiaomi/login.jsp");
} catch (Exception e) {
response.getWriter().write("<h3>不好意思,注册失败!!</h3>");
response.setHeader("refresh", "4;url=/xiaomi/register.jsp");
e.printStackTrace();
}
return null;
}
上传成功显示:
4.3 完善文件上传
三个问题:
- 相同名字(如:一张在桌面,一张在D盘)的图片 覆盖了 如何解决?
- Clean(关闭 ,清除)服务器, 图片丢失, 如何解决?
- 数据库中photo字段存什么值?
- 相同名字的图片 覆盖了 如何解决?
(2)fileName = UUIDUtils.getUUID()+fileName;
-
Clean(关闭 ,清除)服务器, 图片丢失, 如何解决?
(1) 本地磁盘中新建xml_upload(自命名) (2) 在eclipse中进行如下操作:
最后一定要ctrl+s
取消文件上传前一步得注释
- 数据库中photo字段存什么值?
user.setPhoto(fileName);
UserServlet.java
package com.zql.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Time;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.beanutils.BeanUtils;
import com.zql.pojo.User;
import com.zql.service.UserService;
import com.zql.service.impl.UserServiceImpl;
import com.zql.utils.UUIDUtils;
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends BaseServlet{
UserService us = new UserServiceImpl();
//检验手机号是否唯一
//用户退出
public String checkPhoneNumber(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String phone_number = request.getParameter("phone_number");
System.out.println(phone_number);
User user = us.checkPhoneNumber(phone_number);
String msg = "";
if(user != null) {
msg="true";
}else {
msg="false";
}
response.getWriter().write(msg);
return null;
}
/*校验用户名唯一*/
public String checkUsername(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String username = request.getParameter("username");
System.out.println(username);
//UserService us = new UserServiceImpl();
User user = us.checkUsername(username);
String msg = "";
if(user != null) {
msg="true";
}else {
msg="false";
}
response.getWriter().write(msg);
return null;
}
/*用户注册*/
public String register(HttpServletRequest request, HttpServletResponse response) throws Exception{
//System.out.println(111);
//处理数据
try {
Map<String, String[]> map = request.getParameterMap();
User user = new User();
BeanUtils.populate(user, map);
//创建时间
user.setCreate_time(new Date().toLocaleString());
//文件(图片)上传
//Content-Disposition: form-data; name="photo"; filename="logo2.png" //f12浏览器获得
//获取图片资源
Part part = request.getPart("photo");
//System.out.println(part);//org.apache.catalina.core.ApplicationPart@7de43dc1
String header = part.getHeader("Content-Disposition");
//System.out.println(header);//form-data; name="photo"; filename="logo2.png"
//获取图片名称
String fileName = header.substring(header.indexOf("filename")+10, header.length()-1);
//System.out.println(substring);//logo2.png
//1. 相同名字的图片 覆盖了 如何解决?
fileName = UUIDUtils.getUUID()+fileName;
//String path = request.getServletContext().getRealPath("/upload");
//System.out.println(path); //项目下新建得upload在tomcat下得路径
//2. Clean(关闭 ,清除)服务器, 图片丢失, 如何解决?
String path = "D:\\develop\\eclipse\\eclipse-workspace\\xml_upload";
part.write(path+"\\"+fileName);
//3. 数据库中photo字段存什么值?
user.setPhoto(fileName);
us.register(user);
response.getWriter().write("<h3>恭喜您注册成功,5秒后将跳转登录页面</h3>");
response.setHeader("refresh", "5;url=/xiaomi/login.jsp");
} catch (Exception e) {
response.getWriter().write("<h3>不好意思,注册失败!!</h3>");
response.setHeader("refresh", "4;url=/xiaomi/register.jsp");
e.printStackTrace();
}
return null;
}
}
运行最后显示:
五、获取手机验证码和手机号验证码登录
5.1 获取手机验证码
5.1.1 阿里云短信验证码学习
如果之前用过直接按照下面操作否则点击我了解再操作哈(文件二)
操作1:控制台——>短信服务——>国内消息 就可以看到自己是否之前启动过阿里云短信啦 😐
操作2:没有则自己进行添加: 模板管理——>添加模板 即可生成如下:
工具类:SMSTools.java
package com.zql.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* 描述:手机验证码工具类
*
*/
public class SMSTools {
//发送验证码
public static void sendCode(String phone_number) {
//获取四位随机数
long code = (long) (Math.random()*(9999-1000)+1000);
//设置超时时间-可自行调整
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient需要的几个参数
final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
//替换成你的AK
final String accessKeyId = "LTAI4FpTeynnwtmDHPghDZSB";//你的accessKeyId,参考文档《SMSTools说明》 步骤二
final String accessKeySecret = "buANUlhQZhJKKJCDF36JC09Y4SzSIK";//你的accessKeySecret,参考文档《SMSTools说明》步骤二
//初始化ascClient,暂时不支持多region(请勿修改)
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
e.printStackTrace();
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
SendSmsRequest request = new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
request.setPhoneNumbers(phone_number);
//必填:短信签名-可在短信控制台中找到
request.setSignName("小米商城");//参考文档《SMSTools说明》步骤三
//必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
request.setTemplateCode("SMS_178756728");参考文档《SMSTools说明》步骤四
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
request.setTemplateParam("{\"name\":\"Tom\", \"code\":\""+code+"\"}");
//可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//请求成功
System.out.println("发送验证码成功");
}else {
System.out.println("发送验证码失败");
}
}
//测试
public static void main(String[] args) {
//调用上面方法
sendCode("18899769949");
}
}
运行结果:
5.1.2 获取手机验证码
login.jsp
<script type="text/javascript">
/*获取手机验证码 */
$(function(){
$("#zphone").click(function(){
var p_val = $("#phone_number").val();
var req =/^\s*$/;
if(req.test(p_val)){
//alert("手机号码不能为空");
}
//调用下面已提供得倒计时方法
RemainTime();
$.post("${pageContext.request.contextPath}/user",{"method":"sendCode","phone_number":p_val},function(data){
//alert(data)
});
});
})
</script>
UserServlet.java
//获取手机验证码
public String sendCode(HttpServletRequest request, HttpServletResponse response)throws Exception {
//System.out.println(111);
//处理数据
String phone_number = request.getParameter("phone_number");
//SMSTools.sendCode(phone_number);
//获取四位随机数
long code = (long) (Math.random()*(9999-1000)+1000);
//模拟获取
System.out.println("你的校验码:"+code+"您正在进化成为一个世界级顶级超人,感谢有你!");
return null;
}
最终显示:http://localhost:8080/xiaomi/login.jsp
5.2 手机号验证码登录
代码实现:
login.jsp
<script type="text/javascript">
//页面加载
$(function(){
//获取手机验证码
var req = /^\s*$/;
$("#zphone").click(function(){
var p_val = $("#phone_number").val();
if(req.test(p_val)){
alert("手机号码不能为空")
return;
}
//倒计时 直接调用
RemainTime();
//发送ajax请求
$.post("${pageContext.request.contextPath}/user",
{"method":"sendCode","phone_number":p_val},function(data){
})
})
//手机号 验证码 登录
$("#sub").click(function(){
//获取验证码的值
var code = $("#code").val();
if(req.test(code)){
alert("验证码不能为空")
return;
}
//获取手机号的值
var p_val = $("#phone_number").val();
if(req.test(p_val)){
alert("手机号码不能为空")
return;
}
//发送ajax请求
$.post("${pageContext.request.contextPath}/user",{"method":"login","code":code,
"phone_number":p_val},function(data){
//获取后台的返回值
if(data == "0"){
$("#msg").html("验证码错误")
}else if(data == "1"){
$("#msg").html("该手机号未注册, 请先注册!")
}else if(data == "2"){
alert("登录成功")
}
})
})
})
</script>
UserServlet.java
//手机号验证码登录
public String login(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
//获取手机号码
String phone_number = request.getParameter("phone_number");
//获取手机验证码
String code = request.getParameter("code");
code = phone_number+code;
//业务处理
String msg = us.login(request,phone_number,code);
//响应到前端页面
response.getWriter().write(msg);
return null;
}
//获取手机验证码
public String sendCode(HttpServletRequest request, HttpServletResponse response)throws Exception {
//System.out.println(111);
//处理数据
String phone_number = request.getParameter("phone_number");
//SMSTools.sendCode(phone_number);
//获取四位随机数
long code = (long) (Math.random()*(9999-1000)+1000);
//模拟获取
System.out.println("你的校验码:"+code+"您正在进化成为一个世界级顶级超人,感谢有你!");
//存放到session域对象中
request.getSession().setAttribute("code",phone_number+code+"");
return null;
}
UserService.java
//手机号验证码登录
String login(HttpServletRequest request, String code, String phone_number) throws Exception;
UserServiceImpl.java
//登录
@Override
public String login(HttpServletRequest request, String phone_number, String code) throws Exception {
//判断第一情况
//从域中获取发送的验证码
HttpSession session = request.getSession();
String sessionCode = (String) session.getAttribute("code");
//判断验证码是否一致
if(code.equals(sessionCode)) {
System.out.println("验证码正确");
//判断手机是否注册
User user = ud.checkPhoneNumber(phone_number);
if(user != null) {
//已被注册 登录成功 返回 2
return "2";
}else {
//手机不存在,提示该手机号未注册 返回 1
System.out.println("该手机号未注册");
return "1";
}
}else {
//判断验证码不正确 返回值 0
System.out.println("验证码错误");
return "0";
}
}
逻辑走通了,但是遇到一点问题,一般是点击了Build Path导致
解决办法:可以重建个空工程,将静态页面,com包,数据库连接xml拷贝进去一般就正常了
登录四种最终显示:
(1)登录成功显示
(2)手机号码或验证码错误显示:
(3)未注册显示:
(4)验证码空显示:
六 、后台管理部分实现
6.1、管理员登录
(1)导入资料(文件二)admin
(2)admin/login.jsp
(3) UserServlet.java
//管理员登录
public String adminLogin(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//业务处理
User user = us.adminLogin(username,password);
//响应页面
if(user != null) {
//存放到域中
request.getSession().setAttribute("user", user);
//重定向
System.out.println("登录成功");
response.sendRedirect(request.getContextPath()+"/admin/main.jsp");
}else {
request.setAttribute("msg", "用户名或者密码错误");
return "/admin/login.jsp";
}
return null;
}
UserService.java
//管理员登录
User adminLogin(String username, String password) throws Exception;
UserServiceImpl.java
//管理员登录
@Override
public User adminLogin(String username, String password) throws Exception {
return ud.adminLogin(username,password);
}
UserDao.java
//管理员登录
User adminLogin(String username, String password)throws Exception;
UserDaoImpl.java
//管理员登录
@Override
public User adminLogin(String username, String password) throws Exception {
String sql = "select * from user where username=? and password=? and manager=?";
Object[] params = {username,password,1};
return qr.query(sql, new BeanHandler<User>(User.class),params);
}
admin/login.jsp
<li><font color="red">${msg}</font></li>
admin/index.jsp
${user.name}
登录成功显示:
6.2、管理员退出
(1)admin/top.jsp
(2)UserServlet.java
//管理员退出
public String adminLoginOut(HttpServletRequest request, HttpServletResponse response)throws Exception {
HttpSession session = request.getSession();
session.removeAttribute("user");
response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
return null;
}
最终显示:
6.3、用户管理–查询所有用户
(1)在admin/left.jsp中添加标签
<li><cite></cite><a href="${pageContext.request.contextPath }/user?method=findUserList" target="rightFrame">用户管理</a><i></i></li>
(2)UserServlet.java
//查询所有用户
public String findUserList(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String parameter = request.getParameter("");
List<User> ulist = us.findUserList();
//System.out.println(ulist);//控制台测试查询出来了
//存放到域中
request.setAttribute("ulist", ulist);
return "/admin/user_list.jsp";
}
(3) UserService.java
//查询所有用户
List<User> findUserList()throws Exception;
(4) UserServiceImpl.java
//查询所有用户
@Override
public List<User> findUserList() throws Exception {
return ud.findUserList();
}
(5) UserDao.java
//查询所有用户
List<User> findUserList() throws Exception;
(3) UserDaoImpl.java
//查询所有用户
@Override
public List<User> findUserList() throws Exception{
String sql = "select * from user";
return qr.query(sql, new BeanListHandler<User>(User.class));
}
(6)使用EL表达式编写部分 admin/user_list.jsp
<c:if test="${not empty ulist}">
<c:forEach items="${ulist}" var="p" varStatus="vs">
<tr>
<td><input name="ids" type="checkbox" value=""/></td>
<td>${vs.count }</td>
<td>${p.name }</td>
<td>
<c:if test="${p.sex == 1}">男</c:if>
<c:if test="${p.sex == 0}">女</c:if>
</td>
<td>${p.phone_number}</td>
<td>${p.area }</td>
<td>
<c:if test="${p.manager == 1}"><font color='red'>管理员</font></c:if>
<c:if test="${p.manager == 0}">普通用户</c:if>
</td>
<td>${p.username }</td>
<td style="text-align: center;">
<img src="/xml_upload/${p.photo }" width="80" height="50" alt="" />
</td>
<td>
<c:if test="${p.manager == 0}">
<a href="">指定管理员</a>
</c:if>
<c:if test="${p.manager == 1}">
<a href=""><font color='red'>指定普通用户</font></a>
</c:if>
</td>
</tr>
</c:forEach>
</c:if>
完整——>admin/user_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户信息</title>
<link href="${pageContext.request.contextPath}/admin/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
// old write
$(document).ready(function(){
$(".click").click(function(){
$(".tip").fadeIn(200);
});
$(".tiptop a").click(function(){
$(".tip").fadeOut(200);
});
$(".sure").click(function(){
$(".tip").fadeOut(100);
});
$(".cancel").click(function(){
$(".tip").fadeOut(100);
});
});
</script>
</head>
<body>
<div class="place">
<span>位置:</span>
<ul class="placeul">
<li><a href="#">商品管理</a></li>
</ul>
</div>
<div class="rightinfo">
<div class="tools">
<ul class="toolbar">
<!--
<li class="click"><span><img src="images/t02.png" /></span>修改</li>
<li><span><img src="images/t04.png" /></span>统计</li>
-->
<li id="batchDelete" style="cursor: pointer;"><span><img src="${pageContext.request.contextPath}/admin/images/t03.png" /></span>批量删除</li>
</ul>
</div>
<table class="tablelist">
<thead>
<tr>
<th><input id="checkbox_main" type="checkbox" /></th>
<th>序号<i class="sort"><img src="${pageContext.request.contextPath}/admin/images/px.gif" /></i></th>
<th>姓名</th>
<th>性别</th>
<th>电话号码</th>
<th>所在地区</th>
<th>权限</th>
<th>账号</th>
<th>头像</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:if test="${not empty ulist}">
<c:forEach items="${ulist}" var="p" varStatus="vs">
<tr>
<td><input name="ids" type="checkbox" value=""/></td>
<td>${vs.count }</td>
<td>${p.name }</td>
<td>
<c:if test="${p.sex == 1}">男</c:if>
<c:if test="${p.sex == 0}">女</c:if>
</td>
<td>${p.phone_number}</td>
<td>${p.area }</td>
<td>
<c:if test="${p.manager == 1}"><font color='red'>管理员</font></c:if>
<c:if test="${p.manager == 0}">普通用户</c:if>
</td>
<td>${p.username }</td>
<td style="text-align: center;">
<img src="/xml_upload/${p.photo }" width="80" height="50" alt="" />
</td>
<td>
<c:if test="${p.manager == 0}">
<a href="">指定管理员</a>
</c:if>
<c:if test="${p.manager == 1}">
<a href=""><font color='red'>指定普通用户</font></a>
</c:if>
</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
<div class="pagin">
<div class="message">共<i class="blue">100</i>条记录,当前显示第 <i class="blue">10 </i>页</div>
<ul class="paginList">
<li class="paginItem"><a href="">首页</a></li>
<li class="paginItem"><a href="">上一页</a></li>
<li class="paginItem"><a href="">下一页</a></li>
<li class="paginItem"><a href="">尾页</a></li>
</ul>
</div>
<div class="tip">
<div class="tiptop"><span>提示信息</span><a></a></div>
<div class="tipinfo">
<span><img src="images/ticon.png" /></span>
<div class="tipright">
<p>是否确认对信息的修改 ?</p>
<cite>如果是请点击确定按钮 ,否则请点取消。</cite>
</div>
</div>
<div class="tipbtn">
<input name="" type="button" class="sure" value="确定" />
<input name="" type="button" class="cancel" value="取消" />
</div>
</div>
</div>
<script type="text/javascript">
$('.tablelist tbody tr:odd').addClass('odd');
</script>
</body>
</html>
最终显示:http://localhost:8080/xiaomi/admin/main.jsp
6.4、用户管理对查询所有用户进行分页
(1)导入工具类PageBean.java(资料文件二)
(2)修改添加 admin/left.jsp
${pageContext.request.contextPath }/user?method=findUserByPageBean&pageNumber=1
(3) 根据(2)提供的方法编写 UserServlet.java
//对查询的所有用户进行分页
public String findUserByPageBean(HttpServletRequest request, HttpServletResponse response)throws Exception {
//处理数据
String pageNumber = request.getParameter("pageNumber");
//创建pageBean对象
PageBean pb = new PageBean();
//设置当前页
pb.setPageNumber(Integer.parseInt(pageNumber));
//设置每页显示的条数
pb.setPageSize(5);
PageBean<User> pageBean = us.findUserByPageBean(pb);
//存放到域中
request.setAttribute("pb", pageBean);
//请求转发
return "/admin/user_list.jsp";
}
(4) UserService.java
//对查询到的用户进行分页
PageBean<User> findUserByPageBean(PageBean pb) throws Exception;
(5) UserServiceImpl.java
//对查询到的用户进行分页
@Override
public PageBean<User> findUserByPageBean(PageBean pb) throws Exception {
//当前显示的数据
List<User> result = ud.findUserByPageBean(pb);
//总记录数
int count = ud.selectCount();
pb.setResult(result);
pb.setTotalCount(count);
return pb;
}
(6) UserDao.java
//将查询到的所有用户进行分页
List<User> findUserByPageBean(PageBean pb) throws Exception;
//分页显示总记录数
int selectCount() throws Exception;
(7) UserDaoImpl.java
//将查询到的所有用户进行分页
@Override
public List<User> findUserByPageBean(PageBean pb) throws Exception {
String sql = "select * from user limit ?,?";
Object [] param = {pb.getStartIndex(),pb.getPageSize()};
return qr.query(sql, new BeanListHandler<User>(User.class),param);
}
//查询要分页显示的总记录数
@Override
public int selectCount() throws SQLException {
String sql = "select count(*) from user";
Long count = (Long) qr.query(sql, new ScalarHandler());
return count.intValue();
}
(8) admin/user_list.jsp
完整代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户信息</title>
<link href="${pageContext.request.contextPath}/admin/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
// old write
$(document).ready(function(){
$(".click").click(function(){
$(".tip").fadeIn(200);
});
$(".tiptop a").click(function(){
$(".tip").fadeOut(200);
});
$(".sure").click(function(){
$(".tip").fadeOut(100);
});
$(".cancel").click(function(){
$(".tip").fadeOut(100);
});
});
</script>
</head>
<body>
<div class="place">
<span>位置:</span>
<ul class="placeul">
<li><a href="#">商品管理</a></li>
</ul>
</div>
<div class="rightinfo">
<div class="tools">
<ul class="toolbar">
<!--
<li class="click"><span><img src="images/t02.png" /></span>修改</li>
<li><span><img src="images/t04.png" /></span>统计</li>
-->
<li id="batchDelete" style="cursor: pointer;"><span><img src="${pageContext.request.contextPath}/admin/images/t03.png" /></span>批量删除</li>
</ul>
</div>
<table class="tablelist">
<thead>
<tr>
<th><input id="checkbox_main" type="checkbox" /></th>
<th>序号<i class="sort"><img src="${pageContext.request.contextPath}/admin/images/px.gif" /></i></th>
<th>姓名</th>
<th>性别</th>
<th>电话号码</th>
<th>所在地区</th>
<th>权限</th>
<th>账号</th>
<th>头像</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:if test="${not empty pb.result}">
<c:forEach items="${pb.result}" var="p" varStatus="vs">
<tr>
<td><input name="ids" type="checkbox" value=""/></td>
<td>${vs.count }</td>
<td>${p.name }</td>
<td>
<c:if test="${p.sex == 1}">男</c:if>
<c:if test="${p.sex == 0}">女</c:if>
</td>
<td>${p.phone_number}</td>
<td>${p.area }</td>
<td>
<c:if test="${p.manager == 1}"><font color='red'>管理员</font></c:if>
<c:if test="${p.manager == 0}">普通用户</c:if>
</td>
<td>${p.username }</td>
<td style="text-align: center;">
<img src="/xml_upload/${p.photo }" width="80" height="50" alt="" />
</td>
<td>
<c:if test="${p.manager == 0}">
<a href="">指定管理员</a>
</c:if>
<c:if test="${p.manager == 1}">
<a href=""><font color='red'>指定普通用户</font></a>
</c:if>
</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
<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="${pageContext.request.contextPath }/user?method=findUserByPageBean&pageNumber=1">首页</a></li>
<li class="paginItem"><a href="${pageContext.request.contextPath }/user?method=findUserByPageBean&pageNumber=${pb.pageNumber-1}">上一页</a></li>
<li class="paginItem"><a href="${pageContext.request.contextPath }/user?method=findUserByPageBean&pageNumber=${pb.pageNumber+1}">下一页</a></li>
<li class="paginItem"><a href="${pageContext.request.contextPath }/user?method=findUserByPageBean&pageNumber=${pb.totalPage}">尾页</a></li>
</ul>
</div>
<div class="tip">
<div class="tiptop"><span>提示信息</span><a></a></div>
<div class="tipinfo">
<span><img src="images/ticon.png" /></span>
<div class="tipright">
<p>是否确认对信息的修改 ?</p>
<cite>如果是请点击确定按钮 ,否则请点取消。</cite>
</div>
</div>
<div class="tipbtn">
<input name="" type="button" class="sure" value="确定" />
<input name="" type="button" class="cancel" value="取消" />
</div>
</div>
</div>
<script type="text/javascript">
$('.tablelist tbody tr:odd').addClass('odd');
</script>
</body>
</html>
最终显示 😐
http://localhost:8080/xiaomi/admin/login.jsp
:
更多推荐
所有评论(0)