ssm小项目:实现用户登录 、注册新用户、修改密码功能
项目结构:
具体搭建步骤:
创建c_user表:
-- auto-generated definition
create table c_user
(
userNo int auto_increment
primary key,
userName varchar(20) not null,
pass varchar(20) not null,
address varchar(50) not null,
phoneNum varchar(20) not null,
price varchar(20) not null,
createTime timestamp default CURRENT_TIMESTAMP not null comment '创建时间'
)
;
1.配置spring相关文件,创建applicationContext.xml
2.spring-mvc.xml
3.spring-mybatis.xml
classpath:jdbc.properties
4.jdbc.properties配置数据库源
#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useSSL=false
jdbc.username=root
jdbc.password=root
#c3p0连接池信息
c3p0.minPoolSize=10
c3p0.maxPoolSize=100
#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数
c3p0.acquireIncrement=3
#定义在从数据库获取新连接失败后重复尝试的次数
c3p0.acquireRetryAttempts=60
#两次连接中间隔时间,单位毫秒
c3p0.acquireRetryDelay=1000
#连接关闭时默认将所有未提交的操作回滚
c3p0.autoCommitOnClose=false
#当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限
c3p0.checkoutTimeout=3000
#每120秒检查所有连接池中的空闲连接。Default: 0
c3p0.idleConnectionTestPeriod=120
#最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
c3p0.maxIdleTime=600
#如果设为true那么在取得连接的同时将校验连接的有效性。Default: false
c3p0.testConnectionOnCheckin=false
#如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
c3p0.maxStatements=8
#maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
c3p0.maxStatementsPerConnection=5
#自动超时回收Connection
c3p0.unreturnedConnectionTimeout=25
5.web.xml配置
Archetype Created Web Application
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
springmvc
/
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
6.持久层代码
UserMapper
package dao;
import beans.UserBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Administrator on 2018/9/5.
*/
@Repository
public interface UserMapper {
int InsUserList(UserBean userBean);//用户注册
int UpUserPass(@Param("username") String username,//修改密码
@Param("pass") String pass);
List selLogin(@Param("name") String name,//用户登录
@Param("pass") String pass);
}
userMapper.xml
INSERT INTO c_user
(userName, pass, address, phoneNum,price)
VALUES (#{userName,jdbcType=VARCHAR},
#{pass,jdbcType=VARCHAR},
#{address,jdbcType=VARCHAR},
#{phoneNum,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR});
UPDATE c_user
SET pass=#{pass,jdbcType=VARCHAR}
WHERE username=#{username,jdbcType=VARCHAR};
SELECT userNo
FROM c_user
WHERE userName=#{name,jdbcType=VARCHAR}
AND pass=#{pass,jdbcType=VARCHAR};
SendMapper
package dao;
import beans.UserBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Administrator on 2018/9/6.
*/
@Repository
public interface SendMapper {
List loginList(@Param("name") String name,
@Param("pNum") String phone);
}
sendMapper.xml
SELECT *
FROM c_user
WHERE userName=#{name,jdbcType=VARCHAR}
and phoneNum=#{pNum,jdbcType=VARCHAR};
7.业务层代码实现
IUserService.java
package service;
import beans.UserBean;
import java.util.List;
/**
* Created by Administrator on 2018/9/5.
*/
public interface IUserService {
int InsUserList(UserBean userBean);
void UpUserPass(String username, String pass);
boolean selLogin(String name,String pass);
}
UserServiceImp.java
package service.imp;
import beans.UserBean;
import dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.IUserService;
import java.util.List;
/**
* Created by Administrator on 2018/9/5.
*/
@Service
public class UserServiceImp implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public int InsUserList(UserBean userBean) {
return userMapper.InsUserList(userBean);
}
@Override
public void UpUserPass(String username, String pass) {
userMapper.UpUserPass(username, pass);
}
@Override
public boolean selLogin(String name, String pass) {
List userBeanList = userMapper.selLogin(name, pass);
return userBeanList.size() != 0;
}
}
IPhoneService.java
package service;
/**
* Created by Administrator on 2018/9/6.
*/
public interface IPhoneService {
boolean loginList(String name, String phone);
}
PhoneServiceImp.java
package service.imp;
import beans.UserBean;
import dao.SendMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.IPhoneService;
import java.util.List;
/**
* Created by Administrator on 2018/9/6.
*/
@Service
public class PhoneServiceImp implements IPhoneService {
@Autowired
private SendMapper sendMapper;
@Override
public boolean loginList(String name, String phone) {
List login = sendMapper.loginList(name,phone);
int i = login.size();
System.out.print(i);
return i != 0;
}
}
8、控制层功能实现
UserController.java
package controllers;
import beans.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import service.IUserService;
import utils.ResponseUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Administrator on 2018/9/5.
*/
@Controller
public class UserController {
@Autowired
private IUserService iUserService;
@RequestMapping(value = "/InsUserList",method = RequestMethod.GET)
public void InsUserList(UserBean userBean, HttpServletRequest request,HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
String address = request.getParameter("address");
userBean.setUserName(new String(userName.getBytes("iso-8859-1"),"UTF-8"));
userBean.setAddress(new String(address.getBytes("iso-8859-1"),"UTF-8"));
int flag = iUserService.InsUserList(userBean);
if (flag <= 0) {
ResponseUtil.write(response,"error!");
}
ResponseUtil.write(response,"注册成功!");
}
@RequestMapping(value = "/login",method = RequestMethod.GET)
public void login(HttpServletRequest request,HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
name = new String(name.getBytes("iso-8859-1"),"UTF-8");
pass = new String(pass.getBytes("iso-8859-1"),"UTF-8");
if (iUserService.selLogin(name,pass)) {
ResponseUtil.write(response,"登录成功!");
}
ResponseUtil.write(response,"用户名或密码错误!");
}
}
SendController.java
package controllers;
import beans.UserBean;
import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.IPhoneService;
import service.IUserService;
import utils.SendUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
/**
* Created by Administrator on 2018/9/6.
*/
@Controller
public class SendController {
@Autowired
private IPhoneService iPhoneService;
@Autowired
private IUserService iUserService;
@ResponseBody
@RequestMapping(value = "/sendme", method = RequestMethod.GET)
public ModelAndView sendme(@RequestParam(value = "name") String name,@RequestParam(value = "phone") String phone, HttpServletRequest request) throws HttpException, IOException {
ModelAndView model = new ModelAndView();
String str = request.getParameter("name");
name = new String(str.getBytes("iso-8859-1"),"UTF-8");
boolean flag = iPhoneService.loginList(name,phone);
if (flag) {
HashMap hashMap = SendUtil.getMessageStatus(phone);
String result = hashMap.get("result");
if (result.trim().equals("1")) {
String code = hashMap.get("code");
HttpSession session = request.getSession();
session.setAttribute(phone+"code",code);
session.setMaxInactiveInterval(60*5);
model.addObject("flag","发送成功");
} else {
model.addObject("flag", "发送失败");
}
model.addObject("name",name);
model.addObject("phone",phone);
model.setViewName("forgotPass.jsp");
} else {
model.addObject("flag1", "用户名或手机号码不正确");
model.addObject("name", name);
model.addObject("phone",phone);
model.setViewName("forgotPass.jsp");
}
return model;
}
@RequestMapping(value = "/comparecode", method = RequestMethod.GET)
public ModelAndView comparecode(@RequestParam(value = "code") String code, UserBean userBean,HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView model = new ModelAndView();
String str1 = request.getParameter("name");
String str2 = request.getParameter("pass");
String name = new String(str1.getBytes("iso-8859-1"), "UTF-8");
iUserService.UpUserPass(name,str2);
HttpSession session = request.getSession();//设置session
String sessionCode = (String) session.getAttribute(userBean.getPhoneNum()+"code");
System.out.println(sessionCode);
if (code.equals(sessionCode)) {
model.addObject("result", "修改密码成功");
} else {
model.addObject("result", "验证码不正确");
model.setViewName("forgotPass.jsp");
}
model.setViewName("result.jsp");
return model;
}
}
9、其中的工具类
RandomUtil得到4位数的验证码
package utils;
/**
* Created by Administrator on 2018/9/6.
*/
public class RandomUtil {
//随机得到4位数
public static int getRandNum() {
return (int)((Math.random()*9+1)*1000);
}
}
SendUtil.java 连接第三方平台 短信模板 生成验证码
package utils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.IOException;
import java.util.HashMap;
/**
* Created by Administrator on 2018/9/6.
*/
public class SendUtil {
public static HashMap getMessageStatus(String phone) throws IOException {
HashMap hashMap = new HashMap<>();
//第三方平台网站地址 http://www.webchinese.com.cn/User/?action=pay
PostMethod post = new PostMethod("http://utf8.api.smschinese.cn/");
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
String randMun = String.valueOf(RandomUtil.getRandNum());
//短信模板
NameValuePair[] data ={
new NameValuePair("Uid", "噼噼啪啪"), //sms短信通 注册的用户名
new NameValuePair("Key", "d41d8cd98f00b204e980"), //密匙
new NameValuePair("smsMob",phone),//要发送的手机号
new NameValuePair("smsText","验证码:"+randMun+",发送")//短信内容
};
post.setRequestBody(data);
HttpClient client = new HttpClient();
client.executeMethod(post);
//获取http头
Header[] headers = post.getResponseHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:"+statusCode);
for(Header h:headers){
System.out.println(h.toString());
}
//获取返回消息
String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
System.out.println(result); //打印返回消息状态
//将返回消息和6位数验证码放入到map列表里面
hashMap.put("result", result);
hashMap.put("code", randMun);
//断开与第三方平台的连接
post.releaseConnection();
return hashMap;
}
}
10.jsp页面实现
login.jsp登录页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/9/7
Time: 11:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%--启用el表达式--%>
<%@ page isELIgnored="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
Title
registerUser.jsp用户注册
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%--启用el表达式--%>
<%@ page isELIgnored="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
用户注册
forgotPass.jsp找回密码
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%--启用el表达式--%>
<%@ page isELIgnored="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Insert title here
result.jsp返回结果
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%--启用el表达式--%>
<%@ page isELIgnored="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
Insert title here
${result}
原文:https://blog.csdn.net/maxPoolSize/article/details/82494043