• 电商秒杀基础构建项目笔记1(搭建项目到用户模块开发)


    秒杀初始项目流程:

    第一步

    创建一个quickstart的依赖项目miaosha,

    引入一些包,打印helloworld ,

    第二步

    在properties之前添加依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.10.RELEASE</version>
    </parent>
    

    在App类加上@EnableAutoConfiguration(启动tomcat)@RestController(配置请求路径),在网页显示hello World,

    创建application.properties 改下端口,看原来的端口是否访问断开

    第三步

    Mybatis接入Spring Boot项目

    maven导入包,配置

    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
                <id>mybatis generator</id>
                <phase>package</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <!--允许移动生成的文件-->
            <verbose>true</verbose>
            <!--允许自动覆盖文件-->
            <overwrite>false</overwrite>
            <configurationFile>
                src/main/resources/mybatis-generator.xml
            </configurationFile>
        </configuration>
    
    </plugin>
    

    第四步

    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>
    
        <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->
    
    
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <!--数据库连接地址账号密码-->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                            connectionURL="jdbc:mysql://127.0.0.1:3306/miaosha?serverTimezone=Asia/Shanghai"
                            userId="root"
                            password="123456">
            </jdbcConnection>
    
    
            <!--<javaTypeResolver >-->
            <!--<property name="forceBigDecimals" value="false" />-->
            <!--</javaTypeResolver>-->
    
            <!--生成Model/DataObject类存放的位置-->
            <javaModelGenerator targetPackage="com.miaoshaproject.dataobject" targetProject="src/main/java">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
    
            <!--生成映射文件存放的位置-->
            <sqlMapGenerator targetPackage="mapping"  targetProject="src/main/resources">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
    
            <!--生成Dao类存放的位置-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.miaoshaproject.dao"  targetProject="src/main/java">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
    
    
            <!--生成对应表及类名-->
            <table tableName="user_info" domainObjectName="UserDO" enableCountByExample="false"
            enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
            <table tableName="user_password" domainObjectName="UserPasswordDO" enableCountByExample="false"
            enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
    
            <!--<table tableName="item" domainObjectName="ItemDO" enableCountByExample="false"-->
            <!--enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"-->
            <!--selectByExampleQueryId="false"></table>-->
            <!--<table tableName="item_stock" domainObjectName="ItemStockDO" enableCountByExample="false"-->
            <!--enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"-->
            <!--selectByExampleQueryId="false"></table>-->
    
            <!--<table tableName="order_info" domainObjectName="OrderDO" enableCountByExample="false"-->
            <!--enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"-->
            <!--selectByExampleQueryId="false"></table>-->
    
    
            <!--<table tableName="sequence_info" domainObjectName="SequenceDO" enableCountByExample="false"-->
            <!--enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"-->
            <!--selectByExampleQueryId="false"></table>-->
    
            <!--<table tableName="promo" domainObjectName="PromoDO" enableCountByExample="false"-->
            <!--enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"-->
            <!--selectByExampleQueryId="false"></table>-->
    
    
    
        </context>
    </generatorConfiguration>
    
    

    第5步

    配置application.properties

    server.port=8090
    mybatis.mapperLocations=classpath:mapping/*.xml
    
    #连接数据库
    spring.datasource.name=miaosha
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/miaosha?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    spring.datasource.username=root
    #spring.datasource.data-password=123456
    spring.datasource.password=123456
    
    #使用druid数据源
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
    

    先配置扫描类,为了再注入service封装

    @SpringBootApplication(scanBasePackages = {"com.miaoshaproject"} )
    @MapperScan("com.miaoshaproject.dao")
    

    之后在App类里面测试数据库数据,第一个id是否纯在。

    第六步

    使用SpringMVC方式开发用户信息

    创建controller,service层,编写UserController,下一步编写UserService接口和实现类,为了把数据返回给前端,创建UserModel类,把dataobject里面的数据编写到User Model,在就可以在service层里面把数据传给前端了,

    dataobject负责数据存储到service层传输,在service里面组装了用户的核心领域模型,controller层做了一个到viewobject的跳转,只使用需要展示的字段即可。

    先编写UserService,在编写实现类,先要修改UserPasswordDoMapper中的selectByUserId方法,之后再用户密码dao层增加一个查询的接口,下一步就可以编写Controler层了,在前端就可以访问到所有的数据,包括第三方信息和加密密码。

    修改UserPasswordDoMapper,增加通过用户id查询语句

    <select id="selectByUserId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    
      select
      <include refid="Base_Column_List" />
      from user_password
      where user_id = #{userId,jdbcType=INTEGER}
    </select>
    

    ​ 编写UserService层

    public interface UserService {
        //通过对象id获取对象
        UserModel getUserById(Integer id);
    }
    

    control层

    @Controller("user")
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        UserService userService;
    
        @RequestMapping("/get")
        @ResponseBody
        public UserModel getUser(@RequestParam(name = "id") Integer id)  {
            //调用service服务获取对应id对象返回给前端
            UserModel userModel = userService.getUserById(id);
           
            return userModel;
        }
    

    新增加一个viewObject层,为了让用户看到一些不必要的数据

    编写UserVo类

    public class UserVO {
        private Integer id;
    
        private String name;
    
        private Byte gender;
        private Integer age;
    
        private String telphone;
        ...
    }
    

    接着在control层继续编写

     public UserVO getUser(@RequestParam(name = "id") Integer id)  {
            //调用service服务获取对应id对象返回给前端
            UserModel userModel = userService.getUserById(id);
           
            return convertFromModel(userModel);
        }
    
        private UserVO convertFromModel(UserModel userModel) {
            if (userModel == null) {
                return null;
            }
            UserVO userVo = new UserVO();
            BeanUtils.copyProperties(userModel, userVo);
            return userVo;
        }
    

    第七步

    定义通用的返回对象,返回正确信息。

    新建一个response,之后建一个CommonReturnType类,编写请求处理的返回结果。

    public class CommonReturnType {
        //表明对应请求的返回处理结果“success”或“fail"
        private String status;
    
        //若status=success,则data内返回前端需要的json数据
        //若status=fail,则data内使用通用的错误码格式
        private Object data;
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public Object getData() {
            return data;
        }
    
        public void setData(Object data) {
            this.data = data;
        }
    
        //定义一个通用的创建方法
        public static CommonReturnType create(Object result) {
            return CommonReturnType.create(result,"success");
    
        }
        public static CommonReturnType create(Object result,String status) {
            CommonReturnType type = new CommonReturnType();
            type.setStatus(status);
            type.setData(result);
            return type;
        }
        }
    

    在control层调用之后在前端可以看到登入之后状态和数据。

    第八步 用枚举定义通用返回对象--返回错误信息 ,

    创建error包,通过建立一个关于错误信息的接口来为处理异常做准备,

    public interface CommonError {
        public int getErrCode();
        public String getErrMsg();
        public CommonError setErrMsg(String errMsg);
    
    }
    

    创建枚举接口,封装一些错误信息,

    public enum EmBusinessError implements CommonError {
        //通用错误类型000001
        PARAMETER_VALIDATION_ERROR(00001,"参数不合法"),
        //10000开头为用户相关错误
        USER_NOT_EXIST(10001,"用户不存在")
        ;
    
        private int errorCode;
        private String errmsg;
        private EmBusinessError(int errCode,String errMsg) {
            this.errorCode=errCode;
            this.errmsg=errMsg;
        }
    
        @Override
        public int getErrCode() {
            return this.errorCode;
        }
    
        @Override
        public String getErrMsg() {
            return this.errmsg;
        }
    
        @Override
        public CommonError setErrMsg(String errMsg) {
            this.errmsg = errMsg;
            return this;
        }
    }
    

    创建BusinessException,用于接收构建业务异常,

    //包装器业务异常类实现
    public class BusinessException extends Exception implements CommonError{
    
        //emun
        private CommonError commonError;
    
        //直接接收EmBusinessError的传参用于构造业务异常
        public BusinessException(CommonError commonError){
            super();
            this.commonError = commonError;
        }
    
        //接收自定义errMsg的方式构造业务异常(通过覆盖原本errMsg)
        public BusinessException(CommonError commonError, String errMsg) {
            super();
            this.commonError = commonError;
            this.commonError.setErrMsg(errMsg);
        }
        @Override
        public int getErrCode() {
            return commonError.getErrCode();
        }
    
        @Override
        public String getErrMsg() {
            return commonError.getErrMsg();
        }
    
        @Override
        public CommonError setErrMsg(String errMsg) {
            commonError.setErrMsg(errMsg);
            return this;
        }
    }
    

    第8步

    处理通用异常,仅在页面显示路径。

    //定义exceptionghandler解决为被controller层吸收的exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex) {
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setStatus("fail");
        commonReturnType.setData(ex);
        return commonReturnType;
    }
    

    第9步

    进一步优化处理异常,让页面之间显示错误信息,把处理异常的信息类封装到另一个包中。

    新建一个BaseController,让UserController继承

    public class BaseController {
        //定义exceptionghandler解决为被controller层吸收的exception
        @ExceptionHandler(Exception.class)
        @ResponseStatus(HttpStatus.OK)
        @ResponseBody
        public Object handlerException(HttpServletRequest request, Exception ex) {
    
            //必须自己封装data对象,否则data为exception反序列化的对象
            Map<String,Object> responseData = new HashMap<>();
    
            if(ex instanceof BusinessException){
                BusinessException bussinessException = (BusinessException) ex;
                responseData.put("errCode",bussinessException.getErrCode());
                responseData.put("errMsg",bussinessException.getErrMsg());
            } else {
                responseData.put("errCode", EmBusinessError.UNKNOW_ERROR.getErrCode());
                responseData.put("errMsg",EmBusinessError.UNKNOW_ERROR.getErrMsg());
    
            }
            return CommonReturnType.create(responseData,"fail");
    
        }
    }
    

    第10步

    模型类的管理--otp验证码获取

    在controller层加入otp验证码,可以在打印台上调试,看到测试数据是否传入

    @Autowired
    HttpServletRequest httpServletRequest;
    
    //用户获取otp短信接口
    @RequestMapping("/getotp")
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name = "telphone")String telphone){
        //需要按照一定规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt +=10000;
        String otpCode = String.valueOf(randomInt);
    
        //将OTP验证同对应用户的手机号关联,使用HTTP session的方式绑定(redis非常适用)
        httpServletRequest.getSession().setAttribute(telphone,otpCode);
    
        //将OTP验证码通过短信通道发送给用户,省略
        System.out.println("telphone ="+telphone + " & otpCode =" +otpCode);
    
        return CommonReturnType.create(null);
    }
    

    第11步

    用户getotp页面实现

    编写getotp.html页面,在controller加上响应方法和响应类型,为了防止拦截跨站请求,加上@CrossOrigin注解,最后的效果,前端页面出现动态效果,可以在控制台上看到请求的信息。

    编写getotp.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
        <script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
    </head>
    
    <body >
    <div >
        <h3 >获取opt信息</h3>
        <div >
            <label>手机号</label>
            <div>
                <input  type="text" placeholder="手机号" name="telphone" id="telphone"/>
            </div>
        </div>
        <div >
            <button  id="getotp" type="submit">
                获取otp短信
            </button>
        </div>
    </div>
    </body>
    
    <script>
        // 页面渲染成功才可以操作
        jQuery(document).ready(function(){
    
            //绑定otp的click事件用于像后端发送获取手机验证码请求
            $("#getotp").on("click",function(){
                var telphone = $("#telphone").val();
    
                if(telphone == null || telphone == ""){
                    alert("手机号不能为空");
                     return false;
                }
                $.ajax({
                    type:"POST",
                    contentType:"application/x-www-form-urlencoded",
                    url:"http://localhost:8090/user/getotp",
                    data:{
                        "telphone":$("#telphone").val(),
                    },
    
                    success:function(data){
                        if(data.status == "success"){
                            alert("otp已经发送到了手机,请注意查收");
    
                        } else {
                            alert("otp发送失败,原因为" + data.data.errMsg);
                        }
                    },
                    error:function(data){
                        alert("otp发送失败,原因为," + data.responseText);
                    }
                });
                return false;
            });
        });
    </script>
    </html>
    

    在BaseController定义

    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";
    

    在UserController类要重新定义请求方法和请求类型,

    @RequestMapping(value = "/getotp",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    

    第12步

    getotp页面优化

    引入css样式,为前端美化即可。

    第13步

    用户注册功能实现

    ​ 新增用户注册功能,在controller编写实现逻辑,编写用户注册接口,在接口增加注册类,编写实现方法,添加apache。commons-lang3依赖,

    controller层

    @RequestMapping(value = "/register", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    //用户注册接口
    public CommonReturnType regist(@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="password")String password) throws BusinessException {
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);
        if (!com.alibaba.druid.util.StringUtils.equals(otpCode,inSessionOtpCode)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"短信验证码不符合");
        }
        //用户注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(MD5Encoder.encode(password.getBytes()));
    
        userService.register(userModel);
        return CommonReturnType.create(null);
    }
    

    实现类

    @Override
    @Transactional
    public void register(UserModel userModel) throws BusinessException {
        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);
    
        }
        //实现model->dataobject方法
        UserDO userDO = convertFromModel(userModel);
        //使用insertSelective而不是insert,insertSelective会将对象为null的字段不进行插入,使这个字段依赖数据库的默认值。
        userDOMapper.insertSelective(userDO);
    
        UserPasswordDO  userPasswordDO = convertPasswordFromModel(userModel);
        userPasswordDOMapper.insertSelective(userPasswordDO);
    
        return;
    }
    
    private UserPasswordDO convertPasswordFromModel(UserModel userModel ){
        if(userModel == null) {
            return null;
        }
        UserPasswordDO userPasswordDO = new UserPasswordDO();
        userPasswordDO.setEncrptPassword(userModel.getEncrptPassword());
        userPasswordDO.setUserId(userModel.getId());
        return userPasswordDO;
    }
    private UserDO convertFromModel(UserModel userModel){
            if(userModel == null) {
                return null;
            }
            UserDO userDO = new UserDO();
            BeanUtils.copyProperties(userModel,userDO);
            return userDO;
     }
    

    第14步

    编写用户注册前端页面,

    与后端页面做出响应,为了避免前端跨站请求不到,解决跨域请求对ajax的共享,需要在controller层@CrossOrigin仔细注明allowCredentials = "true",allowedHeaders = "*",DEFAULT_ALLOWED_HEADERS:允许跨域传输所有的header参数,将使用token放入header域做session共享的跨站请求,DEFAULT_ALLOW_CREDENTIALS =true: 需配合前端设置 xhrFields 授信后使得跨域session共享。

    使用封装的MD5加密有问题,需要自己修改,发现user_id 为0,需要在XML里指定数据库id,为了保证注册功能的唯一性,需要在数据库里面指定telephone指定为唯一索引,还要在前端给用户相应的提示。

    编写register.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="static/assets/global/css/components.css" rel="stylesheet" type="text/css"/>
        <link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
        <script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
    </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="text" placeholder="密码" name="password" id="password">
            </div>
        </div>
    
    
    
        <div class="form-actions">
            <button class="btn blue" id="register" type="submit">
                提交注册
            </button>
        </div>
    </div>
    </body>
    
    <script>
        // 页面渲染成功才可以操作
        jQuery(document).ready(function(){
    
            //绑定otp的click事件用于像后端发送获取手机验证码请求
            $("#register").on("click",function(){
                var telphone = $("#telphone").val();
             var otpCode = $("#otpCode").val();
             var name = $("#name").val();
             var gender = $("#gender").val();
             var age = $("#age").val();
             var password = $("#password").val();
                if(telphone == null || telphone == ""){
                    alert("手机号不能为空");
                }
                if(password == null || password == ""){
                    alert("密码不能为空");
                    // return false;
                }
                if(age == null || age == ""){
                    alert("年龄不能为空");
                    // return false;
                }
                if(gender == null || gender == ""){
                    alert("性别不能为空");
                    // return false;
                }
                if(name == null || name == ""){
                    alert("姓名不能为空");
                    // return false;
                }
    
                $.ajax({
                    type:"POST",
                    contentType:"application/x-www-form-urlencoded",
                    url:"http://localhost:8090/user/register",
                    data:{
                   "telphone": telphone,
                   "otpCode": otpCode,
                   "name": name,
                   "gender": gender,
                   "age": age,
                   "password": password
                    },
    
                    xhrFields:{
                   withCredentials:true
                },
                    success:function(data){
                        if(data.status == "success"){
                            alert("注册成功");
                            window.location.href("login");
                        } else {
                            alert("注册失败,原因为" + data.data.errMsg);
                        }
                    },
                    error:function(data){
                        alert("otp发送失败,原因为," + data.responseText);
                    }
                });
                return false;
            });
        });
    </script>
    </html>
    

    修改MD5加密

    public String enCodeByMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        // 确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        // 加密字符串
        String newStr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newStr;
    }
    

    第15步

    编写用户登入接口,先增加用户登入接口,在UserDOMMapper.xml增加 一条通过用户手机查询的SQL语句,接着编写实现类,最后变现controller层,后端功能完成之后,接着编写登入的前端界面,之后验证登入界面登入功能响应成功,注册窗口跳转成功。

    增加一个接口

    UserModel validateLogin(String telphone,String encrptPassword) throws BusinessException;
    

    在xml文件增加一个查询语句,之后要在补上相应的接口

    <select id="selectByTelphone"  resultMap="BaseResultMap">
      <!--
        WARNING - @mbg.generated
        This element is automatically generated by MyBatis Generator, do not modify.
        This element was generated on Sat Nov 28 21:45:00 CST 2020.
      -->
      select
      <include refid="Base_Column_List" />
      from user_info
      where telphone = #{telphone,jdbcType=VARCHAR}
    </select>
    

    编写逻辑实现类

    //用户登陆接口
    @RequestMapping(value = "/login", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType register(@RequestParam(name = "telphone") String telphone,
                                     @RequestParam(name="password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        if(org.apache.commons.lang3.StringUtils.isEmpty(telphone)||
                StringUtils.isEmpty(password)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        //用户登陆服务,用来校验用户登陆是否合法
        UserModel userModel =userService.validateLogin(telphone,this.EnCodeByMD5(password));
    
        //将登陆凭证加入到用户登陆成功的session中
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
    
        return CommonReturnType.create(null);
    }
    

    登入界面login.html

    <!DOCTYPE html>
    <html>
    
    <head>
            <meta charset="utf-8">
            <title></title>
            <link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
            <link href="static/assets/global/css/components.css" rel="stylesheet" type="text/css"/>
            <link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
            <script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
    </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="password" placeholder="密码" name="password" id="password">
             </div>
          </div>
          <div class="form-actions">
             <button class="btn blue" id="login" type="submit">
                登录
             </button>
             <button class="btn green" id="register" type="submit">
                注册
             </button>
          </div>
       </div>
    </body>
    
    <script>
       $(document).ready(function() {
          $("#register").on("click", function() {
             window.location.href="getotp.html";
          });
    
          $("#login").on("click", function() {
             var telphone = $("#telphone").val();
             var password = $("#password").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://localhost:8090/user/login",
                data: {
                   "telphone": telphone,
                   "password": password
                },
                xhrFields:{
                   withCredentials:true
                },
                success: function(data) {
                   if (data.status == "success") {
                      alert("登录成功");
                      window.location.href="listitem.html";
                   } else {
                      alert("登录失败,原因为" + data.data.errMsg);
                   }
                },
                error: function(data) {
                   alert("登录失败,原因为" + data.responseText);
                }
             });
             return false;
          });
       });
    </script>
    
    </html>
    
  • 相关阅读:
    《真是头铁的》 回复
    今天 凌晨, 我 的 许多 帖子 (回复) 被 反相吧 吧务 删除
    《【建议】吧务同志们每个礼拜写一篇规范论文》 回复
    《有个数学模型想咨询下吧友的意见》 回复
    《请大家推荐反相吧大吧主》 回复
    复变函数 和 积分变换 就是 自己 设定 一套规则 自己 玩
    《这是等臂杠杆还是省力杠杆?》 回复
    《我的理论转帖讨论》 回复
    《数学已经明确了,0.999...与1是完全相等的》 回复
    和 @物空必能 的 对话
  • 原文地址:https://www.cnblogs.com/zzy8080/p/14077135.html
Copyright © 2020-2023  润新知