java注册登陆视频_JavaWeb_(视频网址)_二、用户模块1 注册登陆

用户模块

创建用户实体

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)privateLong id;privateString username;privateString password;privateString email;privateString firstName;privateString lastName;privateString displayNane;//个人首页

privateString webUrl;privateString phone;//个人描述

privateString description;//social Link

privateString qqLink;privateString weixinLink;//封面头像

privateString coverImage;//头像

privateString headImage;//创建时间

private String createTime;

用户注册流程图

0dada30c3104ccb48b60947192a619b2.png

当用户输入手机号后,通过JQery判断用户是否输入正确的手机号,如果正确,则发送验证码,如果错误,则提示用户手机号输入错误

在Controller层中添加用户层UserController,java,用于接收sms请求

@Controllerpublic classUserController {//发送手机验证码

@RequestMapping("/sms")

@ResponseBodypublicString sms(String phone)

{

System.out.println(phone);return "";

}

}

39d7c263f278bc221fdb20f24aa666b8.gif

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

//检验短信验证码是否正确

$("#smsInput").blur(function(){var sms = $("#smsInput").val();//校验验证码

$.post(//action的地址

[[@{~/judgeSMS}]],

//数据

{"sms":sms},//回调函数

function(data)

{if(data.message)

{

layer.msg("验证码正确!!");

}else{

layer.msg("验证码错误!!");

$("#smsInput").val("");

}

},//数据格式

"json")

})//发送手机验证码

$("#usernameInput").blur(function(){//获得手机号

var phone = $("#usernameInput").val();//判断是否为手机号

if(/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(phone))

{//发送手机验证码

$.post(//action的地址

[[@{~/sms}]],

//数据

{"phone":phone},//回调函数

function(data)

{if(data.message)

{

layer.msg("验证码发送成功~");

}else{

layer.msg("该手机号已经被注册~");

}

},//数据格式

"json")

}else{

layer.msg("手机格式有误!!");

}

})

手机验证码.javascript

Controller层UserController.java接收到用户发送回来的消息后,使用userService.findUserByUsername(phone)方法查询数据库中手机号是否存在

//发送手机验证码

@RequestMapping("/sms")

@ResponseBodypublicString sms(String phone)

{//System.out.println(phone);//判断数据库中是否存在手机号

String json = null;if(userService.findUserByUsername(phone) != null)

{//存在,不用发短信

json = "{\"message\":"+false+"}";

}else{//不存在,发送短信

SMS();

json= "{\"message\":"+true+"}";

}returnjson;

}

使用父类CrudRepository.java查询数据库中电话是否重复

@Query(value = "select * from user where username = ?1",nativeQuery =true)User findUserByUsername(String phone);

腾讯云手机发送验证码SMS模块

