JavaWeb项目--网上商城 (6-1)
day1
1.项目分析
商城实体: 用户 商品 订单 分类
实体关系: 用户和订单:一对多 商品和订单:多对多 分类和商品:一对多
今日任务: 用户模块开发 注册 用户激活 用户登录 用户退出
2.新建项目 导入jar包 驱动 c3p0 dbutils beanutils jstl mail 导入配置文件和工具类 导入页面
3.新建包结构:
com.itheima.service
com.itheima.service.impl //处理业务包
com.itheima.dao
com.itheima.dao.impl //model层处理数据库
com.itheima.web.servlet //控制类、control
com.itheima.web.filter //处理类
com.itheima.domain //实体类
com.itheima.utils //工具类
com.itheima.constant //常量类
4.servlet抽取: 前三条是弊端
1.doget每次请求都会执行--- 重写service
2.用了大量 if else if 判断执行的是那个方法让方法执行
Method method = this.getClass().getMethod(mt, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
3.每个方法执行的结果无非就是请求转发或者重定向或者打印数据 让所有的方法都返回一个字符串 若最后的结果需要请求转发,就把转发的路径给返回
若最后的结果不需要请求转发,就返回一个null
Method method = this.getClass().getMethod(mName, HttpServletRequest.class,HttpServletResponse.class);
//3.让方法执行,接受返回值
String path=(String) method.invoke(this, request,response);
4.所有servlet的service中的代码都一样 向上继续抽取编写一个BaseServlet,将之前service方法中的代码复制过来即可, 然所有的servlet都继承baseservlet即可
5.统一的错误页面
5. 模块实现
数据库用户表字段: user表 uid 用户主键id username、password、name、email、telephone、birthday、sex、
state、用户状态是否激活 0未激活 1激活 code 根据此激活状态码
案例1-用户注册
1.设置默认首页(index.jsp),让其自动的跳转到/jsp/index.jsp
2.修 改index.jsp上的 注册 连接<a href='/store/user?method=registUI'>注册</a>
3.在userservlet中编写reigstUI方法 请求转发到 /jsp/register.jsp
4.修改register.jsp上的表单信息action ="/store/user?method=regist" method为每一个子标签添加name属性
5.点击注册按钮 向userservlet发送请求
6.userservlet中编写regist方法 获取参数,封装成user对象调用service完成注册 生成提示信息,转发 /jsp/msg.jsp
7.userservice中的操作:调用dao完成注册操作发送邮件
8.userdao...
案例2-用户激活
需求 : 用户登录邮箱之后,点击邮箱中的连接,完成用户激活操作
步骤分析:
1.点击邮箱中的连接 ,向商城userservlet发送一个请求 user?method=active&coed=xxxx
2.在userservlet中编写active方法接受code 调用service完成激活 返回值:user 生成提示信息 转发
3.在service中编写激活方法 通过code获取用户 若没有找到:提示重新激活或者重新注册若找到了 设置激活状态 1将code设置为null
4.在dao需要编写两个方法 getByCode update
案例3-用户登录
需求: 在一个登录页面上,输入用户名和密码,点击登录,完成登录操作 随机验证码实现
步骤分析:
1.在index.jsp点击 登录 连接,跳转到登录页面
2.在userserlvet中编写 loginUI
3.修改login.jsp表单的信息 action: /user?method=login method 给子标签添加name属性
4.点击提交发送请求
5.在userservlet中编写login方法 获取用户名和密码 调用service完成登录 返回值:user 若登录成功,跳转到index.jsp 并展示用户信息 若登录失败,
若user为空:提示 用户名和密码 跳转到login.jsp 若user不为空但是未激活:提示信息 "请先去邮箱激活,再登录" 跳转msg.jsp
6.service,dao
案例4-用户退出
需求: 点击 index.jsp上 退出连接,退出当前的用户,跳转index.jsp
步骤分析:
1.点击 index.jsp上 退出 连接,向userservlet发送请求 /user?methode=logout
2.在userservlet中编写logout方法 销毁session 重定向到index.jsp
案例5- 扩展 记住用户名:
需求: 登录成功之后,若勾选了记住用户名,下一次再登录的时候,会展示出来用户名
步骤分析:修改login方法的逻辑 登录成功之后,判断是否勾选了记住用户名
若勾选了,将用户名(将用户名编码)保存到cookie中 在login.jsp加载成功的时候需要从cookie中获取用户名且展示出来
案例6--baseservlet的抽取
6.代码区
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.itheima.web.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <description></description> <display-name>UserServlet</display-name> <servlet-name>UserServlet</servlet-name> <servlet-class>com.itheima.web.servlet.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/user</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>BaseServlet</display-name> <servlet-name>BaseServlet</servlet-name> <servlet-class>com.itheima.web.servlet.base.BaseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BaseServlet</servlet-name> <url-pattern>/base</url-pattern> </servlet-mapping> <error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> </web-app>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% response.sendRedirect(request.getContextPath()+"/jsp/index.jsp"); %> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>WEB01</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" /> <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container-fluid"> <!-- 时间:2015-12-30 描述:菜单栏 --> <div class="container-fluid"> <div class="col-md-4"> <img src="${pageContext.request.contextPath}/img/logo2.png" /> </div> <div class="col-md-5"> <img src="${pageContext.request.contextPath}/img/header.png" /> </div> <div class="col-md-3" style="padding-top:20px"> <ol class="list-inline"> <c:if test="${empty user }"> <li><a href="${pageContext.request.contextPath }/user?method=loginUI">登录</a></li> <li><a href="${pageContext.request.contextPath }/user?method=registUI">注册</a></li> </c:if> <c:if test="${not empty user }"> ${user.name }:你好! <li><a href="${pageContext.request.contextPath }/user?method=registUI">我的订单</a></li> <li><a href="${pageContext.request.contextPath }/user?method=logout">退出</a></li> </c:if> <li><a href="cart.htm">购物车</a></li> </ol> </div> </div> <!-- 时间:2015-12-30 描述:导航条 --> <div class="container-fluid"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">首页</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="product_list.htm">手机数码<span class="sr-only">(current)</span></a></li> <li><a href="#">电脑办公</a></li> <li><a href="#">电脑办公</a></li> <li><a href="#">电脑办公</a></li> </ul> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </div> <!-- 作者:ci2713@163.com 时间:2015-12-30 描述:轮播条 --> <div class="container-fluid"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="${pageContext.request.contextPath}/img/1.jpg"> <div class="carousel-caption"> </div> </div> <div class="item"> <img src="${pageContext.request.contextPath}/img/2.jpg"> <div class="carousel-caption"> </div> </div> <div class="item"> <img src="${pageContext.request.contextPath}/img/3.jpg"> <div class="carousel-caption"> </div> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <!-- 作者:ci2713@163.com 时间:2015-12-30 描述:商品显示 --> <div class="container-fluid"> <div class="col-md-12"> <h2>热门商品 <img src="${pageContext.request.contextPath}/img/title2.jpg"/></h2> </div> <div class="col-md-2" style="border:1px solid #E7E7E7;border-right:0;padding:0;"> <img src="${pageContext.request.contextPath}/products/hao/big01.jpg" width="205" height="404" style="display: inline-block;"/> </div> <div class="col-md-10"> <div class="col-md-6" style="text-align:center;height:200px;padding:0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/middle01.jpg" width="516px" height="200px" style="display: inline-block;"> </a> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> </div> </div> <!-- 作者:ci2713@163.com 时间:2015-12-30 描述:广告部分 --> <div class="container-fluid"> <img src="${pageContext.request.contextPath}/products/hao/ad.jpg" width="100%"/> </div> <!-- 作者:ci2713@163.com 时间:2015-12-30 描述:商品显示 --> <div class="container-fluid"> <div class="col-md-12"> <h2>热门商品 <img src="${pageContext.request.contextPath}/img/title2.jpg"/></h2> </div> <div class="col-md-2" style="border:1px solid #E7E7E7;border-right:0;padding:0;"> <img src="${pageContext.request.contextPath}/products/hao/big01.jpg" width="205" height="404" style="display: inline-block;"/> </div> <div class="col-md-10"> <div class="col-md-6" style="text-align:center;height:200px;padding:0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/middle01.jpg" width="516px" height="200px" style="display: inline-block;"> </a> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;"> <a href="product_info.htm"> <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;"> </a> <p><a href="product_info.html" style='color:#666'>冬瓜</a></p> <p><font color="#E4393C" style="font-size:16px">¥299.00</font></p> </div> </div> </div> <!-- 作者:ci2713@163.com 时间:2015-12-30 描述:页脚部分 --> <div class="container-fluid"> <div style="margin-top:50px;"> <img src="${pageContext.request.contextPath}/img/footer.jpg" width="100%" height="78" alt="我们的优势" title="我们的优势" /> </div> <div style="text-align: center;margin-top: 5px;"> <ul class="list-inline"> <li><a href="info.html">关于我们</a></li> <li><a>联系我们</a></li> <li><a>招贤纳士</a></li> <li><a>法律声明</a></li> <li><a>友情链接</a></li> <li><a>支付方式</a></li> <li><a>配送方式</a></li> <li><a>服务声明</a></li> <li><a>广告声明</a></li> </ul> </div> <div style="text-align: center;margin-top: 5px;margin-bottom:20px;"> Copyright © 2005-2016 传智商城 版权所有 </div> </div> </div> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html> <head></head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>会员登录</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" /> <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script> <!-- 引入自定义css文件 style.css --> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css"/> <style> body{ margin-top:20px; margin:0 auto; } .carousel-inner .item img{ width:100%; height:300px; } .container .row div{ /* position:relative; float:left; */ } font { color: #3164af; font-size: 18px; font-weight: normal; padding: 0 10px; } </style> </head> <body> <!-- 时间:2015-12-30 描述:菜单栏 --> <div class="container-fluid"> <div class="col-md-4"> <img src="${pageContext.request.contextPath}/img/logo2.png" /> </div> <div class="col-md-5"> <img src="${pageContext.request.contextPath}/img/header.png" /> </div> <div class="col-md-3" style="padding-top:20px"> <ol class="list-inline"> <li><a href="login.htm">登录</a></li> <li><a href="register.htm">注册</a></li> <li><a href="cart.htm">购物车</a></li> </ol> </div> </div> <!-- 时间:2015-12-30 描述:导航条 --> <div class="container-fluid"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">首页</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">手机数码<span class="sr-only">(current)</span></a></li> <li><a href="#">电脑办公</a></li> <li><a href="#">电脑办公</a></li> <li><a href="#">电脑办公</a></li> </ul> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </div> <div class="container" style="width:100%;background:url('${pageContext.request.contextPath}/image/regist_bg.jpg');"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background:#fff;padding:40px 80px;margin:30px;border:7px solid #ccc;"> <font>会员注册</font>USER REGISTER <form class="form-horizontal" style="margin-top:5px;" method="post" action="${pageContext.request.contextPath }/user"> <input type="hidden" name="method" value="regist"> <div class="form-group"> <label for="username" class="col-sm-2 control-label">用户名</label> <div class="col-sm-6"> <input type="text" class="form-control" id="username" placeholder="请输入用户名" name="username"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">密码</label> <div class="col-sm-6"> <input type="password" class="form-control" id="inputPassword3" placeholder="请输入密码" name="password"> </div> </div> <div class="form-group"> <label for="confirmpwd" class="col-sm-2 control-label">确认密码</label> <div class="col-sm-6"> <input type="password" class="form-control" id="confirmpwd" placeholder="请输入确认密码"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-6"> <input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email"> </div> </div> <div class="form-group"> <label for="usercaption" class="col-sm-2 control-label">姓名</label> <div class="col-sm-6"> <input type="text" class="form-control" id="usercaption" placeholder="请输入姓名" name="name"> </div> </div> <div class="form-group opt"> <label for="inlineRadio1" class="col-sm-2 control-label">性别</label> <div class="col-sm-6"> <label class="radio-inline"> <input type="radio" name="sex" id="inlineRadio1" value="1"> 男 </label> <label class="radio-inline"> <input type="radio" name="sex" id="inlineRadio2" value="0"> 女 </label> </div> </div> <div class="form-group"> <label for="date" class="col-sm-2 control-label">出生日期</label> <div class="col-sm-6"> <input type="date" class="form-control" name="birthday"> </div> </div> <div class="form-group"> <label for="date" class="col-sm-2 control-label">验证码</label> <div class="col-sm-3"> <input type="text" class="form-control" > </div> <div class="col-sm-2"> <img src="${pageContext.request.contextPath}/image/captcha.jhtml"/> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" width="100" value="注册" name="submit" border="0" style="background: url('${pageContext.request.contextPath}/images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height:35px;width:100px;color:white;"> </div> </div> </form> </div> <div class="col-md-2"></div> </div> </div> <div style="margin-top:50px;"> <img src="${pageContext.request.contextPath}/image/footer.jpg" width="100%" height="78" alt="我们的优势" title="我们的优势" /> </div> <div style="text-align: center;margin-top: 5px;"> <ul class="list-inline"> <li><a>关于我们</a></li> <li><a>联系我们</a></li> <li><a>招贤纳士</a></li> <li><a>法律声明</a></li> <li><a>友情链接</a></li> <li><a target="_blank">支付方式</a></li> <li><a target="_blank">配送方式</a></li> <li><a>服务声明</a></li> <li><a>广告声明</a></li> </ul> </div> <div style="text-align: center;margin-top: 5px;margin-bottom:20px;"> Copyright © 2005-2016 传智商城 版权所有 </div> </body></html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/tb47
c3p0.user=root
c3p0.password=123456
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.web.servlet.base;
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;
/**
* 通用的servlet
*/
public class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.获取方法名称
String mName = request.getParameter("method");
//1.1判断 参数是否为空 若为空,执行默认的方法
if(mName == null || mName.trim().length()==0){
mName = "index";
}
//2.获取方法对象
Method method = this.getClass().getMethod(mName, HttpServletRequest.class,HttpServletResponse.class);
//3.让方法执行,接受返回值
String path=(String) method.invoke(this, request,response);
//4.判断返回值是否为空 若不为空统一处理请求转发
if(path != null){
request.getRequestDispatcher(path).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public String index(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("亲,不要捣乱");
return null;
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.itheima.constant.Constant;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.UUIDUtils;
import com.itheima.web.servlet.base.BaseServlet;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor;
/**
* 用户模块
*/
public class UserServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
/**
* 退出
*/
public String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath());
return null;
}
/**
* 用户登录
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.调用service完成登录 返回值:user
UserService us = new UserServiceImpl();
User user=us.login(username,password);
//3.判断user 根据结果生成提示
if(user == null){
//用户名和密码不匹配
request.setAttribute("msg", "用户名和密码不匹配");;
return "/jsp/login.jsp";
}
//若用户不为空,继续判断是否激活
if(Constant.USER_IS_ACTIVE != user.getState()){
//未激活
request.setAttribute("msg", "请先去邮箱激活,再登录!");
return "/jsp/msg.jsp";
}
//登录成功 保存用户登录状态
request.getSession().setAttribute("user", user);
/////////////////记住用户名//////////////////////
//判断是否勾选了记住用户名
if(Constant.SAVE_NAME.equals(request.getParameter("savename"))){
Cookie c = new Cookie("saveName", URLEncoder.encode(username, "utf-8"));
c.setMaxAge(Integer.MAX_VALUE);
c.setPath(request.getContextPath()+"/");
response.addCookie(c);
}
///////////////////////////////////////
//跳转到 index.jsp
response.sendRedirect(request.getContextPath());
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "用户登录失败");
return "/jsp/msg.jsp";
}
return null;
}
/**
* 跳转到登录页面
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String loginUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return "/jsp/login.jsp";
}
/**
* 用户激活
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.接受code
String code = request.getParameter("code");
//2.调用service完成激活 返回值:user
UserService us=new UserServiceImpl();
User user=us.active(code);
//3.判断user 生成不同的提示信息
if(user == null){
//没有找到这个用户,激活失败
request.setAttribute("msg", "激活失败,请重新激活或者重新注册~");
return "/jsp/msg.jsp";
}
//激活成功
request.setAttribute("msg", "恭喜你,激活成功了,可以登录了~");
} catch (Exception e) {
request.setAttribute("msg", "激活失败,请重新激活或者重新注册~");
return "/jsp/msg.jsp";
}
return "/jsp/msg.jsp";
}
/**
* 用户注册
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.封装对象
User user = new User();
BeanUtils.populate(user, request.getParameterMap());
//1.1手动封装uid
user.setUid(UUIDUtils.getId());
//1.2手动封装激活状态 state
user.setState(Constant.USER_IS_NOT_ACTIVE);
//1.3手动封装激活码 code
user.setCode(UUIDUtils.getCode());
//2.调用service完成注册
UserService us=new UserServiceImpl();
us.regist(user);
//3.页面转发 提示信息
request.setAttribute("msg", "恭喜你,注册成功,请登录邮箱完成激活!");
}catch (Exception e) {
e.printStackTrace();
//转发到 msg.jsp
request.setAttribute("msg", "用户注册失败!");
return "/jsp/msg.jsp";
}
return "/jsp/msg.jsp";
}
/**
* 跳转到注册页面
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return "/jsp/register.jsp";
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.web.filter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; /** * 统一编码 * @author Administrator * */ public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //1.强转 HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response=(HttpServletResponse) resp; //2.放行 chain.doFilter(new MyRequest(request), response); } @Override public void destroy() { // TODO Auto-generated method stub } } class MyRequest extends HttpServletRequestWrapper{ private HttpServletRequest request; private boolean flag=true; public MyRequest(HttpServletRequest request) { super(request); this.request=request; } @Override public String getParameter(String name) { if(name==null || name.trim().length()==0){ return null; } String[] values = getParameterValues(name); if(values==null || values.length==0){ return null; } return values[0]; } @Override /** * hobby=[eat,drink] */ public String[] getParameterValues(String name) { if(name==null || name.trim().length()==0){ return null; } Map<String, String[]> map = getParameterMap(); if(map==null || map.size()==0){ return null; } return map.get(name); } @Override /** * map{ username=[tom],password=[123],hobby=[eat,drink]} */ public Map<String,String[]> getParameterMap() { /** * 首先判断请求方式 * 若为post request.setchar...(utf-8) * 若为get 将map中的值遍历编码就可以了 */ String method = request.getMethod(); if("post".equalsIgnoreCase(method)){ try { request.setCharacterEncoding("utf-8"); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if("get".equalsIgnoreCase(method)){ Map<String,String[]> map = request.getParameterMap(); if(flag){ for (String key:map.keySet()) { String[] arr = map.get(key); //继续遍历数组 for(int i=0;i<arr.length;i++){ //编码 try { arr[i]=new String(arr[i].getBytes("iso8859-1"),"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } flag=false; } //需要遍历map 修改value的每一个数据的编码 return map; } return super.getParameterMap(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.service.impl; import com.itheima.constant.Constant; import com.itheima.dao.UserDao; import com.itheima.dao.impl.UserDaoImpl; import com.itheima.domain.User; import com.itheima.service.UserService; import com.itheima.utils.MailUtils; public class UserServiceImpl implements UserService { @Override /** * 用户注册 */ public void regist(User user) throws Exception { //1.调用dao完成注册 UserDao ud=new UserDaoImpl(); ud.save(user); //2.发送激活邮件 String emailMsg="恭喜"+user.getName()+":成为我们商城的一员,<a href='http://localhost/store/user?method=active&code="+user.getCode()+"'>点此激活</a>"; MailUtils.sendMail(user.getEmail(), emailMsg); } @Override /** * 用户激活 */ public User active(String code) throws Exception { UserDao ud=new UserDaoImpl(); //1.通过code获取用户 User user=ud.getByCode(code); //1.1 通过激活码没有找到 用户 if(user == null){ return null; } //2.若获取到了 修改用户 user.setState(Constant.USER_IS_ACTIVE); user.setCode(null); ud.update(user); return user; } @Override /** * 用户登录 */ public User login(String username, String password) throws Exception { UserDao ud=new UserDaoImpl(); return ud.getByUsernameAndPwd(username,password); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.dao.impl; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import com.itheima.dao.UserDao; import com.itheima.domain.User; import com.itheima.utils.DataSourceUtils; public class UserDaoImpl implements UserDao{ @Override /** * 用户注册 */ public void save(User user) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); /* * `uid` varchar(32) NOT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, `telephone` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `state` int(11) DEFAULT NULL, `code` varchar(64) DEFAULT NULL, */ String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?);"; qr.update(sql, user.getUid(),user.getUsername(),user.getPassword(), user.getName(),user.getEmail(),user.getTelephone(), user.getBirthday(),user.getSex(),user.getState(), user.getCode()); } @Override /** * 通过激活码获取用户 */ public User getByCode(String code) throws Exception { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from user where code = ? limit 1"; return qr.query(sql, new BeanHandler<>(User.class), code); } @Override /** * 更新用户 */ public void update(User user) throws Exception { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); /* * `uid` varchar(32) NOT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, `telephone` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `state` int(11) DEFAULT NULL, `code` varchar(64) DEFAULT NULL, */ String sql="update user set password = ?,sex = ?,state = ?,code = ? where uid = ?"; qr.update(sql, user.getPassword(),user.getSex(),user.getState(),user.getCode(),user.getUid()); } @Override /** * 用户登录 */ public User getByUsernameAndPwd(String username, String password) throws Exception { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from user where username = ? and password = ? limit 1"; return qr.query(sql, new BeanHandler<>(User.class), username,password); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.itheima.domain; public class User { /* * `uid` varchar(32) NOT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, `telephone` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `state` int(11) DEFAULT NULL, `code` varchar(64) DEFAULT NULL, */ private String uid; private String username; private String password; private String name; private String email; private String telephone; private String birthday; private String sex; private Integer state; private String code; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }