项目文件夹展示

spring mvc 不登录调用接口 springmvc登录注册功能_ajax

spring mvc 不登录调用接口 springmvc登录注册功能_spring mvc 不登录调用接口_02

springmvc的各类文件的作用

spring mvc 不登录调用接口 springmvc登录注册功能_spring mvc 不登录调用接口_03

(1)创建User实体类 

package com.gem.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String username;
    private String password;
}

(2)数据库建表tbl_user

spring mvc 不登录调用接口 springmvc登录注册功能_spring mvc 不登录调用接口_04

 

(3)创建Mapper接口UserMapper.java

package com.gem.mapper;

import com.gem.entity.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    /**
     * 根据用户名和密码查询用户
     */
    User selectUserByUsernameAndPassword(@Param("username") String username, @Param("password") String password);

    /**
     * 添加用户
     */
    int insertUser(User user);

    /**
     * 根据用户名查询用户
     */
    User selectUserByUsername(String username);
}

(3) 创建UserMapper.xml,写sql语句查询数据库

<?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.gem.mapper.UserMapper">
    <select id="selectUserByUsernameAndPassword" resultType="user">
        select * from tbl_user where username=#{username} and password=#{password}
    </select>

    <insert id="insertUser" parameterType="user">
        insert into tbl_user(username,password) values(#{username},#{password})
    </insert>

    <select id="selectUserByUsername" resultType="user">
         select * from tbl_user where username=#{username}
    </select>
</mapper>

(4)定义接口(业务逻辑),创建UserService.java文件

package com.gem.service;

import com.gem.entity.User;

//业务接口
public interface UserService {
    //登陆
    User login(String username, String password);

    //注册
    void register(User user);

    //验证用户名
    User checkUsername(String username);
}

(5)对接口函数进行实现,创建 UserServiceImpl.java,通过注解,可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作

package com.gem.service.impl;

import com.gem.entity.User;
import com.gem.mapper.UserMapper;
import com.gem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 业务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper useMapper;

    @Override
    public User login(String username, String password) {
        User user = useMapper.selectUserByUsernameAndPassword(username,password);
        return user;
    }

    @Override
    public void register(User user) {
        useMapper.insertUser(user);
    }

    @Override
    public User checkUsername(String username) {
        return useMapper.selectUserByUsername(username);
    }
}

(6)创建控制器UserController.java

package com.gem.controller;

import com.gem.entity.User;
import com.gem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 显示首页
     * 当你访问路径:
     * localhost:8888/crm/user/index
     * 自动跳转到
     * /WEB-INF/jsp/login.jsp
     */
    //由于此方法就是一个路径跳转页面,所以可以通过配置默认跳转方式来实现
    /*@RequestMapping("/")
    public String index(){
        //配置视图解析器过后, 可以自动在跳转路径前和后拼接字符串,形成完整路径
        ///WEB-INF/jsp/login.jsp
        return "login";
    }*/

    //以POST方式访问localhost:8888/crm/user/login来实现登陆操作
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    //返回纯数据而非页面
    @ResponseBody
    public String login(String username, String password) {
        User user = userService.login(username, password);
        if (user != null) {
            return "1";
        }
        return "0";
    }

    @RequestMapping("/check")
    @ResponseBody
    public String check(String username) {
        User user = userService.checkUsername(username);
        if (user != null) {
            return "1";
        }
        return "0";
    }

    /**
     * 默认情况下跳转页面方式为转发,可能出现刷新反复提交问题,
     * 可以使用重定向的方式来实现跳转,避免该问题
     */
    @RequestMapping("/register")
    public String register(User user) {
        try {
            userService.register(user);
            //重定向
            return "redirect:/";
        } catch (Exception e) {
            return "error";
        }
    }
}

 (7)创造一个监听器MyPathListener.java,本类的作用是用来监听项目的启动,当项目启动时,就自动产生一个应用路径的变量供全局使用

package com.gem.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 监听器
 * 本类的作用是用来监听项目的启动,当项目启动时,就自动产生一个应用路径的变量供全局使用
 */
@WebListener
public class MyPathListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("-----服务器自动-----");
        ServletContext context = sce.getServletContext();
        String base = context.getContextPath();
        context.setAttribute("base", base);
    }
}

(8)写界面,创建login.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登陆页面</title>
    <link rel="shortcut icon" type="image/x-icon" href="${base}/assets/img/favicon.ico"/>
    <!-- CSS -->
    <link rel="stylesheet" href="${base}/assets/css/reset.css">
    <link rel="stylesheet" href="${base}/assets/css/supersized.css">
    <link rel="stylesheet" href="${base}/assets/css/style.css">
