【项目分享~写给应届生的一篇文章】基于Web企业招聘网站 ~~ 登录注册设计

背景

适合人群: 应届生
推荐:可直接做为毕业设计项目,开发架构简单,按照统一的规范开发,容易上少
原因:这个项目涉及到SSM三大框架,所以刚刚入门JavaWeb的同学可能不大适合,缺少太多必备的知识,导致学习这个项目事倍功半。如果你已经是有一两年工作经验开发者,这个项目对你的level太低了,也不推荐哦
每 年 的 话 我 都 会 指 导 一 些 应 届 生 过 计 算 机 毕 业 设 计 , 在 这 个 过 程 中 , 很 多 人 都 会 问 到 以 下 问 题 : \color{red}每年的话我都会指导一些应届生过计算机毕业设计,在这个过程中,很多人都会问到以下问题: :
登录注册是如何实现了?
如何实现可以发邮件?
账户激活如何实现?
“ 基 于 W e b 企 业 招 聘 网 站 ” \color{red}“基于Web企业招聘网站” Web这篇文章为例,今天给大家讲讲这个:登录注册是如何实现的

小总结

你还在为大学最后的毕业设计而苦恼吗?
你还在面对毕业设计而无从下手吗?
你还在实习,但苦于没有时间做毕业设计吗?
适合应届生当做项目经验、或者毕设作品
小作者的随手之作,实现难度不难~~
这个项目,你值得拥有

项目演示视频分享

链接:https://pan.baidu.com/s/1bTrY4RUQWu8r6ttGpA_NwA
提取码:51ul
想要源码的可以私聊我,
亦或是加我qq:924155240
可指导毕设,稳过

项目截图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

登录权限设计

为了方便大家理解,我先把整个过程database->dao->service->controller整个流程的代码先贴出来

表结构设计

最核心的字段: username 和 password ,账号密码,isAudit是用来激活使用的
注册时,isAudit值为1,表示未激活,需要邮件激活后变为2,才可以登录使用

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL COMMENT '账号',
  `password` varchar(100) DEFAULT NULL,
  `isAudit` int(2) DEFAULT NULL COMMENT '是否审核',
  `register` datetime DEFAULT NULL COMMENT '注册时间',
  `qq` varchar(255) DEFAULT NULL COMMENT '关联qq号',
  `weixin` varchar(255) DEFAULT NULL COMMENT '关联微信号',
  `other` varchar(255) DEFAULT NULL COMMENT '其他信息',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;

代码

dao层

package com.xiaozheng.recruitment.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.xiaozheng.recruitment.pojo.User;
import com.xiaozheng.recruitment.pojo.query.UserCondition;

public interface UserMapper {
    
    
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    
    @Select("select * from user u where u.username = #{0}")
   	User selectUserByUsername(String username);
    
    @Select("select * from user u where u.username = #{0} and u.password = #{1}")
   	User selectUserByUsernameAndPassword(String username, String password);

	List<Map<String, Object>> listAllByCondition(UserCondition userCondition);
	@Update("update user u set u.isaudit = #{1} where u.id = #{0}")
	int tingyong(Integer id, int i);

	@Update("update user u set u.isaudit = #{0} where u.password = #{1}")
	void updateByBaseString(int i, String baseString);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xiaozheng.recruitment.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.xiaozheng.recruitment.pojo.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="isAudit" property="isaudit" jdbcType="INTEGER" />
    <result column="register" property="register" jdbcType="TIMESTAMP" />
    <result column="qq" property="qq" jdbcType="VARCHAR" />
    <result column="weixin" property="weixin" jdbcType="VARCHAR" />
    <result column="other" property="other" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, username, password, isAudit, register, qq, weixin, other
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{
    
    id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where id = #{
    
    id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.xiaozheng.recruitment.pojo.User" >
    insert into user (id, username, password, 
      isAudit, register, qq, 
      weixin, other)
    values (#{
    
    id,jdbcType=INTEGER}, #{
    
    username,jdbcType=VARCHAR}, #{
    
