1.idea创建maven项目,下面步骤按自己实际情况填写创建。
2.环境
spring、mvc等配置不需要自己写,只需配置一下数据库即可。另外,与主应用程序上下文不同的外部配置,我在根目录创建application.properties来配置,mybatis逆向生成需要配置。
(1)首先,搞一下pom.xml。(里面有些是用不到的,不过全copy了,后面业务会用的)
[Maven库依赖查询](https://mvnrepository.com/),例如 <artifactId>junit</artifactId>,将junit输入查询,即可得到各个版本的。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.smxy.study</groupId>
<artifactId>shoping</artifactId>
<version>1.0-SNAPSHOT</version>
<name>shoping</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 数据库依赖,数据库mySql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.17</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 辅助校验 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<!-- 校验 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<!--时间-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!--mybatis逆向生成-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>mybatis_generator</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许覆盖生成的文件-->
<verbose>false</verbose>
<overwrite>true</overwrite>
<configurationFile>
src/main/resources/mybatis-generator.xml
</configurationFile>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)jar包架好之后,可以测试一下,打开App.java
//1.让Springboot扫描配置文件
/**
* 如果没有包,就用这个注解,因为我现在是要弄一个项目,这些包都创建好了
*@EnableAutoConfiguration将该类做成支持配置可以自动加载 并
*/
//@EnableAutoConfiguration
@SpringBootApplication(scanBasePackages = {"com.smxy.study"})
@MapperScan("com.smxy.study.dao")
@RestController
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class,args);
//启动web容器
System.out.println( "启动SpringBoot项目" );
}
}
(3)application.properties的上下文全局配置
# 设置自己的服务访问端口
server.port=8090
mybatis.mapperLocations=classpath:mapping/*.xml
# 数据库相关配置
spring.datasource.name=shoping
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/miaosha
spring.datasource.username=root
spring.datasource.password=123456
#配置数据源,这里是有druid数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
(4)mybatis的逆向生成,可以查看Mybatis官方文档。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 设置不会生成注释的自动生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/miaosha"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 指定JavaBean生成的位置(pojo) -->
<javaModelGenerator targetPackage="com.smxy.study.pojo"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 指定Sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapping" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 指定Dao接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.smxy.study.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- table指定每个表生成策略 -->
<!--enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"-->
<table tableName="promo" domainObjectName="Promo" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
逆向文件配置好之后,运行即可生成相关代码
3.用户模型
习惯性创建用户时,会将password一起整到一张表,这样,前端请求就可以看到这类敏感数据,虽然加密,但是还是给用户一种不好的体验。所以,从现在学习更好的模型规划。
(1)自动生成的User和Password类不动
(2)Service层操作模型类
UserModel .java
package com.smxy.study.service.model;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class UserModel {
private Integer id;
@NotBlank(message = "用户名不能为空")
private String name;
@NotNull(message = "性别不能不填")
private Byte gender;
@NotNull(message = "年龄不能不填")
@Min(value = 0,message = "年龄必须大于0")
@Max(value = 150,message = "年龄必须小于150")
private Integer age;
@NotBlank(message = "手机号不能为空")
private String telphone;
private String regisaterMode;
private String thirdPartyId;
@NotBlank(message = "密码不能为空")
private String encrptPassword;
< 对应的get/set >
}
(3)可以给前端展示的模型
UserVO.java
package com.smxy.study.controller.viewobject;
public class UserVO {
private Integer id;
private String name;
private Byte gender;
private Integer age;
private String telphone;
< 对应的get/set >
}
4.业务实现
来写Service层。
UserService.java
package com.smxy.study.service;
import com.smxy.study.error.BusinessException;
import com.smxy.study.service.model.UserModel;
import org.xml.sax.SAXException;
import java.io.IOException;
public interface UserService {
public UserModel getUserById(Integer id);
/**
* 用户注册服务
* @param userModel
* @throws BusinessException
*/
void register(UserModel userModel) throws BusinessException, IOException, SAXException;
/**
* 校验登录用户的信息
* @param telpnone,用户的手机号
* @param passd,用户加密后的密码
*/
UserModel validateLogin(String telpnone,String passd) throws BusinessException;
}
UserServiceImpl.java
package com.smxy.study.service.impl;
import ch.qos.logback.core.net.SyslogOutputStream;
import com.smxy.study.Validator.ValidationResult;
import com.smxy.study.Validator.ValidatorImpl;
import com.smxy.study.dao.UserMapper;
import com.smxy.study.dao.UserPasswordMapper;
import com.smxy.study.error.BusinessException;
import com.smxy.study.error.EmBusinessError;
import com.smxy.study.pojo.User;
import com.smxy.study.pojo.UserPassword;
import com.smxy.study.service.UserService;
import com.smxy.study.service.model.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.SAXException;
import java.io.IOException;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserPasswordMapper userPasswordMapper;
@Autowired
private ValidatorImpl validator;
@Override
public UserModel getUserById(Integer id) {
User userDo = userMapper.selectByPrimaryKey(id);
UserPassword userPassword = userPasswordMapper.selectByUserId(id);
UserModel userModel = convertFromDataObject(userDo,userPassword);
return userModel;
}
@Override
@Transactional
public void register(UserModel userModel) throws BusinessException, IOException, SAXException {
if(userModel == null) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "用户为空");
}
//开始校验
// if(StringUtils.isEmpty(userModel.getName())
// || userModel.getGender() == null
// || userModel.getAge() == null
// || StringUtils.isEmpty(userModel.getTelphone())){
// throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"传入参数不合法");
// }
ValidationResult result = validator.validate(userModel);
if(result.isHasErrors()){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
}
//增加事务,避免出现类似userMapper成功,userPasswordMapper失败案例
User userDO = convertFromDataObject(userModel);
userMapper.insertSelective(userDO);
userModel.setId(userDO.getId());//将自增生成的id给userModel,再传给UserPassword
UserPassword userPass = convertPassFromDataObject(userModel);
userPasswordMapper.insertSelective(userPass);
return;
}
@Override
public UserModel validateLogin(String telpnone, String passd) throws BusinessException {
//通过手机号获取用户信息
User userDO = userMapper.selectByTelphone(telpnone);
if(userDO == null){
throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
}
UserPassword userPassword = userPasswordMapper.selectByUserId(userDO.getId());
UserModel userModel = convertFromDataObject(userDO,userPassword);
//比对用户加密过的密码
if(!StringUtils.equals(passd,userModel.getEncrptPassword())){
throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
}
return userModel;
}
/**
* user、UserPassword转换-》UserModel
* @param user
* @param userPassword
* @return
*/
private UserModel convertFromDataObject(User user,UserPassword userPassword){
if(user==null)
return null;
UserModel userModel = new UserModel();
BeanUtils.copyProperties(user,userModel);
if(userPassword==null)
userModel.setEncrptPassword(null);
userModel.setEncrptPassword(userPassword.getEncrptPassword());
return userModel;
}
/**
* UserModel转换-》User
* @param userModel
* @return
*/
private User convertFromDataObject(UserModel userModel){
if(userModel == null)
return null;
User user = new User();
BeanUtils.copyProperties(userModel,user);
return user;
}
/**
* UserModel转换-》UserPassword
* @param userModel
* @return
*/
private UserPassword convertPassFromDataObject(UserModel userModel){
if(userModel == null)
return null;
UserPassword userPassword = new UserPassword();
userPassword.setEncrptPassword(userModel.getEncrptPassword());
userPassword.setUserId(userModel.getId());
return userPassword;
}
}
5.控制层接口
UserController.java
package com.smxy.study.controller;
import com.alibaba.druid.util.StringUtils;
import com.smxy.study.controller.viewobject.UserVO;
import com.smxy.study.error.BusinessException;
import com.smxy.study.error.EmBusinessError;
import com.smxy.study.response.CommentReturnType;
import com.smxy.study.service.impl.UserServiceImpl;
import com.smxy.study.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
@Controller
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class UserController extends BaseController {
@Autowired
private UserServiceImpl userService;
@Autowired
private HttpServletRequest httpServletRequest;//单例模式
@RequestMapping("/get")
@ResponseBody
public CommentReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
UserModel userModel = userService.getUserById(id);
//如果用户不存在,实现自定义异常类
if (userModel == null) {
throw new BusinessException(EmBusinessError.USER_NOT_EXIT);
}
UserVO userVO = convertFormModel(userModel);
return CommentReturnType.create(userVO);
}
/**
* 要保护用户信息,转成可供view使用的model
*
* @param userModel
* @return
*/
private UserVO convertFormModel(UserModel userModel) {
if (userModel == null)
return null;
UserVO userVO = new UserVO();
BeanUtils.copyProperties(userModel, userVO);
return userVO;
}
//用户获取opt短信接口
@RequestMapping(value = "/getopt", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
@ResponseBody
public CommentReturnType getOpt(@RequestParam(name = "telphone") String telphone) {
//1.按照一定规则生成opt---------随机数
Random random = new Random();
int randomInt = random.nextInt(99999);
randomInt += 10000;
String optCode = String.valueOf(randomInt);
//2、将opt验证码与用户的手机关联---------Redis(更好),httpSession
httpServletRequest.getSession().setAttribute(telphone, optCode);
//3.将opt验证码通过短信通道发送给用户(省略)
System.out.println("telephon=" + telphone + ",optcode=" + optCode);
return CommentReturnType.create(null);
}
//用户注册
@RequestMapping(value = "/register", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
@ResponseBody
public CommentReturnType register(@RequestParam(name = "telphone") String telphone,
@RequestParam(name = "otpCode") String otpCode,
@RequestParam(name = "name") String name,
@RequestParam(name = "gender") Integer gender,
@RequestParam(name = "age") Integer age,
@RequestParam(name = "encrptPassword") String encrptPassword) throws BusinessException, IOException, NoSuchAlgorithmException, SAXException {
//1.验证手机号和otp验证码
String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);
//String inSessionTelphone = (String) this.httpServletRequest.getSession().getAttribute(otpCode);
if (!StringUtils.equals(inSessionOtpCode, otpCode)) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符合");
}
//2.用户注册流程
UserModel userModel = new UserModel();
userModel.setName(name);
userModel.setGender(new Byte(String.valueOf(gender.intValue())));
userModel.setAge(age);
userModel.setTelphone(telphone);
userModel.setRegisaterMode("byphone");
userModel.setEncrptPassword(EncodeByMD5(encrptPassword));
userService.register(userModel);
return CommentReturnType.create(userModel);
}
//用户登录
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
@ResponseBody
public CommentReturnType login(@RequestParam(name="telphone")String telphone,@RequestParam(name="encrptPassword")String encrptPassword) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
//入参校验
if(StringUtils.isEmpty(telphone) || StringUtils.isEmpty(encrptPassword)){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"手机号和密码不能为空");
}
//用户登录服务,校验用户登录是否合法
String passwd = EncodeByMD5(encrptPassword);
UserModel userModel =userService.validateLogin(telphone,passwd);
//将登录凭证加入到用户登录成功的Session类
this.httpServletRequest.getSession().setAttribute("LOGIN",true);
this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
return CommentReturnType.create(userModel);
}
//MD5加密
public String EncodeByMD5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64Encoder = new BASE64Encoder();
String newPasswd = base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
return newPasswd;
}
}
6.页面实现
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="metronic_v4.7.5/_start/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
<link href="metronic_v4.7.5/theme/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"><link/>
<link href="metronic_v4.7.5/theme/assets/global/css/components.css" rel="stylesheet" type="text/css"><link/>
<link href="metronic_v4.7.5/theme/assets/pages/css/login.css" rel="stylesheet" type="text/css"><link/>
</head>
<body class=" login">
<div class="content">
<form class="login-form" action="index.html" method="post">
<h3 class="form-title"> 用户登录 </h3>
<div class="form-group">
<label class="#control-label">手机号:</label>
<div>
<input class="form-control" type="text" placeholder="手机号" name="telphone" id="telphone">
</div>
</div>
<div class="form-group">
<label class="#control-label">密码:</label>
<div>
<input class="form-control" type="password" name="encrptPassword" id="encrptPassword">
</div>
</div>
<div class="form-actions">
<button class="btn blue" id="login" type="submit">
登录
</button>
<button class="btn green" id="register" type="submit" onclick=javascript:goRegister()>
注册
</button>
</div>
</form>
</div>
</body>
<script>
//注册事件
//$("#register").on("click",function(){
// window.location.href = "getopt.html";
//});
//onclick="window.location.href='getopt.html'"
function goRegister(){
window.location.href="getopt.html";
}
jQuery(document).ready(function(){
//登录请求
$("#login").on("click",function(){
var telphone = $("#telphone").val();
var password = $("#encrptPassword").val();
if(telphone == null || telphone == ""){
alert("手机号不能为空");
return false;
}
if(password == null || password == ""){
alert("密码不能为空");
return false;
}
$.ajax({
type:"POST",
contentType:"application/x-www-form-urlencoded",
url:"http://127.0.0.1:8090/user/login",
data:{
"telphone": telphone,
"encrptPassword": password,
},
xhrFields: {withCredentials: true},
success:function(data){
if(data.status == "fail"){
alert("登录失败,原因:"+data.data.errMsg);
}else{
alert("用户登录成功");
window.location.href = "listitem.html";
}
},
error:function(data){
alert("请求失败:"+data.responseText);
}
});
return false;
});
});
</script>
</html>
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="F:/IdeaProjects/html/metronic_v4.7.5/_start/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
<link href="F:/IdeaProjects/html/metronic_v4.7.5/theme/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"><link/>
<link href="F:/IdeaProjects/html/metronic_v4.7.5/theme/assets/global/css/components.css" rel="stylesheet" type="text/css"><link/>
<link href="F:/IdeaProjects/html/metronic_v4.7.5/theme/assets/pages/css/login-4.css" rel="stylesheet" type="text/css"><link/>
</head>
<body class="login">
<div class="content">
<h3 class="form-title"> 用户注册 </h3>
<div class="form-group">
<label class="#control-label">手机号:</label>
<div>
<input class="form-control" type="text" placeholder="手机号" name="telphone" id="telphone">
</div>
</div>
<div class="form-group">
<label class="#control-label">验证码:</label>
<div>
<input class="form-control" type="text" placeholder="验证码" name="otpCode" id="otpCode">
</div>
</div>
<div class="form-group">
<label class="#control-label">用户名:</label>
<div>
<input class="form-control" type="text" placeholder="用户名" name="name" id="name">
</div>
</div>
<div class="form-group">
<label class="#control-label">性别:</label>
<div>
<input class="form-control" type="text" placeholder="性别" name="gender" id="gender">
</div>
</div>
<div class="form-group">
<label class="#control-label">年龄:</label>
<div>
<input class="form-control" type="text" placeholder="年龄" name="age" id="age">
</div>
</div>
<div class="form-group">
<label class="#control-label">密码:</label>
<div>
<input class="form-control" type="password" name="encrptPassword" id="encrptPassword">
</div>
</div>
<div class="form-actions">
<button class="btn blue" id="register" type="submit">
提交注册
</button>
<button class="btn green" id="login" type="submit">
已有账号
</button>
</div>
</div>
</body>
<script>
jQuery(document).ready(function(){
$("#login").on("click",function(){
window.location.href = "file:///F:/IdeaProjects/html/login.html";
});
//注册请求
$("#register").on("click",function(){
var telphone = $("#telphone").val();
var name = $("#name").val();
var gender = $("#gender").val();
var age = $("#age").val();
var password = $("#encrptPassword").val();
var otpCode = $("#otpCode").val();
if(telphone == null || telphone == ""){
alert("手机号不能为空");
return false;
}
if(name == null || name == ""){
alert("用户名不能为空");
return false;
}
if(password == null || password == ""){
alert("密码不能为空");
return false;
}
if(age == null || age == ""){
alert("年龄不能为空");
return false;
}
if(gender == null || gender == ""){
alert("性别不能为空");
return false;
}if(otpCode == null || otpCode == ""){
alert("otp不能为空");
return false;
}
$.ajax({
type:"POST",
contentType:"application/x-www-form-urlencoded",
url:"http://127.0.0.1:8090/user/register",
data:{
"telphone": telphone,
"otpCode": otpCode,
"name": name,
"gender": gender,
"age": age,
"encrptPassword": password,
},
xhrFields: {withCredentials: true},
success:function(data){
if(data.status == "fail"){
alert("注册失败,原因:"+data.data.errMsg);
}else{
alert("用户注册成功");
}
},
error:function(data){
alert("请求失败:"+data.responseText);
}
});
return false;
});
});
</script>
</html>
index.html(模仿手机验证码注册)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="metronic_v4.7.5/_start/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
<link href="metronic_v4.7.5/theme/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"><link/>
<link href="metronic_v4.7.5/theme/assets/global/css/components.css" rel="stylesheet" type="text/css"><link/>
<link href="metronic_v4.7.5/theme/assets/pages/css/login.css" rel="stylesheet" type="text/css"><link/>
</head>
<body class="login">
<div class="content">
<h3 class="form-title"> 获取otp信息 </h3>
<div class="form-group">
<label class="#control-label">手机号:</label>
<div>
<input class="form-control" type="text" placeholder="手机号" name="telphone" id="telphone">
</div>
</div>
<div class="form-actions">
<button class="btn blue" id="getotp" type="submit">
获取otp短信
</button>
</div>
</div>
</body>
<script>
jQuery(document).ready(function(){
//绑定opt的绑定事件
$("#getotp").on("click",function(){
var telphone = $("#telphone").val();
console.log(telphone);
if(telphone == null || telphone == ""){
alert("手机号不能为空");
return false;
}
$.ajax({
type:"POST",
contentType:"application/x-www-form-urlencoded",
url:"http://127.0.0.1:8090/user/getopt",
data:{
"telphone":telphone,
},
xhrFields: {withCredentials: true},
success:function(data){
if(data.status == "success"){
alert("opt已经发送到手机上");
window.location.href = "file:///F:/IdeaProjects/html/register.html";
//window.event.returnValue = false;
//return false;
}else{
alert(data.data.errMsg);
}
},
error:function(data){
alert(data.responseText);
}
});
return false;
});
});
</script>
</html>
=================================================================================================================================================
因为该项目是前后端分离,在Controller层要加一些注解,在html的ajax请求也要加一些请求格式。[结合上面代码]
其中还有Exception自定义类、自定义返回类、Validator校验等没有贴出来,完整项目看这里
Controler | ajax |
---|---|
@CrossOrigin(allowCredentials = “true”, allowedHeaders = “*”) | xhrFields: {withCredentials: true}, |
consumes = {CONTENT_TYPE_FORMED} | contentType:“application/x-www-form-urlencoded” |
界面展示
idea控制台
输入otp,以及其他相关信息