private voidSMS(String telephone,HttpSession session) {//腾讯云中的数据

int appid = 1400184301;

String appkey= "58f61b731363faba756087b9504bff46";int templateId=275243;

String smsSign= "Garyd公众号";//电话

String phoneNumber =telephone;//验证码

Random r = newRandom();

String code= "";for(int i=0;i<4;i++)

{

code+=r.nextInt(10);

}//放入session域中

session.setAttribute("sms", code);//验证码

String[] params = new String[1];

params[0] =code;

System.out.println("验证码为:"+code);//发送验证码模块

SmsSingleSender ssender = newSmsSingleSender(appid, appkey);try{

ssender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");

}catch (HTTPException | JSONException |IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

ae19bdb75636b0b5c87491ffbaf90522.gif

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.Gary.betobe.controller;importjava.io.IOException;importjava.util.Random;importjavax.servlet.http.HttpSession;importorg.json.JSONException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;importcom.Gary.betobe.service.UserService;importcom.github.qcloudsms.SmsSingleSender;importcom.github.qcloudsms.httpclient.HTTPException;

@Controllerpublic classUserController {

@AutowiredprivateUserService userService;

@AutowiredprivateHttpSession session;//发送手机验证码

@RequestMapping("/sms")

@ResponseBodypublicString sms(String phone)

{//System.out.println(phone);//判断数据库中是否存在手机号

String json = null;if(userService.findUserByUsername(phone) != null)

{//存在,不用发短信

json = "{\"message\":"+false+"}";

}else{//不存在,发送短信

SMS(phone,session);

json= "{\"message\":"+true+"}";

}returnjson;

}private voidSMS(String telephone,HttpSession session) {//腾讯云中的数据

int appid = 1400184301;

String appkey= "58f61b731363faba756087b9504bff46";int templateId=275243;

String smsSign= "Garyd公众号";//电话

String phoneNumber =telephone;//验证码

Random r = newRandom();

String code= "";for(int i=0;i<4;i++)

{

code+=r.nextInt(10);

}//放入session域中

session.setAttribute("sms", code);//验证码

String[] params = new String[1];

params[0] =code;

System.out.println("验证码为:"+code);//发送验证码模块

SmsSingleSender ssender = newSmsSingleSender(appid, appkey);try{

ssender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");

}catch (HTTPException | JSONException |IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

UserController.java

鼠标离焦后,讲验证码发送给手机

6f5b63663a0e7aafee26667e57e72a87.png

login-register登陆注册页面用过javascript去实现离焦后判断用户是否正确输入验证码

//检验短信验证码是否正确

$("#smsInput").blur(function(){var sms = $("#smsInput").val();//校验验证码

$.post(//action的地址

[[@{~/judgeSMS}]],

//数据

{"sms":sms},//回调函数

function(data)

{if(data.message)

{

layer.msg("验证码正确!!");

}else{

layer.msg("验证码错误!!");

$("#smsInput").val("");

}

},//数据格式

"json")

})

后台UserController.java中实现对手机验证码的是否正确输入进行判断

//判断手机验证码

@RequestMapping("/judgeSMS")

@ResponseBodypublicString judgeSMS(String sms,HttpSession session)

{//sms与Session中的sms对比

String smsInSession = (String)session.getAttribute("sms");

String json= null;if(sms.equals(smsInSession))

{

json= "{\"message\":"+true+"}";

}else{

json= "{\"message\":"+false+"}";

}returnjson;

}

eb2ce3244c5cd5b70854f33059aaa9e5.gif

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

//检验短信验证码是否正确

$("#smsInput").blur(function(){var sms = $("#smsInput").val();//校验验证码

$.post(//action的地址

[[@{~/judgeSMS}]],

//数据

{"sms":sms},//回调函数

function(data)

{if(data.message)

{

layer.msg("验证码正确!!");

}else{

layer.msg("验证码错误!!");

$("#smsInput").val("");

}

},//数据格式

"json")

})

检验短信验证码是否正确.javascript

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.Gary.betobe.controller;importjava.io.IOException;importjava.util.Random;importjavax.servlet.http.HttpSession;importorg.json.JSONException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;importcom.Gary.betobe.service.UserService;importcom.github.qcloudsms.SmsSingleSender;importcom.github.qcloudsms.httpclient.HTTPException;

@Controllerpublic classUserController {

@AutowiredprivateUserService userService;

@AutowiredprivateHttpSession session;//判断手机验证码

@RequestMapping("/judgeSMS")

@ResponseBodypublicString judgeSMS(String sms,HttpSession session)

{//sms与Session中的sms对比

String smsInSession = (String)session.getAttribute("sms");

String json= null;if(sms.equals(smsInSession))

{

json= "{\"message\":"+true+"}";

}else{

json= "{\"message\":"+false+"}";

}returnjson;

}//发送手机验证码

@RequestMapping("/sms")

@ResponseBodypublicString sms(String phone)

{//System.out.println(phone);//判断数据库中是否存在手机号

String json = null;if(userService.findUserByUsername(phone) != null)

{//存在,不用发短信

json = "{\"message\":"+false+"}";

}else{//不存在,发送短信

SMS(phone,session);

json= "{\"message\":"+true+"}";

}returnjson;

}private voidSMS(String telephone,HttpSession session) {//腾讯云中的数据

int appid = 1400184301;

String appkey= "58f61b731363faba756087b9504bff46";int templateId=275243;

String smsSign= "Garyd公众号";//电话

String phoneNumber =telephone;//验证码

Random r = newRandom();

String code= "";for(int i=0;i<4;i++)

{

code+=r.nextInt(10);

}//放入session域中

session.setAttribute("sms", code);//验证码

String[] params = new String[1];

params[0] =code;

System.out.println("验证码为:"+code);/*//发送验证码模块

SmsSingleSender ssender = new SmsSingleSender(appid, appkey);

try {

ssender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");

} catch (HTTPException | JSONException | IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}*/}

}

UserController.java

实现用户注册功能

注册页面输入手机号信息,邮箱,密码,验证码正确后,当用户点击提交表单后,注册页面将表单传入数据库中。

9f881553d9a23802070ee096ac4d53a6.gif

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.Gary.betobe.domain;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistence.Lob;

@Entitypublic classUser {

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)privateLong id;privateString username;privateString password;privateString email;privateString firstName;privateString lastName;privateString displayNane;//个人首页

privateString webUrl;privateString phone;//个人描述

@Lob//长文本 ->lob对应mysql的数据类型 longtext

privateString description;//social Link

privateString qqLink;privateString weixinLink;//封面头像

privateString coverImage;//头像

privateString headImage;//创建时间

privateString createTime;//JPA的标准

protectedUser()

{

}publicUser(Long id, String username, String password, String email, String firstName, String lastName,

String displayNane, String webUrl, String phone, String description, String qqLink, String weixinLink,

String coverImage, String headImage, String createTime) {super();this.id =id;this.username =username;this.password =password;this.email =email;this.firstName =firstName;this.lastName =lastName;this.displayNane =displayNane;this.webUrl =webUrl;this.phone =phone;this.description =description;this.qqLink =qqLink;this.weixinLink =weixinLink;this.coverImage =coverImage;this.headImage =headImage;this.createTime =createTime;

}publicLong getId() {returnid;

}public voidsetId(Long id) {this.id =id;

}publicString getUsername() {returnusername;

}public voidsetUsername(String username) {this.username =username;

}publicString getPassword() {returnpassword;

}public voidsetPassword(String password) {this.password =password;

}publicString getEmail() {returnemail;

}public voidsetEmail(String email) {this.email =email;

}publicString getFirstName() {returnfirstName;

}public voidsetFirstName(String firstName) {this.firstName =firstName;

}publicString getLastName() {returnlastName;

}public voidsetLastName(String lastName) {this.lastName =lastName;

}publicString getDisplayNane() {returndisplayNane;

}public voidsetDisplayNane(String displayNane) {this.displayNane =displayNane;

}publicString getWebUrl() {returnwebUrl;

}public voidsetWebUrl(String webUrl) {this.webUrl =webUrl;

}publicString getPhone() {returnphone;

}public voidsetPhone(String phone) {this.phone =phone;

}publicString getDescription() {returndescription;

}public voidsetDescription(String description) {this.description =description;

}publicString getQqLink() {returnqqLink;

}public voidsetQqLink(String qqLink) {this.qqLink =qqLink;

}publicString getWeixinLink() {returnweixinLink;

}public voidsetWeixinLink(String weixinLink) {this.weixinLink =weixinLink;

}publicString getCoverImage() {returncoverImage;

}public voidsetCoverImage(String coverImage) {this.coverImage =coverImage;

}publicString getHeadImage() {returnheadImage;

}public voidsetHeadImage(String headImage) {this.headImage =headImage;

}publicString getCreateTime() {returncreateTime;

}public voidsetCreateTime(String createTime) {this.createTime =createTime;

}

}

User.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.Gary.betobe.controller;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.Random;importjavax.servlet.http.HttpSession;importorg.json.JSONException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;importcom.Gary.betobe.domain.User;importcom.Gary.betobe.service.UserService;importcom.github.qcloudsms.SmsSingleSender;importcom.github.qcloudsms.httpclient.HTTPException;

@Controllerpublic classUserController {

@AutowiredprivateUserService userService;

@AutowiredprivateHttpSession session;//用户注册

@RequestMapping("/register")publicString register(User user)

{//private String username;//private String password;//private String email;//private String firstName;//private String lastName;//private String displayNane;//个人首页//private String webUrl;//private String phone;

user.setPhone(user.getUsername());//个人描述//private String description;//social Link//private String qqLink;//private String weixinLink;//封面头像//private String coverImage;

user.setCoverImage("/images/user/bg/profile-bg.png");//头像//private String headImage;

Random r = newRandom();

user.setHeadImage("/images/user/head/"+r.nextInt(15)+".jpg");//创建时间//private String createTime;

Date date = newDate(System.currentTimeMillis());

SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

user.setCreateTime(format.format(date));

userService.saveUser(user);return "redirect:/loginBetobe";

}//判断手机验证码

@RequestMapping("/judgeSMS")

@ResponseBodypublicString judgeSMS(String sms,HttpSession session)

{//sms与Session中的sms对比

String smsInSession = (String)session.getAttribute("sms");

String json= null;if(sms.equals(smsInSession))

{

json= "{\"message\":"+true+"}";

}else{

json= "{\"message\":"+false+"}";

}returnjson;

}//发送手机验证码

@RequestMapping("/sms")

@ResponseBodypublicString sms(String phone)

{//System.out.println(phone);//判断数据库中是否存在手机号

String json = null;if(userService.findUserByUsername(phone) != null)

{//存在,不用发短信

json = "{\"message\":"+false+"}";

}else{//不存在,发送短信

SMS(phone,session);

json= "{\"message\":"+true+"}";

}returnjson;

}private voidSMS(String telephone,HttpSession session) {//腾讯云中的数据

int appid = 1400184301;

String appkey= "58f61b731363faba756087b9504bff46";int templateId=275243;

String smsSign= "Garyd公众号";//电话

String phoneNumber =telephone;//验证码

Random r = newRandom();

String code= "";for(int i=0;i<4;i++)

{

code+=r.nextInt(10);

}//放入session域中

session.setAttribute("sms", code);//验证码

String[] params = new String[1];

params[0] =code;

System.out.println("验证码为:"+code);/*//发送验证码模块

SmsSingleSender ssender = new SmsSingleSender(appid, appkey);

try {

ssender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");

} catch (HTTPException | JSONException | IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}*/}

}

UserController.java

用户登陆功能

用户登陆流程图

4e85722b21d890084c1e0bec87c1af6d.png

防止页面在未登录的情况下访问不到资源,在SecurityConfig.java中通过http.authorizeRequests().antMatchers开放资源

//做拦截

@Overrideprotected void configure(HttpSecurity http) throwsException {//请求授权

http.formLogin()//自己登陆页面

.loginPage("/loginBetobe")//自己的表单登陆的URL

.loginProcessingUrl("/loginPage")

.and()

.authorizeRequests()

.antMatchers("/loginRegister","/sms","/judgeSMS","/register","/loginBetobe","/scss/**","/layerslider/**","/layer/**","/js/**","/images/**","/fonts/**","/dist/**","/css/**","/api/**","/bower_components/**").permitAll()//所有请求

.anyRequest()//都需要我们身份认证

.authenticated().and()//跨站请求伪造和防护

.csrf().disable();

}

用户登陆模块,在SocialUserServiceimpl.java中判断登陆的用户在数据库中是否存在

@Overridepublic UserDetails loadUserByUsername(String username) throwsUsernameNotFoundException {//System.out.println(username);

User user =userService.findUserByUsername(username);//查找是否存在该用户

if (user == null) {//不存在,UsernameNotFoundException

throw new UsernameNotFoundException("");

}//存在,给我们SpringSecurity用户名及密码,权限

return new SocialUser(user.getUsername(), passwordEncoder.encode(user.getPassword()), true, true, true, true,

AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));

}

a1611c987588443096eb118a5b8796bb.gif

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.Gary.betobe.service.impl;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.core.authority.AuthorityUtils;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.security.crypto.password.PasswordEncoder;importorg.springframework.stereotype.Component;importorg.springframework.social.security.SocialUser;importorg.springframework.social.security.SocialUserDetails;importorg.springframework.social.security.SocialUserDetailsService;importcom.Gary.betobe.domain.User;importcom.Gary.betobe.service.UserService;

@Componentpublic class SocialUserServiceimpl implementsUserDetailsService {

@AutowiredprivateUserService userService;

@AutowiredprivatePasswordEncoder passwordEncoder;

@Overridepublic UserDetails loadUserByUsername(String username) throwsUsernameNotFoundException {//System.out.println(username);

User user =userService.findUserByUsername(username);//查找是否存在该用户

if (user == null) {//不存在,UsernameNotFoundException

throw new UsernameNotFoundException("");

}//存在,给我们SpringSecurity用户名及密码,权限

return new SocialUser(user.getUsername(), passwordEncoder.encode(user.getPassword()), true, true, true, true,

AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));

}

}

SocialUserServiceimpl.java

用户登陆成功or失败处理

LoginSuccessHandler.java处理用户登陆成功

@Overridepublic voidonAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,

Authentication authentication)throwsServletException, IOException {//TODO Auto-generated method stub//成功,,跳转到首页

response.sendRedirect("/index");//super.onAuthenticationSuccess(request, response, authentication);

}

LoginFailureHandler.java处理用户登陆失败

@Overridepublic voidonAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,

AuthenticationException exception)throwsIOException, ServletException {//TODO Auto-generated method stub//在request域中放置错误信息

request.setAttribute("error", "Error in username or password");//转发到loginBetobe

request.getRequestDispatcher("/loginBetobe").forward(request, response);//super.onAuthenticationFailure(request, response, exception);

}

在SecurityConfig.java中添加两个handler

@AutowiredprivateLoginSuccessHandler loginSuccessHandler;

@Autowiredprivate LoginFailureHandler loginFailureHandler;

实现登陆失败提示的显示

当登陆成功时,跳转到index.html首页面

当登陆失败时,在login.html页面中添加javascript代码,使得刷新页面后,显示Error的信息

//当页面加载完成的时候会调用

window.onload = functionerror()

{//如果错误的信息不为空

if([[${error}]] != null)

{//显示Error的信息

$("#error").html([[${error}]]);

$("#errorMessage").show();

}

}

08580e64045de9d6e0bfae2685677080.gif

记住我功能

实现记住我功能流程图

0050c43a4a59fc06e94bb4d26f4acd06.png

记住我的checkbox

Remember me

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值