    password,jdbcType=VARCHAR}, 
      #{
    
    isaudit,jdbcType=INTEGER}, #{
    
    register,jdbcType=TIMESTAMP}, #{
    
    qq,jdbcType=VARCHAR}, 
      #{
    
    weixin,jdbcType=VARCHAR}, #{
    
    other,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.xiaozheng.recruitment.pojo.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="isaudit != null" >
        isAudit,
      </if>
      <if test="register != null" >
        register,
      </if>
      <if test="qq != null" >
        qq,
      </if>
      <if test="weixin != null" >
        weixin,
      </if>
      <if test="other != null" >
        other,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{
    
    id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{
    
    username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{
    
    password,jdbcType=VARCHAR},
      </if>
      <if test="isaudit != null" >
        #{
    
    isaudit,jdbcType=INTEGER},
      </if>
      <if test="register != null" >
        #{
    
    register,jdbcType=TIMESTAMP},
      </if>
      <if test="qq != null" >
        #{
    
    qq,jdbcType=VARCHAR},
      </if>
      <if test="weixin != null" >
        #{
    
    weixin,jdbcType=VARCHAR},
      </if>
      <if test="other != null" >
        #{
    
    other,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.xiaozheng.recruitment.pojo.User" >
    update user
    <set >
      <if test="username != null" >
        username = #{
    
    username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{
    
    password,jdbcType=VARCHAR},
      </if>
      <if test="isaudit != null" >
        isAudit = #{
    
    isaudit,jdbcType=INTEGER},
      </if>
      <if test="register != null" >
        register = #{
    
    register,jdbcType=TIMESTAMP},
      </if>
      <if test="qq != null" >
        qq = #{
    
    qq,jdbcType=VARCHAR},
      </if>
      <if test="weixin != null" >
        weixin = #{
    
    weixin,jdbcType=VARCHAR},
      </if>
      <if test="other != null" >
        other = #{
    
    other,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{
    
    id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.xiaozheng.recruitment.pojo.User" >
    update user
    set username = #{
    
    username,jdbcType=VARCHAR},
      password = #{
    
    password,jdbcType=VARCHAR},
      isAudit = #{
    
    isaudit,jdbcType=INTEGER},
      register = #{
    
    register,jdbcType=TIMESTAMP},
      qq = #{
    
    qq,jdbcType=VARCHAR},
      weixin = #{
    
    weixin,jdbcType=VARCHAR},
      other = #{
    
    other,jdbcType=VARCHAR}
    where id = #{
    
    id,jdbcType=INTEGER}
  </update>
  
  <!-- 以下是我自己写的方法 -->
  <select id="listAllByCondition" resultType="java.util.Map" parameterType="com.xiaozheng.recruitment.pojo.query.UserCondition">
 		SELECT u.id,u.username,u.weixin,u.qq,u.isaudit,u.register
   		FROM user u 
		<where>
			    <if test="username!=null and username!=''">  	 
			        and u.username like CONCAT('%', #{
    
    username}, '%') 
			    </if>
			    <if test="qq!=null and qq!=''">  	 
			        and u.qq like CONCAT('%', #{
    
    qq}, '%') 
			    </if>
			     <if test="weixin!=null and weixin!=''">  	 
			        and u.weixin like CONCAT('%', #{
    
    weixin}, '%') 
			    </if>
			    <if test="isaudit!=null and isaudit!=''">
			        and u.isaudit = #{
    
    isaudit}
			    </if>
   	   </where>
  </select>
</mapper>

pojo

package com.xiaozheng.recruitment.pojo;

import java.util.Date;

public class User {
    
    
    private Integer id;

    private String username;

    private String password;

    private Integer isaudit;

    private Date register;

    private String qq;

    private String weixin;

    private String other;

    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 == null ? null : username.trim();
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password == null ? null : password.trim();
    }

    public Integer getIsaudit() {
    
    
        return isaudit;
    }

    public void setIsaudit(Integer isaudit) {
    
    
        this.isaudit = isaudit;
    }

    public Date getRegister() {
    
    
        return register;
    }

    public void setRegister(Date register) {
    
    
        this.register = register;
    }

    public String getQq() {
    
    
        return qq;
    }

    public void setQq(String qq) {
    
    
        this.qq = qq == null ? null : qq.trim();
    }

    public String getWeixin() {
    
    
        return weixin;
    }

    public void setWeixin(String weixin) {
    
    
        this.weixin = weixin == null ? null : weixin.trim();
    }

    public String getOther() {
    
    
        return other;
    }

    public void setOther(String other) {
    
    
        this.other = other == null ? null : other.trim();
    }
}

service层

package com.xiaozheng.recruitment.service;

import java.util.List;
import java.util.Map;

import com.xiaozheng.recruitment.pojo.User;
import com.xiaozheng.recruitment.pojo.query.UserCondition;

public interface IUserService {
    
    

	public int insertUser(User user);
	
	public User selectUserByUsername(String username);
	
	public User selectUserByUsernameAndPassword(String username,String password);

	public List<Map<String, Object>> listAllByCondition(UserCondition userCondition);

	public int chongzhi(Integer id) throws Exception;

	public int tingyong(Integer id, int i);
}

package com.xiaozheng.recruitment.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaozheng.recruitment.dao.UserMapper;
import com.xiaozheng.recruitment.pojo.User;
import com.xiaozheng.recruitment.pojo.UserResume;
import com.xiaozheng.recruitment.pojo.query.UserCondition;
import com.xiaozheng.recruitment.service.IUserService;
import com.xiaozheng.recruitment.utils.MailUtils11;
import com.xiaozheng.recruitment.utils.MyMd5Utils;
@Service
@Transactional
public class UserServiceImpl implements IUserService {
    
    
	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 插入一条数据
	 */
	@Override
	public int insertUser(User user) {
    
    
		return userMapper.insert(user);
	}
	
	/**
	 * 
	 * 根据邮箱查找
	 */
	public User selectUserByUsername(String username) {
    
    
		// TODO Auto-generated method stub
		return userMapper.selectUserByUsername(username);
	}
	
	/**
	 * 根据邮箱+密码来查询数据库
	 */
	public User selectUserByUsernameAndPassword(String username,String password) {
    
    
		return userMapper.selectUserByUsernameAndPassword(username,password);
	}
	/**
	 * 关联用户的qq
	 * @param user
	 */
	public int updateAssociatedQq(User user) {
    
    
		//根据id查找出当前的对象
		User u = userMapper.selectByPrimaryKey(user.getId());
		u.setQq(user.getQq());
		return userMapper.updateByPrimaryKey(u);
		
	}
	/**
	 * 根据id查找当前用户信息
	 * @param userId
	 * @return
	 */
	public User selectByUserId(int userId) {
    
    
		return userMapper.selectByPrimaryKey(userId);
	}

	public int updateAssociatedWeixin(User user) {
    
    
		//根据id查找出当前的对象
		User u = userMapper.selectByPrimaryKey(user.getId());
		u.setWeixin(user.getWeixin());
		return userMapper.updateByPrimaryKey(u);
		
	}
	/**
	 * 修改用户密码
	 * @param user
	 */
	public int updatePassword(User user) {
    
    
		//根据id查找出当前的对象
		User u = userMapper.selectByPrimaryKey(user.getId());
		
		String baseString = MyMd5Utils.encodeByMD5(u.getUsername()+"-"+user.getPassword());
		
		u.setPassword(baseString);
		
		return userMapper.updateByPrimaryKey(u);
		
	}

	public List<Map<String, Object>> listAllByCondition(UserCondition userCondition) {
    
    
		// TODO Auto-generated method stub
		return userMapper.listAllByCondition(userCondition);
	}

	@Override
	public int chongzhi(Integer id) throws Exception {
    
    
		// TODO Auto-generated method stub
		User user = userMapper.selectByPrimaryKey(id);
		String baseString = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+"123456");
		user.setPassword(baseString);
		//发送邮件告诉对方
		MailUtils11.sendMail("小郑招聘系统提醒", user.getUsername(),  "密码重置通知","尊敬的用户,您的密码已经重置为'123456',为了您的安全,建议登录到官网网站修改个人密码。https://hongbin.albbkongbao.com/recruitmentWebsite/system/index");
		
		return userMapper.updateByPrimaryKey(user);
	}

	@Override
	public int tingyong(Integer id, int i) {
    
    
		// TODO Auto-generated method stub
		return userMapper.tingyong(id,i);
	}

	public void updateByBaseString(String baseString) {
    
    
		userMapper.updateByBaseString(1,baseString);
		
	}
	
}

controller层

package com.xiaozheng.recruitment.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.deser.Deserializers.Base;
import com.xiaozheng.recruitment.dao.UserMapper;
import com.xiaozheng.recruitment.pojo.User;
import com.xiaozheng.recruitment.pojo.UserResume;
import com.xiaozheng.recruitment.pojo.Workexperience;
import com.xiaozheng.recruitment.service.IApplayService;
import com.xiaozheng.recruitment.service.IWorkExperienceService;
import com.xiaozheng.recruitment.service.impl.UserResumeServiceImpl;
import com.xiaozheng.recruitment.service.impl.UserServiceImpl;
import com.xiaozheng.recruitment.utils.MailUtils11;
import com.xiaozheng.recruitment.utils.MyMd5Utils;
import com.xiaozheng.recruitment.utils.Response;
import com.xiaozheng.recruitment.utils.Response;

@Controller
@RequestMapping("/user")
public class UserController {
    
    
	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Autowired
	private UserResumeServiceImpl userResumeServiceImpl;
	
	@Autowired
	private IWorkExperienceService workExperienceService;
	
	@Autowired
	private IApplayService applayService;
	
