快速掌握shiro安全框架(三)之集成thymeleaf前端页面

1、pom文件加thymeleaf所需jar包

<!-- thymeleaf所需JAR包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、在resources目录下新建templates文件夹,在此文件夹下新建login.html文件作为登录页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/myController/userLogin">
    <div>用户名:<input type="text" name="name" value=""></div>
    <div>密码:<input type="password" name="pwd" value=""></div>
    <div><input type="submit" value="登录"></div>
</form>
</body>
</html>

3、再新建一个main.html作为登录成功后的展示页

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Shiro 登录认证后主页面</h1>
<br>
登录用户为:<span th:text="${session.user}"></span>
</body>
</html>

4、在LoginController.class中加login的方法,用于跳转登录页面,改造userLogin方法,方法体中加入HttpSession,用于前端使用,return给main页面进行展示

package com.wxg.springbootshiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/myController")
public class LoginController {

    @GetMapping("/login")
    public String login(){
       return "login";
    }

    @GetMapping("/userLogin")
    public String userLogin(String name, String pwd, HttpSession session){
        //获取subject对象
        Subject subject=SecurityUtils.getSubject();
        //将用户信息封装到token请求中
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        //登录
        try {
            subject.login(token);
            session.setAttribute("user",token.getPrincipal().toString());
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            return "登录失败!";
        }
    }
}

5、application.yml中添加shiro默认登录地址

shiro:
  loginUrl: /myController/login

6、项目结构如下

 7、验证是否集成成功,在浏览器输入http://localhost:8080/myController/login

8、输入用户名密码,点击登录后

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值