一 、第一个springboot程序–hello world.
二 、利用springboot框架及Ajax制作一个简易的注册系统(连接数据库).
利用springboot框架及Ajax制作一个简易的登录系统(连接数据库)可以直接把代码放到上次的工程里
工程图
提示:以下是本篇文章正文内容,下面案例可供参考
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
head>
<body>
用户名<input id="userName">
<br>
密码<input id="password">
<br>
<button onclick="login()" >登录button>
<script type="text/javascript" src="jquery.min.js">script>
<script>
function login() {
var userName = $("#userName").val();
var password = $("#password").val();
var data = {
"userName":userName,"password":password}
$.ajax({
type: "POST",
dataType: "json",
url: "users/login",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(data),
success: function (result) {
if (result.resultCode == 200) {
alert("登录成功")
setCookie("userToken",result.data.userToken);
window.location.href = "/"
}
;
if (result.resultCode == 500) {
alert("注册失败!请检查账号和密码!");
return;
}
},
error: function () {
alert("接口异常,请联系管理员!");
return;
}
});
}
//添加cookie
function setCookie(name,value) {
var exp = new Date();
exp.setTime(exp.getTime()+30*24*60*60*1000);
document.cookie = name+"="+escape(value)+";expires="+exp.toGMTString()+";path=/";
}
script>
body>
html>
添加userToken 用来辨别用户
package com.springboot.regist.demo.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
*
*/
public class SystemUtil {
private SystemUtil() {
}
/**
* 登录或注册成功后,生成保持用户登录状态会话token值
*
* @param src:为用户最新一次登录时的now()+user.id+random(4)
* @return
*/
public static String genToken(String src) {
if (null == src || "".equals(src)) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(src.getBytes());
return new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
return null;
}
}
}
package com.springboot.regist.demo.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*/
public class NumberUtil {
private NumberUtil() {
}
/**
* 判断是否为11位电话号码
*
* @param phone
* @return
*/
public static boolean isPhone(String phone) {
Pattern pattern = Pattern.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0-8])|(18[0-9]))\\d{8}$");
Matcher matcher = pattern.matcher(phone);
return matcher.matches();
}
/**
* 生成指定长度的随机数
*
* @param length
* @return
*/
public static int genRandomNum(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 生成订单流水号
*
* @return
*/
public static String genOrderNo() {
StringBuffer buffer = new StringBuffer(String.valueOf(System.currentTimeMillis()));
int num = genRandomNum(4);
buffer.append(num);
return buffer.toString();
}
public static String formatMoney2Str(Double money) {
java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
return df.format(money);
}
public static String formatMoney2Str(float money) {
java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
return df.format(money);
}
}
代码如下(示例):
/**
* 用户登录
*
* @param user 用户信息
* @return result
*/
@RequestMapping(value = "/users/login", method = RequestMethod.POST)
public Result login(@RequestBody User user) {
Result result = ResultGenerator.genFailResult("登录失败");
if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
result.setMessage("请填写登录信息!");
return result;
}
User loginUser = UserService.userlogin(user.getUserName(), user.getPassword());
if (loginUser != null) {
result = ResultGenerator.genSuccessResult(loginUser);
return result;
}
return result;
}
代码如下(示例):
/**
*
* @param userName 用户名
* @param password 密码
* @return 登录
*/
User userlogin(String userName,String password);
@Override
public User userlogin(String userName, String password) {
//密码加密
//调用dao方法查询用户
User User = userdao.selectuserinfo(userName, MD5Util.MD5Encode(password, "UTF-8"));
if (User != null) {
//生成token
String token = SystemUtil.genToken(System.currentTimeMillis() + "" + User.getId() + NumberUtil.genRandomNum(4));
//更新user表
if (userdao.updateToken(User.getId(), token) > 0) {
//把token给设置进去
User.setUserToken(token);
User.setId(null);
return User;
}
}
return null;
}
//登陆时
//查询数据库是否有用户名密码
User selectuserinfo(@Param("userName") String userName, @Param("passwordMD5") String passwordMD5);
//跟新token
int updateToken(@Param("userId") Long userId, @Param("newToken") String newToken);
<mapper namespace="com.springboot.regist.demo.dao.Userdao">
<resultMap type="com.springboot.regist.demo.entity.User" id="UserResult">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="userName" column="username" jdbcType="VARCHAR"/>
<result property="password" column="password" jdbcType="VARCHAR"/>
<result property="userToken" column="userToken" jdbcType="VARCHAR" />
resultMap>
<select id="selectuserinfo" resultMap="UserResult">
select id,username,password from test1 where username = #{userName} and password = #{passwordMD5}
select>
<update id="updateToken">
update test1 set userToken = #{newToken} where id =#{userId}
update>
public class User {
private Long id;
@Override
public String
toString() {
return "User{" +
"id=" + id +
", password='" + password + '\'' +
", userName='" + userName + '\'' +
", userToken='" + userToken + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String password;
private String userName;
private String userToken;
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
其他的文件配置和上次注册的相同