	@RequestMapping("/toLogin")
	public @ResponseBody Response toLogin(User user,HttpServletRequest  request) {
    
    
		//1.0 声明需要返回的类型
		Response rep = new Response();
		//2.0 根据用户名+密码去检索数据库
		String basePassword = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+user.getPassword());
		User u = userServiceImpl.selectUserByUsernameAndPassword(user.getUsername(),basePassword);
		if(u!=null) {
    
    
			//3.0表示登陆成功
			if(u.getIsaudit() == 2) {
    
    
				//4.0 账号密码错误
				rep.setCode(-1);
				rep.setMsg("您的账户已经被冻结,请联系管理员[email protected]");
				return rep;
			}else if(u.getIsaudit() == 3){
    
    
				rep.setCode(-1);
				rep.setMsg("您登录的账户还没有激活,请到注册的邮箱上点击激活按钮");
				request.getSession().setAttribute("user", u);
				return rep;
			}else {
    
    
				rep.setCode(1);
				rep.setMsg("登陆成功");
				request.getSession().setAttribute("user", u);
				return rep;
			}
			
		}else {
    
    
			//4.0 账号密码错误
			rep.setCode(-1);
			rep.setMsg("账号或者密码错误,请重新输人");
			return rep;
		}
	}
	
	/**
	 * 用户注册
	 * @throws Exception 
	 */
	@RequestMapping("/register")
	public @ResponseBody Response insertUser(User user) throws Exception {
    
    
		//1.0 声明需要返回的类型
		Response rep = new Response();
		//判断邮箱是否存在
		User u = userServiceImpl.selectUserByUsername(user.getUsername());
		if(u!=null) {
    
    
			//返回错误信息,邮箱已存在
			rep.setCode(-1);
			rep.setMsg("邮箱已存在,您已经注册过我们网站,请返回登录");
			return rep;
		}
		user.setIsaudit(1);
		user.setRegister(new Date());
		String baseString = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+user.getPassword());
		user.setPassword(baseString);
		
		int i = userServiceImpl.insertUser(user);
		if(i > 0) {
    
    
			rep.setCode(1);
			rep.setMsg("完美注册,请到您的邮箱上激活,否则不允许登录");
			//MailUtils11.sendMail("招聘网站提醒", user.getUsername(), "账号激活", "您成功注册了小郑招聘网站,接下来点击下面按钮激活即可<br/>"+"http://localhost:8080/recruitmentWebsite/user/xiaochengxu/jihuo?baseString="+baseString);
			return rep;

		}else {
    
    
			rep.setCode(-1);
			rep.setMsg("程序有问题,请检查你的程序");
			return rep;
		}
	}
	
	/**
	 * 邮箱激活
	 */
	@RequestMapping("/xiaochengxu/jihuo")
	public String jihuo(String baseString) {
    
    
		//修改当前的状态即可
		userServiceImpl.updateByBaseString(baseString);
		return "user/jihuo";
	}
	
	/**
	 *  进入用户个人中心页面
	 */
	@RequestMapping("/memberResume")
	public String memberResume(HttpServletRequest  request) {
    
    
		//根据用户的id去简历表查找出个人的简历信息
		User u = (User) request.getSession().getAttribute("user");
		int userId = u.getId();
		UserResume userResume = userResumeServiceImpl.selectByUserId(userId);
		request.setAttribute("userResume", userResume);
		//根据用户的id去工作经验表查找出个人的工作经验信息
		
		List<Workexperience> workexperienceLists = workExperienceService.selectByUid(userId);
		request.setAttribute("workexperienceLists",workexperienceLists);
		return "user/memberResume";
	}
	
	/**
	 *  进入用户个人中心页面
	 */
	@RequestMapping("/memberResume1")
	public String memberResume1() {
    
    
		return "user/memberResume1";
	}
	
	/**
	 * 前往系统设置页面
	 */
	@RequestMapping("/userInfo")
	public String userInfo(HttpServletRequest  request) {
    
    
		//根据用户的id去简历表查找出个人的简历信息
		User u = (User) request.getSession().getAttribute("user");
		int userId = u.getId();
		User user = userServiceImpl.selectByUserId(userId);
		request.setAttribute("info", user);
		return "user/info";
	}
	
	/**
	 * 关联qq
	 * 
	 */
	@RequestMapping("/associatedQq")
	@ResponseBody
	public Response associatedQq(User user) {
    
    
		//只能是修改,不可能是新增的额。
		//1.0 声明需要返回的类型
		Response rep = new Response();
		rep.setCode(1);
		rep.setMsg("操作成功");
		userServiceImpl.updateAssociatedQq(user);
		return rep;
	}
	
	/**
	 * 关联qq
	 * 
	 */
	@RequestMapping("/associatedWeixin")
	@ResponseBody
	public Response associatedWeixin(User user) {
    
    
		//只能是修改,不可能是新增的额。
		//1.0 声明需要返回的类型
		Response rep = new Response();
		rep.setCode(1);
		rep.setMsg("操作成功");
		userServiceImpl.updateAssociatedWeixin(user);
		return rep;
	}
	
	/**
	 *  修改密码
	 */
	@RequestMapping("/updatePassword")
	@ResponseBody
	public Response updatePassword(User user) {
    
    
		//只能是修改,不可能是新增的额。
		Response rep = new Response();
		rep.setCode(1);
		rep.setMsg("操作成功");
		userServiceImpl.updatePassword(user);
		return rep;
	}
	/**
	 * 退出
	 */
	@RequestMapping("/layout")
	@ResponseBody
	public Response layout(HttpServletRequest  request) {
    
    
		Response rep = new Response();
		request.getSession().invalidate();
		rep.setCode(1);
		rep.setMsg("操作成功");
		return rep;
	}
	
	/**
	 * 公司查看个人简历信息
	 */
	@RequestMapping("/showMemberResumeForCompany")
	public String showMemberResumeForCompany(HttpServletRequest  request,Integer uid,Integer aid) {
    
    
		//根据用户的id去简历表查找出个人的简历信息
		if(uid!=null && aid!=null) {
    
    
			UserResume userResume = userResumeServiceImpl.selectByUserId(uid);
			request.setAttribute("userResume", userResume);
			//根据用户的id去工作经验表查找出个人的工作经验信息
			List<Workexperience> workexperienceLists = workExperienceService.selectByUid(uid);
			
			//3.0 将当前的申请记录标示为:已读状态
			applayService.updateStateById(aid,2);
			
			
			request.setAttribute("workexperienceLists",workexperienceLists);
			return "user/showMemberResumeForCompany";
		}else {
    
    
			
			request.setAttribute("error", "必须传入用户的id/aid,非法操作,如操作无误,请联系管理员[email protected]");
			return "system/error";
		}
		
	}
	
	
	//以下是小程序端的接口
	@RequestMapping("/xiaochengxu/toLogin")
	@ResponseBody
	public User toLogin(User user) {
    
    
		//2.0 根据用户名+密码去检索数据库
		String basePassword = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+user.getPassword());
		User u = userServiceImpl.selectUserByUsernameAndPassword(user.getUsername(),basePassword);
		return u;
	}
	
	public static void main(String[] args) {
    
    
		String baseString = MyMd5Utils.encodeByMD5("[email protected]"+"-"+"123456");
		System.out.println(baseString);
	}
}