</head>
<body>
<div class="page-container">
    <h1>LOGIN</h1>
    <form>
        <span style="color:red;font-weight: bolder" id="errorHit"></span>
        <input type="text" name="username" id="username" class="username" placeholder="Username">
        <input type="password" name="password" id="password" class="password" placeholder="Password">
        <button type="button" id="loginBtn">登陆</button>
        <button style="background:#FFA07A;border: 1px solid #FFA07A" type="button" id="registerBtn">注册</button>
    </form>
    <div class="connect">
        <p>其他访问: </p>
        <p>
            <a class="weixin" href="https://wx.qq.com/"></a>
            <a class="qq" href="https://im.qq.com/"></a>
        </p>
    </div>
</div>
<!-- Javascript -->
<script src="${base}/assets/js/jquery-1.8.2.min.js"></script>
<script src="${base}/assets/js/supersized.3.2.7.min.js"></script>
<script src="${base}/assets/js/supersized-init.js"></script>
<script src="${base}/assets/js/scripts.js"></script>
<script src="${base}/assets/js/shop.js"></script>
</body>
</html>

register.jsp(与登录界面类似)

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册页面</title>
    <link rel="shortcut icon" type="image/x-icon" href="${base}/assets/img/favicon.ico"/>
    <link rel="stylesheet" href="${base}/assets/css/reset.css">
    <link rel="stylesheet" href="${base}/assets/css/supersized.css">
    <link rel="stylesheet" href="${base}/assets/css/style.css">
</head>
<body>
<div class="page-container">
    <h1>REGISTER</h1>
    <form action="${base}/user/register" method="post">
        <span style="color:red;font-weight: bolder" id="errorHit"></span>
        <input type="text" name="username" id="rName" class="username" placeholder="Username">
        <input type="password" name="password" id="rPwd" class="password" placeholder="Password">
        <input type="password" name="confirmPwd" id="cPwd" class="password" placeholder="Confirm">
        <button type="submit" style="background-color: #ccc" id="register" disabled>注册</button>
        <button style="background:#FFA07A;border: 1px solid #FFA07A" type="button" id="returnBtn">返回</button>
    </form>
</div>
<!-- Javascript -->
<script src="${base}/assets/js/jquery-1.8.2.min.js"></script>
<script src="${base}/assets/js/supersized.3.2.7.min.js"></script>
<script src="${base}/assets/js/supersized-init.js"></script>
<script src="${base}/assets/js/scripts.js"></script>
<script src="${base}/assets/js/shop.js"></script>
</body>
</html>

 (9)写ajax异步判断,创建shop.js

$(function () {
    $("#loginBtn").click(function () {
        var username = $("#username").val();
        var password = $("#password").val();

        if (username == "" || password == "") {
            $("#errorHit").html("用户名或者密码不能为空!");
        } else {
            //发送AJAX请求(异步登陆)
            $.post("/shop/user/login", {username: username, password: password}, function (data) {
                //判断登陆是否成功
                if (data == 1) {
                    //跳转下一个页面
                    window.location = "list";
                } else {
                    $("#errorHit").html("用户名或者密码有误!");
                }
            });
        }
        //清除用户名和密码输入框中的内容,并且选中用户名输入框
        $("#username").val("").select();
        $("#password").val("");
        //当重新开始输入用户名时,清空错误提示
        $("#username").keyup(function () {
            $("#errorHit").html("");
        });
    });

    $("#registerBtn").click(function () {
        window.location = "register";
    });

    $("#returnBtn").click(function () {
        window.location = "/shop";
    });

    //异步判断注册时用户名是否被使用
    $("#rName").blur(function () {
        $.post("/shop/user/check", {username: $("#rName").val()}, function (data) {
            if (data == 1) {
                //说明该用户名已经被注册
                $("#errorHit").html("该用户名已经被注册!");
                $("#rName").select();
            } else {
                $("#errorHit").html("");
            }
        });
    });

    //判断两次输入的密码是否一致
    $("#cPwd").keyup(function () {
        var p1 = $("#rPwd").val();
        var p2 = $(this).val();
        if (p1 != p2) {
            $("#errorHit").html("两次输入的密码不一致!");
        } else {
            $("#errorHit").html("");
            $("#register").css("backgroundColor", "#ef4300");
            $("#register").attr("disabled", false);
        }
    });
});

我是用idea开发,maven-3.6.3, tomcat7,java版本如下

spring mvc 不登录调用接口 springmvc登录注册功能_ajax_05

 

效果图如下:登录界面

spring mvc 不登录调用接口 springmvc登录注册功能_ajax_06

 

注册界面(包括用户名为空检测,密码不一致检测等等)

spring mvc 不登录调用接口 springmvc登录注册功能_spring_07