shiro使用jsp展示用户名补充
前面基本上已经将所有的shiro框架的急促使用,实战开发的所有内容都编写完毕了,接下来就是一些关于shiro框架的一些其他补充,比如:我们要将当前登录的用户放到首页中展示其用户名,该怎么做呢?在我们的jsp页面中,只需要shiro提供的标签就可以做到:
这个标签,就是获取当前登录人的身份信息:
可以看到当前登录人的用户名展示在了首页。
shiro与Thymeleaf整合开发
首先我们新建了一个项目,之后我们将之前的代码copy过来了,然后我们需要加一下thymeleaf的坐标来整合。首先上坐标:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
上面这个就是使用thymeleaf的坐标。
然后我们来看一下将之前的jsp页面改造为html页面:
首先是login.html:
<! doctype html>
<html lang="en" xmlns:th="http:thymeleaf.org">
<head>
<title>后台管理系统</title>
</head>
<body>
<h1>用户登录</h1>
<form th:action="@{/user/login}" method="post">
<input type="text" name="username" placeholder="请输入用户名"><br/>
<input type="text" name="password" placeholder="请输入密码"><br/>
请输入验证码:<input type="text" name="code"><img th:src="@{/user/getImage}" alt=""><br/>
<input type="submit" name="立即登录">
</form>
<a th:href="@{/user/registerview}">去注册</a>
</body>
</html>
这个首先引入thymeleaf的标签,之后我们将其中的代码改造为th标签。下面是register.html的页面:
<! doctype html>
<html lang="en" xmlns:th="http:thymeleaf.org">
<head>
<title>后台管理系统</title>
</head>
<h1>用户注册</h1>
<body>
<form th:action="@{/user/register}">
<input type="text" name="username" placeholder="请输入用户名"><br/>
<input type="text" name="password" placeholder="请输入密码"><br/>
<input type="submit" name="立即注册">
</form>
</body>
</html>
可以看到相应的我们将页面改为了th的标签,然后我们也将调用的接口也改为了@{}这种写法。
最后我们要来修改index.html页面,怎么修改呢?首先我们要将shiro与thymeleaf的整合坐标引入项目中:
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
这个就是shiro与thymeleaf整合的坐标,并且我们要在前端页面中引入标签shiro针对thymeleaf的整合标签:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
在此之外我们还要将我们的shiro整合thymeleaf的方言设置在shiroConfig中:
@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
只有设置了这段代码我们在首页中的shiro标签才能起作用。
下面我们就来看一下首页页面:
<! doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<title>后台管理系统</title>
</head>
<body>
<h1>系统主页V1.0</h1>
<ul>
<span shiro:hasRole="admin">
<li>物流管理</li>
<ul>
<li><a href="">发货时间</a></li>
<li><a href="">预计送达</a></li>
<li><a href="">承运单位</a></li>
</ul>
<li>订单管理</li>
<ul>
<li><a href="">订单新增</a></li>
<li><a href="">订单删除</a></li>
<li><a href="">订单修改</a></li>
</ul>
<li>商品管理</li>
<ul>
<li><a href="">商品新增</a></li>
<li><a href="">商品删除</a></li>
<li><a href="">商品修改</a></li>
</ul>
</span>
<span shiro:hasAnyRoles="user,admin">
<li>用户管理</li>
<ul>
<span shiro:hasPermission="user:add:*">
<li><a href="">用户新增</a></li>
</span>
<span shiro:hasPermission="user:delete:*">
<li><a href="">用户删除</a></li>
</span>
<span shiro:hasPermission="order:update:*">
<li><a href="">用户修改</a></li>
</span>
</ul>
</span>
</ul>
<a th:href="@{/user/logout}">用户登出</a>
</body>
</html>
至此Shiro安全框架的整个的整合开发实现,就完成了。