一、用户注册、加密、激活、登录、退出
步骤实现:
1.在index.jsp上点击 注册页面 跳转到register.jsp
2.点击注册
<a href="/store/user?method=registUI"></a>
3.在userservlet中编写一个registUI 方法
请求转发到 register.jsp即可.
完成注册
1.regist
封装数据
设置id
设置state
设置code
调用service 完成注册操作
请求转发 /jsp/msg.jsp
2.userservice中的service
调用dao
发送激活邮件
3.userdao dao 添加一条数据
注意:封装数据的时候报了一个错误
是因为 字符串装成时间类型的是出现错误
BeanUtils不支持字符串装成时间
解决方案:
自定义转化器
1.编写一个类 实现Conventer接口
2.实现方法
convert(转换成的类型,前台页面传入的字符串)
3.注册转化器 在封装数据之前注册
ConvertUtils.register(new MyConventer(), Date.class);
扩展:
使用算法加密密码
md5加密 不对称的加密,不可逆
在数据库中可以使用 md5(字段|值)
java中api
-----------------------------------------------------------------------------------------------------------
首页跳转:
<%@ 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>
<jsp:forward page="/index"></jsp:forward>
</body>
</html>
---------------
WEB.XML
<servlet>
<servlet-name>IndexServlet</servlet-name>
<servlet-class>com.feizhu.web.servlet.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
----------
package com.feizhu.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 与首页相关的servlet
*/
public class IndexServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return "/jsp/index.jsp";
}
}
--------------------------------------------------------------------------------------------------------------
前端实现:
注册
<form class="form-horizontal" style="margin-top:5px;" action="${pageContext.request.contextPath }/user?method=regist" method="post">
<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" id="inlineRadio1" value="男" name="sex"> 男
</label>
<label class="radio-inline">
<input type="radio" id="inlineRadio2" value="女" name="sex"> 女
</label>
</div>
</div>
<div class="form-group">
<label for="date" class="col-sm-2 control-label" name="date">出生日期</label>
<div class="col-sm-6">
<input type="date" class="form-control" >
</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>
------------------------------------------------------------------------------------------------------------
登录
<form class="form-horizontal" method="post" action="${pageContext.request.contextPath }/user?method=login">
<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="inputPassword3" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="inputPassword3" placeholder="请输入验证码">
</div>
<div class="col-sm-3">
<img src="${pageContext.request.contextPath}/image/captcha.jhtml"/>
</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.username }:您好
<li><a
href="${pageContext.request.contextPath }/user?method=loginUI">我的订单</a></li>
<li><a
href="${pageContext.request.contextPath }/user?method=logout">退出</a></li>
</c:if>
<li><a href="cart.htm">购物车</a></li>
</ol>
</div>
-------------------------------------------------------------------------------------------------------------
Fileter过滤 统一编码
package com.feizhu.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();
}
}
--------------------------------------------------------------------------------------------------------------
User实体类
package com.feizhu.domain;
import java.util.Date;
public class User {
/**
* 用户实体
*/
private String uid;
private String username;
private String password;
private String name;
private String email;
private String telephone;
private Date birthday;
private String sex;
private Integer state = 0; // 激活状态 1:激活 0:未激活
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date 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;
}
}
--------------------------------------------------------------------------------------------------------------
UserServlet:
package com.feizhu.web.servlet;
import java.io.IOException;
import java.sql.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import com.feizhu.constant.Constant;
import com.feizhu.domain.User;
import com.feizhu.myconventer.MyConventer;
import com.feizhu.service.UserService;
import com.feizhu.service.impl.UserServiceImpl;
import com.feizhu.utils.MD5Utils;
import com.feizhu.utils.UUIDUtils;
/**
* 与用户相关的servlet
*/
public class UserServlet extends BaseServlet {
/**
* 跳转到注册页面
*
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String registUI(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
return "/jsp/register.jsp";
}
/**
* 跳转到登录页面
*
* @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
* @throws Exception
*/
public String regist(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 封装数据
User user = new User();
// 注册自定义转换器
ConvertUtils.register(new MyConventer(), Date.class);
BeanUtils.populate(user, request.getParameterMap());
// 设置用户id
user.setUid(UUIDUtils.getId());
// 设置激活码
user.setCode(UUIDUtils.getCode());
// 使用MD5进行密码加密
user.setPassword(MD5Utils.md5(user.getPassword()));
// 调用service完成注册
UserService s = new UserServiceImpl();
s.regist(user);
// 页面请求转发
request.setAttribute("msg", "用户注册已成功,请去邮箱激活吧");
return "/jsp/msg.jsp";
}
/**
* 用户激活
*
* @param request
* @param response
* @return
* @throws Exception
*/
public String active(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取激活码
String code = request.getParameter("code");
// 调用service 完成激活
UserService s = new UserServiceImpl();
User user = s.active(code);
System.out.println(code);
System.out.println(user);
if (user == null) {
// 通过激活码没有找到用户
request.setAttribute("msg", "请重新激活");
} else {
// 增加信息
request.setAttribute("msg", "激活成功");
}
// 请求转发到msg.jsp
return "/jsp/msg.jsp";
}
public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
//接受参数
String username=request.getParameter("username");
String password=request.getParameter("password");
//使用MD5进行密码加密
password=MD5Utils.md5(password);
//调用service完成登录
UserService s=new UserServiceImpl();
User user=s.login(username,password);
//判断用户是否存在
if(user==null) {
//用户名和密码不匹配
request.setAttribute("msg","用户名和密码不匹配" );
return "/jsp/login.jsp";
}else {
//判断用户是否激活
if(Constant.USER_IS_ACTIVE!=user.getState()) {
request.setAttribute("msg","用户未激活");
return "/jsp/login.jsp";
}
}
//将user放入session中 重定向
request.getSession().setAttribute("user",user);
response.sendRedirect(request.getContextPath()+"/"); //store
return null;
}
public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
//干掉session
request.getSession().invalidate();
//重定向
response.sendRedirect(request.getContextPath());
//处理自动登录
return null;
}
}
---------------------------------------------------------------------------------------------------------------------
Service
UserService
package com.feizhu.service;
import com.feizhu.domain.User;
public interface UserService {
void regist(User user)throws Exception;
User active(String code)throws Exception;
User login(String username, String password)throws Exception;
}
UserServiceImpl
package com.feizhu.service.impl;
import com.feizhu.dao.UserDao;
import com.feizhu.dao.impl.UserDaoImpl;
import com.feizhu.domain.User;
import com.feizhu.service.UserService;
import com.feizhu.utils.MailUtils;
public class UserServiceImpl implements UserService {
/*
* 用户注册 (non-Javadoc)
*
* @see com.feizhu.service.UserService#regist()
*/
@Override
public void regist(User user) throws Exception {
UserDao dao = new UserDaoImpl();
dao.add(user);
// 发送邮件
// email:收件人地址
// emailMsg:邮件的内容
String emailMsg = "欢迎您成为我们的一员,<a href='http://localhost:8080/webuser/user?method=active&code=" + user.getCode()
+ "'>点此激活</a>";
System.out.println(user.getCode());
MailUtils.sendMail(user.getEmail(), emailMsg);
}
/**
* 用户激活
*
* @throws Exception
*/
@Override
public User active(String code) throws Exception {
UserDao dao = new UserDaoImpl();
// 通过code获取一个用户
User user = dao.getByCode(code);
System.out.println(user);
// 判断用户是否为空
if (user == null) {
return null;
}
// 修改用户状态
// 将用户的状态设置为1
user.setState(1);
dao.update(user);
return user;
}
/**
* 用户登录
*/
@Override
public User login(String username, String password) throws Exception {
UserDao dao = new UserDaoImpl();
User user = dao.getByUsernameAndPwd(username, password);
return user;
}
}
---------------------------------------------------------------------------------------------------------
Dao
UserDao 接口
package com.feizhu.dao;
import com.feizhu.domain.User;
public interface UserDao {
void add(User user) throws Exception;
User getByCode(String code)throws Exception;
void update(User user)throws Exception;
User getByUsernameAndPwd(String username, String password)throws Exception;
}
-------
UserDaoImpl
package com.feizhu.dao.impl;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.feizhu.dao.UserDao;
import com.feizhu.domain.User;
import com.feizhu.utils.DataSourceUtils;
public class UserDaoImpl implements UserDao {
/*
* 用户注册 (non-Javadoc)
*
* @see com.feizhu.dao.UserDao#add(com.feizhu.domain.User)
*/
@Override
public void add(User user) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user value(?,?,?,?,?,?,?,?,?,?);";
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());
String sql = "update user set username=?,password=?,name=?,email=?,birthday=?,state=?,code=? where uid=?";
qr.update(sql, user.getUsername(), user.getPassword(), user.getName(), user.getEmail(), user.getBirthday(),
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);
}
}
--------------------------------------------------------------------------------------------------------------
package com.feizhu.constant;
public interface Constant {
int USER_IS_ACTIVE=1;
}
-----------------
日期转换类
package com.feizhu.myconventer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
public class MyConventer implements Converter{
@Override
public Object convert(Class clazz, Object value) {
//class要转成的类型
//object 页面上传入的值
//将object 转换成date
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
Date date=sdf.parse((String)value);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
工具辅助类
-------------------------------------------------------
package com.feizhu.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceUtils {
private static ComboPooledDataSource ds = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl=new ThreadLocal<>();
/**
* 从线程中获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
//从线程中获取conneciton
Connection conn = tl.get();
if(conn==null){
conn=ds.getConnection();
//和当前线程绑定
tl.set(conn);
}
return conn;
}
// 获取数据源
public static DataSource getDataSource() {
return ds;
}
// 释放资源
public static void closeResource( Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
}
// 释放资源
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResource(st, rs);
closeConn(conn);
}
// 释放 connection
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
//和线程解绑
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
// 释放 statement ctrl + shift + f 格式化代码
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
// 释放结果集
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
//开启事务
public static void startTransaction() throws SQLException{
getConnection().setAutoCommit(false);
}
/**
* 事务提交且释放连接
*/
public static void commitAndClose(){
Connection conn = null;
try {
conn=getConnection();
//事务提交
conn.commit();
//关闭资源
conn.close();
//解除版定
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 事务回滚且释放资源
*/
public static void rollbackAndClose(){
Connection conn = null;
try {
conn=getConnection();
//事务回滚
conn.rollback();
//关闭资源
conn.close();
//解除版定
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-------------------------------------------------------------------------------------------------
package com.feizhu.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
//设置发送的协议
props.setProperty("mail.transport.protocol", "SMTP");
//设置发送邮件的服务器
props.setProperty("mail.host", "localhost");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//设置发送人的帐号和密码
return new PasswordAuthentication("service", "123");
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
//设置发送者
message.setFrom(new InternetAddress("service@store.com"));
//设置发送方式与接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
//设置邮件主题
message.setSubject("用户激活");
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
//设置邮件内容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
}
------------------------------------------------------------------------------------------
package com.feizhu.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
* 使用md5的算法进行加密
*/
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
}
----------------------------------------------------------------------------------------------------
package com.feizhu.utils;
import java.util.UUID;
public class UUIDUtils {
/**
* 随机生成id
* @return
*/
public static String getId(){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
/**
* 生成随机码
* @return
*/
public static String getCode(){
return getId();
}
public static void main(String[] args) {
System.out.println(getId());
}
}
备注:由于个人原因,本博客暂停更新。如有问题可联系本人,本人提供技术指导、学习方向、学习路线。本人微信wlp1156107728(添加注明来意) QQ1156107728(添加注明来意)