精华内容
下载资源
问答
  • 实体类 @Data @AllArgsConstructor @NoArgsConstructor public class User { private String username; private String password; } ... User getUsers(String username,String password);...mapper

    实体类

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

    接口

    @Mapper
    @Repository
    public interface UserMapper {
        User getUsers(String username,String password);
    }
    

    SQL语句

    <mapper namespace="com.li.Mapper.UserMapper">
        <select id="getUsers" resultMap="UserMap">
            select * from user where username=#{username} AND password=#{password}
        </select>
        
        <resultMap id="UserMap" type="User">
            <result property="username" column="username"></result>
            <result property="password" column="password"/>
        </resultMap>
    
    </mapper>
    

    数据库表
    在这里插入图片描述
    controller层

    @RequestMapping("/index")
        public String user(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           Model model,
                           HttpSession session) {
            User login = userMapper.getUsers(username,password);
            if (login!=null) {
                session.setAttribute("loginUser", username);
                return "redirect:/dash";
            } else {
                model.addAttribute("msg", "用户名或密码错误");
                return "index";
    
            }
        }
    
    展开全文
  • 登录功能 Controller: 拦截器: controller: @GetMapping("/login") public String login(){ return "login"; } @RequestMapping("/tologin") public String tologin(@RequestParam("username") String ...

    登录功能

    Controller:
    在这里插入图片描述

    拦截器:

    controller:

      @GetMapping("/login")
        public String login(){
            return "login";
        }
        @RequestMapping("/tologin")
        public String tologin(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              Model model, HttpSession session){
            if (!StringUtils.isEmpty(username) && "123456".equals(password)){
                session.setAttribute("loginUser",username);        //登录成功后session获取到值
                return "redirect:/index";
            }else {
                model.addAttribute("msg","用户名或密码错误");
                return "login";
            }
    }
    

    config
    LoginHandlerIntercaptor

    public class LoginHandlerInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //登录成功后应该有用户的session
            Object loginUser = request.getSession().getAttribute("loginUser");    //loginUser接收session的值
            if(loginUser==null){     //如果没有登录                                    //如果loginUser session的值为空,返回主页面登录
                request.setAttribute("msg","请先返回主页面登录");
                request.getRequestDispatcher("/login.html").forward(request,response);  //只要执行到此语句之后则立刻进行跳转,可以传递request属性。服务器端跳转,地址栏内容不变(即客户端浏览器的地址栏不会显示跳转后地址的URL)。客户端请求到达以后,服务器发现当前资源给不出回应,要在服务器内部请求另一个资源的跳转,即服务器端跳转。所以,这种跳转与否客户端不知道(URL不变),属于一次request。
                return false;
            }else {
                return true;
            }
        }
    }
    

    config
    MyConfig

     @Override
        public void addInterceptors(InterceptorRegistry registry) {       //拦截器
            registry.addInterceptor(new LoginHandlerInterceptor())        //获取
                    .addPathPatterns("/**")   //拦截全部
                    .excludePathPatterns("/login.html","/tologin","/img/**","/layui/**","/style.css");  //放行的功能
            }
    

    登录页面:login
    使用了layui组件

    <body>
    <div class="box">
        <h2>后台管理</h2>
        <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
        <form action="tologin" method="post">
            <div class="inputBox">
                <input type="text" name="username" required="">
                <label>Username</label>
            </div>
            <div class="inputBox">
                <input type="password" name="password" required="">
                <label>password</label>
            </div>
            <input type="submit" name="" value="登录">
            <input type="submit" value="注册" style="float:right;">
        </form>
    
    </div>
    <!-- 你的HTML代码 -->
    
    <script src="./layui/layui.js"></script>
    <script>
        //一般直接写在一个js文件中
        layui.use(['layer', 'form'], function(){
            var layer = layui.layer
                ,form = layui.form;
    
            // layer.msg('Hello World');
        });
    </script>
    </body>
    

    直接请求index,失败返回登录页面
    在这里插入图片描述
    输入账号密码,登录成功,进入index页面
    在这里插入图片描述

    展开全文
  • springBoot登录、注册功能的实现,适用于新手小白,Tomcat端口号为8088
  • 在实际开发中,我们经常会遇到某些页面需要登录才能查看的情况。下面使用拦截器实现该功能,在用户没有登录的情况下,将网站的所有访问都指向登录页面。
  • vue+springboot 登录注册功能

    千次阅读 2020-06-01 22:25:49
    } </style> 7、新建login.vue组件 <template> <div> <body id="poster"> <el-form class="login-container" label-position="left" label-width="0px"> 系统登录</h3> <el-form-item> 账号">...

    一、前端

    1、搭建前端项目

    需要用到node的npm,先下载安装node,官网https://nodejs.org/zh-cn/
    在这里插入图片描述
    在命令窗口输入命令:

    npm -v
    node -v
    npm install webpack -g
    npm install vue-cli -g

    在本地新建一个项目文件夹,打开命令窗口cd到项目文件夹,然后按下图操作:(只有一个输入No,其他Yes)
    在这里插入图片描述
    完成后:
    在这里插入图片描述

    2、用VScode打开项目文件夹即可

    3、安装element ui

    在控制台输入命令:

    npm i element-ui -S
    

    4、在main.js中引入

    import ElementUI from 'element-ui'
    import 'element-ui/lib/theme-chalk/index.css'
    Vue.use(ElementUI);
    

    5、目录结构

    在这里插入图片描述

    6、新建register.vue组件

    <template>
      <body id="paper">
      <el-form :model="registerForm" :rules="rules" class="login-container" label-position="left"
               label-width="0px" v-loading="loading">
        <h3 class="login_title">用户注册</h3>
        <el-form-item prop="username">
          <el-input type="text" v-model="registerForm.username"
                    auto-complete="off" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="registerForm.password"
                    auto-complete="off" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item prop="passwordConfirm">
          <el-input type="password" v-model="registerForm.passwordConfirm"
                    auto-complete="off" placeholder="确认密码"></el-input>
        </el-form-item>
    
        <el-form-item style="width: 100%">
          <el-button type="primary" style="width: 100%;background: #505458;border: none;" v-on:click="register">立即注册</el-button>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button type="primary" style="width: 100%;background: #505458;border: none;" v-on:click="tologin">返回</el-button>
        </el-form-item>
      </el-form>
      </body>
    </template>
    
    <script>
    export default{
      name: 'Register',
      data () {
        return {
          rules: {
            username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
            password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
            passwordConfirm: [{required: true, message: '密码不能为空', trigger: 'blur'}]
          },
          checked: true,
          registerForm: {
            username: '',
            password: '',
            passwordConfirm: ''
          },
          loading: false
        }
      },
      methods: {
        register () {
          var _this = this
          if (this.registerForm.password !== this.registerForm.passwordConfirm) {
            this.$message({
              message: '两次输入的密码不一致',
              type: 'error'
            })
            return
          }
          this.axios.post("/register",{
                username:this.registerForm.username,
                password:this.registerForm.password,
              })
            .then(function (response) {
                // console.log(response.data.status)
                if(response.data.status === 200){
                  alert("恭喜你,注册成功")
                //   _this.$message({
                //   message: '恭喜你,注册成功',
                //   type: 'success'
                // })
                _this.$router.replace('/login')
                }
                else {
                  _this.$message({
                  message: '该用户名已存在,请更换一个',
                  type: 'error'
                })
                }
              })
            .catch(function (error) {
                console.log(error)
              })
        },
        tologin () {
          this.$router.replace('/login')
        }
      }
    }
    </script>
    
    <style>
      #paper {
        /*background:url("../assets/img/bg/eva1.jpg") no-repeat;*/
        background-position: center;
        height: 100%;
        width: 100%;
        background-size: cover;
        position: fixed;
      }
      body{
        margin: -5px 0px;
      }
      .login-container {
        border-radius: 15px;
        background-clip: padding-box;
        margin: 160px auto;
        width: 350px;
        padding: 35px 35px 15px 35px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
      }
      .login_title {
        margin: 0px auto 40px auto;
        text-align: center;
        color: #505458;
      }
      .login_remember {
        margin: 0px 0px 35px 0px;
        text-align: left;
      }
    </style>
    

    7、新建login.vue组件

    <template>
      <div>
        <body id="poster">
        <el-form class="login-container" label-position="left"
                 label-width="0px">
          <h3 class="login_title">系统登录</h3>
          <el-form-item>
            <el-input type="text" v-model="loginForm.username"
                      auto-complete="off" placeholder="账号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input type="password" v-model="loginForm.password"
                      auto-complete="off" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item style="width: 100%">
            <el-button type="primary" style="width: 100%;background: #505458;border: none" v-on:click="login">登录</el-button>
          </el-form-item>
          <el-form-item style="width: 100%">
            <el-button type="primary" style="width: 100%;background: #505458;border: none" v-on:click="toregister">没有账号?去注册</el-button>
          </el-form-item>
           <el-form-item style="width: 100%">
            <el-button type="primary" style="width: 100%;background: #505458;border: none" v-on:click="tohome">游客模式</el-button>
          </el-form-item>
        </el-form>
        </body>
        <div></div>
      </div>
    </template>
    <script>
        export default {
          name: "Login",
          data() {
            return {
              loginForm:{
                username:'admin',
                password:'123'
              }
            }
          },
          methods: {
            login(){
              var _this = this
              this.axios.post("/login",{
                username:this.loginForm.username,
                password:this.loginForm.password,
              })
              .then(function (response) {
                // console.log(response.data.status)
                if(response.data.status === 200){
                  _this.$message({
                    message: '登录成功',
                    type: 'success'
                  })
                  _this.$store.commit('login',response.data.object)
                  // _this.$router.push({path: '/'})
                  var path = _this.$route.query.redirect
                  _this.$router.replace({path:path === undefined ? '/' : path})
                }
                else {
                  // alert("账号或密码错误")
                  _this.$message({
                  message: '账号或密码错误',
                  type: 'error'
                })
                }
              })
              .catch(function (error) {
                console.log(error)
              })
            },
            toregister(){
              this.$router.replace('/register')
            },
            tohome(){
              this.$router.replace('/home')
            }
          }
        }
    </script>
    
    
    <style>
      #poster {
        background-image: url("../../static/homeMask.png");
        height: 100%;
        width: 100%;
        background-size: cover;
        position: fixed;
      }
    
      body {
        margin: 0px;
      }
    
      .login-container {
        border-radius: 15px;
        background-clip: padding-box;
        margin: 90px auto;
        width: 350px;
        padding: 35px 35px 15px 35px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
      }
    
      .login_title {
        margin: 0px auto 40px auto;
        text-align: center;
        color: #505458;
      }
    
    </style>
    

    8、在router/index.js引入组件并配置路由

    import Vue from 'vue'
    import Router from 'vue-router'
    import Register from "../components/Register";
    import Login from "../components/Login";
    import Home from "../components/home/Home";
    
    Vue.use(Router)
    
    export default new Router({
      mode: 'history',
      routes: [
        {
          path: '/register',
          name: 'Register',
          component: Register
        },
        {
          path: '/login',
          name: 'Login',
          component: Login
        }
      ]
    })
    
    

    9、main.js

    // The Vue build version to load with the `import` command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    import App from './App'
    import router from './router'
    
    import axios from 'axios'
    import VueAxios from 'vue-axios'
    
    import store from "./store";
    
    
    Vue.config.productionTip = false
    Vue.use(ElementUI);
    
    axios.defaults.baseURL = "/api"
    axios.defaults.withCredentials = true
    Vue.use(VueAxios,axios);
    
    Vue.use(mavonEditor)
    
    router.beforeEach((to,from,next) =>{
      if(to.meta.requireAuth){
        // alert(store.state.currentUser)
        if(store.state.currentUser !== null && store.state.currentUser){
          next()
        }
        else{
          next({
            path:'/login',
            query: {redirect: to.fullPath}
          })
        }
      }
      else{
        next()
      }
    })
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })
    
    

    二、后端

    1、搭建后端项目

    在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

    2、设计数据库(user表)

    在这里插入图片描述

    3、pom.xml

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.southwind</groupId>
        <artifactId>springboottest</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboottest</name>
        <description>Demo project for Spring Boot</description>
        <packaging>jar</packaging>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
    
            <!-- springboot tomcat 支持 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <!--jpa-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <!--shiro-->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <!-- mvn 打包依赖 -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
    
        </build>
    
    </project>
    
    

    4、新建pojo包,在pojo包下新建User

    User.java

    package com.southwind.springboottest.entity;
    
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name = "user")
    @JsonIgnoreProperties({"heandler","hibernateLazyInitializer"})
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        int id;
        String username;
        String password;
        String salt;
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getSalt() {
            return salt;
        }
    
        public void setSalt(String salt) {
            this.salt = salt;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    }
    

    5、新建dao包,在dao包下新建UserDao

    UserDao.java

    package com.southwind.springboottest.repository;
    
    import com.southwind.springboottest.entity.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Integer> {
        User findByUsername(String username);
    }
    
    

    6、新建service包,在service包下新建UserService

    UserService.java

    package com.southwind.springboottest.service;
    
    import com.southwind.springboottest.entity.User;
    import com.southwind.springboottest.repository.UserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService {
        @Autowired
        UserRepository userRepository;
    
        public User getUserByUsername(String username){
            return userRepository.findByUsername(username);
        }
    
        public boolean isExist(String username){
            User user = getUserByUsername(username);
            return user!=null;
        }
    
        public void addUser(User user){
            userRepository.save(user);
        }
    }
    
    

    7、新建controller包,在controller包下新建UserController

    UserController.java

    package com.southwind.springboottest.controller;
    
    import com.southwind.springboottest.Response.Response;
    import com.southwind.springboottest.entity.User;
    import com.southwind.springboottest.service.UserService;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.crypto.SecureRandomNumberGenerator;
    import org.apache.shiro.crypto.hash.SimpleHash;
    import org.apache.shiro.subject.Subject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.util.HtmlUtils;
    
    @Controller
    public class UserController {
        @Autowired
        UserService userService;
    
        @CrossOrigin
        @PostMapping("api/register")
        @ResponseBody
        public Response Register(@RequestBody User user){
            String username = user.getUsername();
            username = HtmlUtils.htmlEscape(username);
            user.setUsername(username);
            String password = user.getPassword();
    
            boolean isExist = userService.isExist(username);
            if (isExist){
                return new Response(500,"failure",null);
            }
            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            int times = 2;
            String algorithm = "md5";
            String pwdAfterHash = new SimpleHash(algorithm,password,salt,times).toString();
            user.setSalt(salt);
            user.setPassword(pwdAfterHash);
            userService.addUser(user);
            return new Response(200,"success",null);
        }
    
        @CrossOrigin
        @PostMapping("api/login")
        @ResponseBody
        public Response login(@RequestBody User user){
            String username = user.getUsername();
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,user.getPassword());
    
            try{
                subject.login(usernamePasswordToken);
                return new Response(200,"success",usernamePasswordToken);
            }catch (AuthenticationException e){
                return new Response(500,"failure",null);
            }
        }
    
        @CrossOrigin
        @GetMapping("api/logout")
        @ResponseBody
        public Response logout(){
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return new Response(200,"登出",null);
        }
    }
    
    

    8、application.yml

    spring:
      datasource:
       
        url: jdbc:mysql://localhost:3306/user_country?useUnicode=true&characterEncoding=UTF-useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
        username: root
        password: xxxxxx
        driver-class-name: com.mysql.jdbc.Driver
      jpa:
        show-sql: true
        properties:
          hibernate:
            format_sql: true
    server:
      port: 8443
    

    未完待续…

    展开全文
  • springboot实现登录功能

    千次阅读 2020-07-30 19:04:37
    今天是接触springboot框架的第三天,看了几个项目,终于完全自行实现了一次登录功能,虽然很简陋,还是挺开心的. 下面就开始很详细的讲解了: 首先当然是建立数据库表,我建立了一个非常简单的数据库表user,只有三个字段,...
    1. 转眼间已经来到公司一个月了,一直都没时间写博客,今天趁着自己调试到心态爆炸,又正好积累了一堆bug经验,赶快记录一下.
    2. 先感叹一下,在公司和学校效率完全不是一个层次,工作催动可比作业催动快多了.
    3. 今天是接触springboot框架的第三天,看了几个项目,终于完全自行实现了一次登录功能,虽然很简陋,还是挺开心的.

    下面就开始很详细的讲解了:

    首先当然是建立数据库表,我建立了一个非常简单的数据库表user,只有三个字段,账户名,密码和访问级别(因为马上要做权限管理嘛)
    在这里插入图片描述

    1. 然后就是建立项目了,总而言之就是用spring start功能,导入web,jdbc,mysql,mybatis(我现在只知道是用来绑定mapper和xml的,持久层框架.)
      这里最重要的是要一行一行的讲清楚

    配置文件yml

    到底在干什么.

    你们如果要复制就把所有汉字删掉就行,注意在配置文件中最好连汉字注释都不要出现,容易报不知道什么鬼的错
    server:
      port: 8080 //简单就是服务器端口号,在springboot里直接访问端口号,
    //springboot会去检测resource文件夹下static文
    //件夹下里有没有叫index.html的,会做为这个端
    //口号的欢迎页,简而言之就是你去访问端口号就会展示欢迎页
      
      注意属性和值之间要有空格,属性和子属性之间有两个空格
    spring:
      datasource://数据源嘛
        url: jdbc:mysql://localhost:3306/demodb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=false&useSSL=false
       //在这里我就要爆炸了,cj.jdbc要放时区,而且时区很容易出错,反正很烦
        username: root//账号密码没什么好说的
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver//注意版本不同是有时区之分的
    
    mybatis:
      mapper-locations: classpath:mapper/*.xml  //持久层框架,很重要哦,这一行是确定你的xml(就是增删改查)文件要到哪里去找,xml文件一般都放在resources下面mapper文件夹.
      type-aliases-package: com.vanchip.model //注意,这是要绑定实体类的,反正不能填错
        
    logging:
      level:
        org.springframework.web: TRACE  //日志级别,最重要的功能是看映射地址
        
        
    spring.thymeleaf.prefix: classpath:/templates/  前端框架,目前还不太会用,不过这两行代码很明显了,就是说我的文件是去哪里找,这文件是html就完事了
    spring.thymeleaf.suffix: .html
    

    建包分层

    **了,你以为这是很常见的,所以就没什么坑了吧,想多了,一定要保证包名一致.在这里插入图片描述
    大概应该是这类型的,如果包名的格式不是很正确,然后就会发现,springboot一会扫不到配置类,一会又扫不到service,因为要依赖注入嘛,所以,我们只使用抽象类就行,有框架进行依赖注入,把实现类导进去.
    分层结构差不多也是这样.
    聪明的孩子会发现少了一个controller层,为什么呢?因为我一开始设置了controller层,然后悲剧的发现根本就映射不到.
    这里有一个知识点;controller层必须放在启动类的子包或者同级才能被检测到,才能实现映射,我在这卡了半天,抓狂
    所以正常情况下建议启动类直接拖到分层包外面去,应该是最安全的.
    **

    分层架构

    **(自己的理解)
    我是推荐新人阅读代码最好要分层来读,跟着一个附带增删改查的功能从头追到尾,而且尽量不要横向发展,否则会很晕的.

    一个请求从浏览器发出,到被拦截器拦截,然后拦截器分配一下地址,不对的访问就给你转发到登录页面.对的基本就是游客身份登录或者怎样.
    然后 在进入登录界面以后,你的登录信息会作为表单也好,参数也罢,开始被controller层接收

    超简单的前端

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>administer,welcome to login Vanchip exam-online system!</title>
    
    </head>
    <body>
    	<form method="post" action="admin/login">//表单访问的映射地址\以及传输方式
    		<label>welcome! administer!</label>
    		<p>
    			<input type="text" value="请输入您的账户" name="username" id="username">//注意name是要传到服务器的属性,id主要是前端样式用的
    		</p>
    		<input type="text" value="请输入您的密码" name="password" id="password">
    		<p>
    			<input type="submit" value="登录" >//就是提交表单嘛.
    		</p>
    
    	</form>
    </body>
    </html>
    

    然后当你提交表单之后,服务器将你的信息提交到映射处,也就是

    controller层

    package com.vanchip.logintest;
    import java.lang.ProcessBuilder.Redirect;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.ibatis.annotations.Param;
    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.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.vanchip.model.User;
    import com.vanchip.service.UserService;
    
    @RequestMapping("/admin")//整个类的映射地址,后面方法映射地址是叠加的
    @Controller//告诉springboot这是controller层,记得把映射搞上去
    public class LoginController {
    	@Autowired//这里是调用的service抽象层的类,以后用,这里的@Autowired应该是说把service实现层的方法加载到这个抽象层容器里
    	UserService UserService;
    
    	@ResponseBody //加上这个注解,返回的就不是地址了,而是一段文本,我这只是看下成功没,正常应该在成功后跳转到其他页面
    	@RequestMapping("/login")//映射嘛
    	public String login(@RequestParam(name = "username", required = true) String username,
    			@RequestParam(name = "password", required = true) String password, HttpServletRequest req,
    			HttpServletResponse res) {//在这里引入了参数,也就是前端传进来的参数,似乎@RequestParam可以去找传进来的参数,当然是用name进行匹配了,
    			//下面两个对象,我其实不知道为啥要加,但是调试的时候总是出错,然后试了一下设置返回文本的格式居然就可以了,我^&*&
    		res.setCharacterEncoding("utf-8");
    		User user = UserService.login(username, password);//调用service层抽象类方法,返回一个承接了数据库返回值的实体类
    		if (user != null) {//很简单的逻辑,返回的只要不是空值就说明是存在的,ok
    			System.out.println(user.toString());
    			return "welcome adminster!" + user.toString();//返回一段文本
    
    		}
    		return "/err";//返回到另一个界面,但是目前还没做
    	}
    
    	@RequestMapping("/s")
    	@ResponseBody
    	private String sen(String info) {
    		return info;
    
    	}
    
    	@RequestMapping("/err")
    	@ResponseBody
    	private String err() {
    		return "登录失败";
    
    	}
    }
    
    

    那么,应该会注意到,controller核心接收前后端数据并且返回,总而言之就是通信层.在这个登录方法里最重要的是service层的方法返回值是怎么样的.

    service抽象层

    package com.vanchip.service;
    
    import org.springframework.stereotype.Service;
    
    import com.vanchip.model.User;
    
    public interface UserService {
    	User login(String username, String password);//就把方法写上去,参数返回值就没了
    }
    
    

    service实现层

    package com.vanchip.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.vanchip.mapper.userMapper;
    import com.vanchip.model.User;
    import com.vanchip.service.UserService;
    
    @Service//注意需要进行注解,不然是扫描不到这是实现层的
    public class UserServiceImpl implements UserService {
    //我个人觉得其实springboot是通过接口引用来确定谁是要装载的抽象层的.
    
    	@Autowired
    	userMapper userMapper;//没什么说的,还是自动装载了mapper抽象层
    
    	@Override
    	public User login(String username, String password) {
    		User user = userMapper.getbycond(username, password);//使用了mapper层方法,现在看着简单和多此一举,但实际上,等业务逻辑复杂就不是简单引用方法,
    		//而是要对mapper层增删改查加上算法和业务逻辑写在这里才行.
    		return user;
    
    	}
    
    }
    
    

    mapper抽象层

    package com.vanchip.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    
    import com.vanchip.model.User;
    
    @Mapper
    public interface userMapper {
    //@Param("username")  @Param("password") //我原来看他们还写了参数叫什么,但是我发现好像反而会造成mapper实现层参数混乱,我去掉就正常了
    	User getbycond(String name,String pwd);
    
    }
    
    

    mapper实现层

    这是增删改查放的地方

    <?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.vanchip.mapper.userMapper">//注意命名空间就是框架绑定的依据哈
    
    
    	<sql id="base_table">
    		user//这是定义了一个属性,方便重复利用罢了
    	</sql>
    	<select id="getbycond" resultType="com.vanchip.model.User">
    		select * from
    		<include refid="base_table" />
    		where id=#{name,jdbcType=VARCHAR}//这就是简单的上个参数和在数据库里的类型,会自动调成实体类能接受的类型
    		and
    		password=#{pwd,jdbcType=VARCHAR}
    	</select>
    //这就是核心部分了,id是说和抽象层哪一个方法绑定,返回值把实体类拉进来自动去绑,而且会根据数据库和实体类自动调整哦.
    
    </mapper>
    

    实体类

    没什么好说的,不过放上来把

    package com.vanchip.model;
    
    import java.io.Serializable;
    
    @SuppressWarnings("serial")
    public class User implements Serializable {
    	String id;
    	String password;
    	Integer accesslevel;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public Integer getAccesslevel() {
    		return accesslevel;
    	}
    
    	public void setAccesslevel(Integer accesslevel) {
    		this.accesslevel = accesslevel;
    	}
    
    	@Override
    	public String toString() {
    
    		return String.format("当前登录账户为"+id+",密码为 %s,访问等级为 %d", password, accesslevel);
    	}
    }
    
    

    最后的重点启动类

    package com.vanchip.logintest;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @MapperScan("com.vanchip.mapper")//表明mapper抽象层在哪里,方便装配
    @SpringBootApplication(scanBasePackages = {"com.vanchip"})//表明你的各种包在哪里
    public class LogintestApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(LogintestApplication.class, args);
    	}
    
    }
    
    
    展开全文
  • 用到 handlerInterceptor;...1) 重写 preHanle 方法 实现登录用户的过滤 判断是否已经登陆,未登录跳转到登录页面 2、 1)在springmvc.xml文件的mvc拦截器中加上实现HanderInterceptor的类 <mvc:interceptors...
  • SpringBoot 简单登录功能 拦截器实现。 在实际开发中,我们经常会遇到某些页面需要登录才能查看的情况。下面使用拦截器实现该功能,在用户没有登录的情况下,将网站的所有访问都指向登录页面。 Springboot 登录
  • springboot 登录注册

    2018-08-01 09:17:41
    springboot整合freemarker模板的登录注册功能,适合初学者

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,275
精华内容 1,310
关键字:

springboot登录功能

spring 订阅