小解读

注册的方法

  1. 用户注册时,手机账号和密码,对密码做md5加密,然后把isAudit设置为1,表示未激活,然后调用邮件的工具类进行发邮件
/**
	 * 用户注册
	 * @throws Exception 
	 */
	@RequestMapping("/register")
	public @ResponseBody Response insertUser(User user) throws Exception {
    
    
		//1.0 声明需要返回的类型
		Response rep = new Response();
		//判断邮箱是否存在
		User u = userServiceImpl.selectUserByUsername(user.getUsername());
		if(u!=null) {
    
    
			//返回错误信息,邮箱已存在
			rep.setCode(-1);
			rep.setMsg("邮箱已存在,您已经注册过我们网站,请返回登录");
			return rep;
		}
		user.setIsaudit(1);
		user.setRegister(new Date());
		String baseString = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+user.getPassword());
		user.setPassword(baseString);
		
		int i = userServiceImpl.insertUser(user);
		if(i > 0) {
    
    
			rep.setCode(1);
			rep.setMsg("完美注册,请到您的邮箱上激活,否则不允许登录");
			//MailUtils11.sendMail("招聘网站提醒", user.getUsername(), "账号激活", "您成功注册了小郑招聘网站,接下来点击下面按钮激活即可<br/>"+"http://localhost:8080/recruitmentWebsite/user/xiaochengxu/jihuo?baseString="+baseString);
			return rep;

		}else {
    
    
			rep.setCode(-1);
			rep.setMsg("程序有问题,请检查你的程序");
			return rep;
		}
	}

【备注】如果不想要有激活的功能,那么把isAudit设置为2或者在登录时,去掉对isAudit的判断即可
如果不能发送邮件,则注释发送邮件的代码即可,发送邮件是一个工具类,后面会分享给大家

登录方法

  1. 先用账号和MD5加密后的数据去数据库找到是否有数据
  2. 判断isAduit字段,账号是否可以的判断
@RequestMapping("/toLogin")
	public @ResponseBody Response toLogin(User user,HttpServletRequest  request) {
    
    
		//1.0 声明需要返回的类型
		Response rep = new Response();
		//2.0 根据用户名+密码去检索数据库
		String basePassword = MyMd5Utils.encodeByMD5(user.getUsername()+"-"+user.getPassword());
		User u = userServiceImpl.selectUserByUsernameAndPassword(user.getUsername(),basePassword);
		if(u!=null) {
    
    
			//3.0表示登陆成功
			if(u.getIsaudit() == 2) {
    
    
				//4.0 账号密码错误
				rep.setCode(-1);
				rep.setMsg("您的账户已经被冻结,请联系管理员[email protected]");
				return rep;
			}else if(u.getIsaudit() == 3){
    
    
				rep.setCode(-1);
				rep.setMsg("您登录的账户还没有激活,请到注册的邮箱上点击激活按钮");
				request.getSession().setAttribute("user", u);
				return rep;
			}else {
    
    
				rep.setCode(1);
				rep.setMsg("登陆成功");
				request.getSession().setAttribute("user", u);
				return rep;
			}
			
		}else {
    
    
			//4.0 账号密码错误
			rep.setCode(-1);
			rep.setMsg("账号或者密码错误,请重新输人");
			return rep;
		}
	}

