最终实现的效果如下:
登录首页:
注册页:
忘记密码页:
用户列表页:
首先建表,表名user:
然后在idea中导入ssm依赖:【pom.xml下,注意导入邮箱验证依赖包】
<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.qcby</groupId><artifactId>SSMDemo1</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><properties><spring.version>5.0.2.RELEASE</spring.version><slf4j.version>1.6.6</slf4j.version><log4j.version>1.2.12</log4j.version><mysql.version>5.1.6</mysql.version><mybatis.version>3.4.5</mybatis.version><jackson.version>2.9.4</jackson.version></properties><dependencies><!--spring--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.6.8</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.0</version><scope>provided</scope></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!--log start--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency><!-- log end--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><!--连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.10</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.2.3</version></dependency><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring4</artifactId><version>3.0.9.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.1.10.RELEASE</version></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.1</version></dependency></dependencies><build><finalName>ssm</finalName><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding><showWarnings>true</showWarnings></configuration></plugin></plugins></pluginManagement><plugins><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.5</version><!--告诉插件,配置文件所在的位置--><configuration><configurationFile>src/main/resources/mbg.xml</configurationFile><verbose>true</verbose><overwrite>true</overwrite></configuration></plugin></plugins></build></project>
创建所需目录:
在spring.xml中配置相关配置:
<context:component-scan base-package="com.qcby"/><!--com.qcby是包名--><!--加载数据库配置文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置数据库连接池--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="pwd" value="${jdbc.pwd}"/></bean><!--spring整合mybatis--><bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据库连接池--><property name="dataSource" ref="dataSource"/><!--扫描entity,配置model包下类的别名--><property name="typeAliasesPackage" value="com.qcby.model"/><!--扫描sql配置文件,mapper文件夹中的xml文件--><property name="mapperLocations" value="classpath:mapper/*.xml"/><!--扫描sqlMapConfig文件--><property name="configLocation" value="classpath:SqlMapConfig.xml"/></bean><!--配置扫描Dao接口包,动态实现Dao接口,注入到ioc容器--><bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.qcby.dao"/></bean>
其中加载的数据库配置文件jdbc.properties中需要添加:【其中login是表名】
在springmvc.xml中添加相关配置:
<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd /schema/context /schema/context/spring-context.xsd /schema/mvc /schema/mvc/spring-mvc.xsd"><!--spring开启对注解的扫描--><context:component-scan base-package="com.qcby"/><!--QQ发送邮箱验证码--><!--读取属性文件--><context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/><!--配置邮件接口--><bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="${mail.smtp.host}"/><property name="username" value="${mail.smtp.username}"/><property name="pwd" value="${mail.smtp.pwd}"/><property name="defaultEncoding" value="${mail.smtp.defaultEncoding}"/><property name="javaMailProperties"><props><prop key="mail.smtp.auth">${mail.smtp.auth}</prop><prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop></props></property></bean><!--处理映射器--><bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/><!--处理器适配器--><bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/><!--配置视图解析器--><bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"><property name="order" value="1"/><property name="characterEncoding" value="UTF-8"/><property name="templateEngine" ref="templateEngine"/></bean><!-- templateEngine --><bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"><property name="templateResolver" ref="templateResolver"/></bean><bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"><property name="prefix" value="/html/" /><property name="suffix" value=".html" /><property name="templateMode" value="HTML5"/></bean><!--开启Spring对SpringMVC的支持--><mvc:annotation-driven/><!--处理静态资源--><mvc:default-servlet-handler/></beans>
其中加载的数据库配置文件mail.properties中需要添加:
要想其中的授权码需要先打开QQ邮箱的smtp服务
打开自己的邮箱后,找到邮箱的设置-账户
找到其中的服务
将POP3/SMTP服务和IMAP/SMTP服务两个设置打开,之后点击生成授权码。
配置文件添加完成后,开始进入正文:
首先,在model文件夹里写类【User.java】:
public class User {private Integer id;private String username;private String pwd;private String email;public User(){}public User(int id, String username, String pwd,String email) {this.id = id;this.username = username;this.pwd= pwd;this.email=email;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return pwd;}public void setPassword(String pwd) {this.pwd= pwd;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", pwd='" + pwd+ '\'' +", email='" + email + '\'' +'}';}}
发送邮箱所需的工具类:
public class SendMail {// 发件人的邮箱账号如:xxx@public static String sendEmailAccount = "xxx@";// 发件人的邮箱的授权码(自己在邮箱服务器中开启并设置)public static String sendEmailPassword = "iumoonirfdeadhce";// 发件人邮箱的SMTP服务器地址,如:,我使用的是qq邮箱所以如下:public static String sendEmailSMTPHost = "";// 收件人的邮箱账号// public static String receiveMailAccount = "xxx@";// 把发送邮件封装为函数,参数为收件人的邮箱账号和要发送的内容public void sendMail(String receiveMailAccount, String mailContent) {// 创建用于连接邮件服务器的参数配置Properties props = new Properties();// 设置使用SMTP协议props.setProperty("mail.transport.protocol", "smtp");// 设置发件人的SMTP服务器地址props.setProperty("mail.smtp.host", sendEmailSMTPHost);// 设置需要验证props.setProperty("mail.smtp.auth", "true");// 根据配置创建会话对象, 用于和邮件服务器交互Session session = Session.getInstance(props);// 设置debug模式,便于查看发送过程所产生的日志session.setDebug(true);try {// 创建一封邮件MimeMessage message = createMimeMessage(session, sendEmailAccount, receiveMailAccount, mailContent);// 根据 Session 获取邮件传输对象Transport transport = session.getTransport();transport.connect(sendEmailAccount, sendEmailPassword);// 发送邮件, 发到所有的收件地址, 通过message.getAllRecipients() 可以获取到在创建邮件对象时添加的所有收件人transport.sendMessage(message, message.getAllRecipients());// 关闭连接transport.close();} catch (NoSuchProviderException e) {e.printStackTrace();} catch (MessagingException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/**** @param session* 和服务器交互的会话* @param sendMail* 发件人邮箱* @param receiveMail* 收件人邮箱* @return* @throws Exception*/public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,String mailContent) throws Exception {// 创建一封邮件MimeMessage message = new MimeMessage(session);// 设置发件人姓名和编码格式message.setFrom(new InternetAddress(sendMail, "登陆验证系统", "UTF-8"));// 收件人message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "尊敬的用户", "UTF-8"));// 设置邮件主题message.setSubject("邮箱提醒", "UTF-8");// 设置邮件正文message.setContent(mailContent, "text/html;charset=UTF-8");// 设置发件时间message.setSentDate(new Date());// 保存设置message.saveChanges();return message;}}
然后在mapper文件夹里写sql:【UserDao.xml】
<mapper namespace="com.qcby.dao.UserDao"><select id="findOne" parameterType="com.qcby.model.User" resultType="com.qcby.model.User">SELECT * FROM user where username=#{username} and pwd=#{pwd}</select><insert id="register" parameterType="com.qcby.model.User" >insert into user(username,pwd,email) values(#{username},#{pwd},#{email})</insert><select id="check" resultType="com.qcby.model.User" parameterType="com.qcby.model.User">select * from user where username=#{username}</select><select id="userlist" resultType="com.qcby.model.User">select * from user</select><select id="getId" resultType="com.qcby.model.User" parameterType="com.qcby.model.User">select * from user where email=#{email}</select></mapper>
dao接口层和service里面的接口是一样的代码:
public interface UserDao {//用户登录User findOne(User user);//用户注册int register(User user);//注册时的重名检测User check(String username);List<User> userlist();User getId(String email);}
UserServiceImpl来实现UserService:【一定注意加上@Service注解】
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Overridepublic User findOne(User user) {return this.userDao.findOne(user);}@Overridepublic int register(User user) {return this.userDao.register(user);}@Overridepublic User check(String username) {return this.userDao.check(username);}@Overridepublic List<User> userlist() {return this.userDao.userlist();}@Overridepublic User getId(String email) {return this.userDao.getId(email);}}
然后在controller层实现相应功能:
@Controller@RequestMapping("/user")public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/login")@ResponseBodypublic String login(User user) {User users = userService.findOne(user);System.out.println("qqqqqqqq");String data = "";// model.addAttribute("msg", u);if (users != null) {data = "{\"code\":\"200\",\"msg\":\"success\"}";} else {data = "{\"code\":\"999\",\"msg\":\"error\"}";}System.out.println(data);return data;}@RequestMapping("/userlist")@ResponseBodypublic List<User> userlist() {List<User> data=userService.userlist();return data;}@RequestMapping("/register")@ResponseBodypublic String register(User user) {User u = userService.check(user.getUsername());User e=userService.getId(user.getEmail());String data = "";if ((u == null) && (e==null)){userService.register(user);data = "{\"code\":\"200\",\"msg\":\"success\"}";}else{data = "{\"code\":\"999\",\"msg\":\"error\"}";}return data;}//找回密码@RequestMapping("/find")@ResponseBodypublic void doPost( String email, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取用户的邮箱// 实例化用户对象User user = null;// 实例化一个发送邮件的对象SendMail mySendMail = new SendMail();// 根据页面获取到的邮箱找到该用户信息user = userService.getId(email);System.out.println(user.getPassword());if(user!=null){mySendMail.sendMail(email, "您的密码为:" + user.getPassword());}}//发送验证码@RequestMapping("/send")@ResponseBodypublic String sendEmail(HttpSession httpSession, String username, String email, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取用户的邮箱// 实例化用户对象User user = null;// 实例化一个发送邮件的对象SendMail mySendMail = new SendMail();//生成六位数验证码String Captcha = String.valueOf(new Random().nextInt(899999) + 100000);//存储验证码httpSession.setAttribute("Captcha", Captcha);SimpleMailMessage message = new SimpleMailMessage();//邮件主题message.setSubject("验证码");//邮件内容message.setText("验证码:" + Captcha);mySendMail.sendMail(email, "您的验证码为:" + Captcha);return Captcha;}}
最后写前端,前端文件这样放置:
首先是登录页:【index.html】
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="css/index.css"><script src="js/jquery.min.js"></script><script src="js/jquery.cookie.js"></script><script src="layer/layer.js"></script></head><body><div class="main"><div class="top">权限认证系统</div><div class="line"></div><div class="bottom"><!-- <form action="/user/login" method="post">--><div class="item"><span>账户:</span><input type="text" id="username"></div><div class="item"><span>密码:</span><input type="pwd" id="pwd"></div><div class="items"><a href="register.html"><input type="button" value="注册" id="btn1"></a><input type="button" value="登录" id="btn2" onclick="login()"><!--<button value="btn2" onclick="login()">登录</button>--></div><div class="item2"><a href="forget.html">忘记密码?点我</a></div><!-- </form>--></div></div></body><script>function login(){var username=$("#username").val();var pwd=$("#pwd").val();console.log("666");$.ajax({url:"/user/login",dataType:'json',data:{"username":username,"pwd":pwd},type:"get",success:function(data) {console.log(666)if(data.code==200) {layer.msg("登录成功",{time:2000,anim:6},function(){$.cookie("username",username)location.href = "html/content.html";})}else {layer.msg("登陆失败",{anim:6})}}});}</script></html>
然后是注册页:
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="css/register.css"><script src="js/jquery.min.js"></script><script src="layer/layer.js"></script></head><body><div class="main"><div class="top">权限认证系统</div><div class="line"></div><div class="bottom"><!-- <form action="/user/login" method="post">--><div class="item"><span>账户:</span><input type="text" id="username"></div><div class="item"><span>密码:</span><input type="pwd" id="pwd"></div><div class="item"><span>邮箱:</span><input type="text" id="email"></div><div class="item"><span>验证码:</span><input type="text" id="mark"><input type="button" id="getMark" value="获取验证码" onclick="send()"></div><div class="items"><a href="index.html"><input type="button" value="登录" id="btn2"></a><input type="button" value="注册" id="btn1" onclick="register()"><!--<button value="btn2" onclick="login()">登录</button>--></div><div class="item2"><a href="forget.html">忘记密码?点我</a></div><!-- </form>--></div></div></body><script>var ma="";function send() {var username=$("#username").val();var email=$("#email").val();$.ajax({url:"/user/send",dataType: "json",data:{"username":username,"email":email},type: "get",success:function (Captcha) {ma=Captcha;layer.msg("已发送",{time:2000,anim:6});}})}function register(){var mark=$("#mark").val();if(mark==ma&&mark!=""&&mark!=null){var username=$("#username").val();var pwd=$("#pwd").val();var email=$("#email").val();console.log("666");$.ajax({url:"/user/register",dataType:'json',data:{"pwd":pwd,"email":email},type:"get",success:function(data) {console.log("666");if(data.code==200){layer.msg("注册成功",{time:2000,anim:6},function(){location.href = "../index.html";})}else{layer.msg("该账户或该邮箱已注册过",{time:2000,anim:6})}}});}else{layer.msg("验证码错误",{time:2000,anim:6})}}</script></html>
忘记密码页:
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="css/forget.css"><script src="js/jquery.min.js"></script><script src="layer/layer.js"></script></head><body><div class="main"><div class="top">权限认证系统</div><div class="line"></div><div class="bottom"><!-- <form action="/user/login" method="post">--><div class="item"><span>邮箱:</span><input type="text" id="email"></div><div class="item"><span>密码:</span><input type="text" id="mark"><input type="button" id="get" value="找回密码" onclick="sendemail()"></div><div class="items"><a href="index.html"><input type="button" value="登录" id="btn2"></a><a href="register.html"><input type="button" value="注册" id="btn1" onclick="register()"></a><!--<button value="btn2" onclick="login()">登录</button>--></div><div class="item2"><a href="forget.html">忘记密码?点我</a></div><!-- </form>--></div></div></body><script>function sendemail(){var email=$("#email").val();console.log("666");$.ajax({url:"/user/find",dataType:'json',data:{"email":email},type:"get",async: false,success:function(data) {layer.msg("已发送",{time:2000,anim:6})console.log("666");// $.cookie("username",username);}});}</script></html>
最后是显示用户列表页:
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="../css/content.css"><script src="../js/jquery.min.js"></script><script src="../js/jquery.cookie.js"></script><script src="../layer/layer.js"></script></head><body><!--th:text="${msg}"--><div><div class="container"><div class="head"><div class="head_box"><span>权限认证系统</span><div><span class="account"></span><a href="../index.html"><input type="button" id="logout" value="退出"></a></div></div></div><div class="main"><div class="top_box"></div><table class="table_box"><thread><tr><th>用户id</th><th>用户名</th><th>密码</th><th>邮箱</th></tr></thread><tbody id="content"></tbody></table><ul class="pagenation"></ul></div></div></div></body><script>$(function(){//初始化登录账号$(".username").html($.cookie("username"))// var pageSize=5;//定义加载数据的函数function loadData(){$.ajax({url:"/user/userlist",// url:"userlist?action=getWhere&page="+page+"&pageSize="+pageSize,type:"get",success:function(data){$("#content").empty();//把内容置空if(data.length<1){$("#content").append("<tr><td colspan='4'>暂无数据</td></tr>");return;}console.log(data);//加载数据到页面显示出来for(var i=0;i<data.length;i++){$("#content").append("<tr>"+"<td>"+data[i].id+"</td>"+"<td>"+data[i].username+"</td>"+"<td>"+data[i].pwd+"</td>"+"<td>"+data[i].email+"</td>"+"</tr>");}// if(isPage){////加载分页函数//loadPage();// }}})}//加载数据loadData();})</script></html>
==============================结束线=====================================
注意:由于我写的p a s s w o r d 涉及敏感发布不了,所以改成了pwd,记得修改