邮箱激活

  1. 激活看似很难理解,确实最简单的,用一个字段int类型来做是否激活的标志位,若1表未激活,若2表激活,在登录的时候验证即可
/**
	 * 邮箱激活
	 */
	@RequestMapping("/xiaochengxu/jihuo")
	public String jihuo(String baseString) {
    
    
		//修改当前的状态即可
		userServiceImpl.updateByBaseString(baseString);
		return "user/jihuo";
	}

邮箱工具类

myEmailAccount : 建议申请163邮箱,然后可以免费发送邮件的功能
在这里插入图片描述

package com.xiaozheng.recruitment.utils;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils11 {
    
    
	 // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), 
    //     对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
    //public static String myEmailAccount = "[email protected]";
   
	private Properties p; // p是属性集合类,用来设置邮件的一些属性比如timeout等
    public static String myEmailAccount = "******@163.com";
    public static String myEmailPassword = "*****";
   
    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
    // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
    public static String myEmailSMTPHost = "smtp.163.com";
   
    
    
    public static void sendMail(String username, String receiveMailAccount , String emailText ,String messageText) throws Exception  // 1. 创建一封邮件
       {
    
    
    	 // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        //props.put("username", "[email protected]");
        props.setProperty("mail.transport.protocol", "SMTP");   // 使用的协议(JavaMail规范要求)
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");           // 需要请求认证
        
     // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
        //     如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
        //     打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
        /*
        // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
        //                  需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
        //                  QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)  */
    	/*Properties props = new Properties();
        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort)*/
        
        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

        // 3. 创建一封邮件
        MimeMessage message = createMimeMessage(session, receiveMailAccount,username,emailText,messageText);
        //message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(props.getProperty("userName")));
        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();

        // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
        // 
        //    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
        //           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
        //           类型到对应邮件服务器的帮助网站上查看具体失败原因。
        //
        //    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
        //           (1) 邮箱没有开启 SMTP 服务;
        //           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
        //           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
        //           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
        //           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
        //
        //    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
        transport.connect(myEmailAccount, myEmailPassword);

        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());

        // 7. 关闭连接
        transport.close();        
    }


	private static MimeMessage createMimeMessage(Session session,String receiveMail,
			String username,String emailText, String messageText) throws UnsupportedEncodingException, MessagingException {
    
    
		// 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)
        message.setFrom(new InternetAddress(myEmailAccount, username+"招聘网站成员", "UTF-8"));

        // 3. To: 收件人(可以增加多个收件人、抄送、密送)

        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "管理员用户", "UTF-8"));

        // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
        message.setSubject(emailText, "UTF-8");

        // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
        message.setContent(messageText, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
	}
    
    public static void main(String[] args) throws Exception {
    
    
    	String username = "欣欣";
		String totalText = "有人查看了发送了你的简历,请上去网站查看谢谢";
		String emailText = "系统提示";
    /*	String username = "admin";
		String totalText = "招聘网站提醒";
		String emailText = "激活验证码:1353";*/
 		MailUtils11.sendMail(username,"[email protected]",emailText, totalText);
	}
}

小总结

知 道 的 越 多 , 不 知 道 的 越 多 , 希 望 对 你 有 帮 助 ! \color{red}知道的越多,不知道的越多,希望对你有帮助!

猜你喜欢

转载自blog.csdn.net/xiaozhegaa/article/details/112344969
今日推荐