项目用到Shiro就从网上找一些案例看看吧,结果看了很多都是maven的,没有办法就自己弄了一个。废话不多说,原理自己找开始上菜。

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>/</url-pattern></servlet-mapping><filter><filter-name>shiroFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param><param-name>targetFilterLifecycle</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
</web-app>

spring-servlet.xml与web.xml同目录

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="com.lkk.shiro"></context:component-scan><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean><mvc:annotation-driven></mvc:annotation-driven><mvc:default-servlet-handler/></beans>

ehcache.xml

<ehcache><!-- Sets the path to the directory where cache .data files are created.If the path is a Java System Property it is replaced byits value in the running VM.The following properties are translated:user.home - User's home directoryuser.dir - User's current working directoryjava.io.tmpdir - Default temp file path --><diskStore path="java.io.tmpdir"/><cache name="authorizationCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><cache name="authenticationCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><cache name="shiro-activeSessionCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><!--Default Cache configuration. These will applied to caches programmatically created throughthe CacheManager.The following attributes are required for defaultCache:maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"/><!--Predefined caches.  Add your cache configuration settings here.If you do not have a configuration for your cache a WARNING will be issued when theCacheManager startsThe following attributes are required for defaultCache:name              - Sets the name of the cache. This is used to identify the cache. It must be unique.maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- Sample cache named sampleCache1This cache contains a maximum in memory of 10000 elements, and will expirean element if it is idle for more than 5 minutes and lives for more than10 minutes.If there are more than 10000 elements it will overflow to thedisk cache, which in this configuration will go to wherever java.io.tmp isdefined on your system. On a standard Linux system this will be /tmp"--><cache name="sampleCache1"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="true"/><!-- Sample cache named sampleCache2This cache contains 1000 elements. Elements will always be held in memory.They are not expired. --><cache name="sampleCache2"maxElementsInMemory="1000"eternal="true"timeToIdleSeconds="0"timeToLiveSeconds="0"overflowToDisk="false"/> --><!-- Place configuration for your caches following --></ehcache>

<ehcache><!-- Sets the path to the directory where cache .data files are created.If the path is a Java System Property it is replaced byits value in the running VM.The following properties are translated:user.home - User's home directoryuser.dir - User's current working directoryjava.io.tmpdir - Default temp file path --><diskStore path="java.io.tmpdir"/><cache name="authorizationCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><cache name="authenticationCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><cache name="shiro-activeSessionCache"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache><!--Default Cache configuration. These will applied to caches programmatically created throughthe CacheManager.The following attributes are required for defaultCache:maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"/><!--Predefined caches.  Add your cache configuration settings here.If you do not have a configuration for your cache a WARNING will be issued when theCacheManager startsThe following attributes are required for defaultCache:name              - Sets the name of the cache. This is used to identify the cache. It must be unique.maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- Sample cache named sampleCache1This cache contains a maximum in memory of 10000 elements, and will expirean element if it is idle for more than 5 minutes and lives for more than10 minutes.If there are more than 10000 elements it will overflow to thedisk cache, which in this configuration will go to wherever java.io.tmp isdefined on your system. On a standard Linux system this will be /tmp"--><cache name="sampleCache1"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="true"/><!-- Sample cache named sampleCache2This cache contains 1000 elements. Elements will always be held in memory.They are not expired. --><cache name="sampleCache2"maxElementsInMemory="1000"eternal="true"timeToIdleSeconds="0"timeToLiveSeconds="0"overflowToDisk="false"/> --><!-- Place configuration for your caches following --></ehcache>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--  1. 配置 SecurityManager!-->     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="cacheManager" ref="cacheManager"/><property name="realms"><ref bean="jdbcRealm"/></property></bean><!--  2. 配置 CacheManager. 2.1 需要加入 ehcache 的 jar 包及配置文件. -->     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"><property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> </bean><!-- 3. 配置 Realm 3.1 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean-->     <bean id="jdbcRealm" class="com.lkk.shiro.realms.ShiroRealm">         <!- 加密算法会用到-></bean><!--  4. 配置 LifecycleBeanPostProcessor. 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法. -->       <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/><!--  5. 启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用. -->     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"depends-on="lifecycleBeanPostProcessor"/><bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"><property name="securityManager" ref="securityManager"/></bean><!--  6. 配置 ShiroFilter. 6.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.-->     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager"/><property name="loginUrl" value="/login.jsp"/><property name="successUrl" value="/list.jsp"/><property name="unauthorizedUrl" value="/unauthorized.jsp"/><!--  配置哪些页面需要受保护. 以及访问这些页面需要的权限. 1). anon 可以被匿名访问2). authc 必须认证(即登录)后才可能访问的页面. 3). logout 登出.4). roles 角色过滤器--><property name="filterChainDefinitions"><value>/login.jsp = anon/shiro/login = anon/shiro/logout = logout# everything else requires authentication:/** = authc</value></property></bean></beans>

ShiroHandler.java

package com.lkk.shiro.handlers;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;@Controller
@RequestMapping("/shiro")
public class ShiroHandler {@RequestMapping("/login")public String login(@RequestParam("username") String username, @RequestParam("password") String password){Subject currentUser = SecurityUtils.getSubject();if (!currentUser.isAuthenticated()) {// 把用户名和密码封装为 UsernamePasswordToken 对象UsernamePasswordToken token = new UsernamePasswordToken(username, password);// remembermetoken.setRememberMe(true);try {System.out.println("1. " + token.hashCode());// 执行登录. currentUser.login(token);} // ... catch more exceptions here (maybe custom ones specific to your application?// 所有认证时异常的父类. catch (AuthenticationException ae) {//unexpected condition?  error?System.out.println("登录失败: " + ae.getMessage());}}return "redirect:/list.jsp";//return "list";}}

ShiroRealm.java

package com.lkk.shiro.realms;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;public class ShiroRealm extends AuthorizingRealm{@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {// TODO Auto-generated method stubreturn null;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {// TODO Auto-generated method stub
System.out.println("[FirstRealm] doGetAuthenticationInfo");//1. 把 AuthenticationToken 转换为 UsernamePasswordToken UsernamePasswordToken upToken = (UsernamePasswordToken) token;//2. 从 UsernamePasswordToken 中来获取 usernameString username = upToken.getUsername();//3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息.");//4. 若用户不存在, 则可以抛出 UnknownAccountException 异常if("unknown".equals(username)){throw new UnknownAccountException("用户不存在!");}//5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常. if("monster".equals(username)){throw new LockedAccountException("用户被锁定");}//6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo//以下信息是从数据库中获取的.//1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. Object principal = username;//2). credentials: 密码. Object credentials ="123"; //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可String realmName = getName();SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);info = new SimpleAuthenticationInfo(principal, credentials,  realmName);return info;}}

list.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><h4>hello world</h4><a href="shiro/logout">注销</a></body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><h4>Login Page</h4><form action="shiro/login" method="POST">username: <input type="text" name="username"/><br><br>password: <input type="password" name="password"/><br><br><input type="submit" value="Submit"/></form>
</body>
</html>

第二章加密的源码可以用这个包

http://pan.baidu.com/s/1bp0JRaB

转载于:https://www.cnblogs.com/lnthz/p/7850435.html

Shiro SpringMVC 非maven HelloWorld相关推荐

  1. Spring+SpringMVC+MyBatis+Maven框架整合

    本文记录了Spring+SpringMVC+MyBatis+Maven框架整合的记录,主要记录以下几点  一.Maven需要引入的jar包  二.Spring与SpringMVC的配置分离  三.Sp ...

  2. Eclipse下创建Spring MVC web程序--非maven版

    首先, 安装eclipse和tomcat, 这里我下载的是tomcat9.0版本64位免安装的:地址https://tomcat.apache.org/download-90.cgi 免安装的如何启动 ...

  3. 【JAVA程序设计】(C00043)基于SSM非maven的人事管理系统

    基于SSM非maven的人事管理系统 项目简介 项目获取 开发环境 项目技术 运行截图 运行视频 项目简介 这是一个SSM非maven项目的人事管理系统 功能:登录.用户增删改查.部门增删改查.职位增 ...

  4. 【JAVA程序设计】(C00089)基于SSM(非maven)的仓库出入库管理系统

    基于SSM(非maven)的仓库出入库管理系统 项目简介 项目获取 开发环境 项目技术 相关代码 运行截图 运行视频 项目简介 基于SSM(非maven)的仓库出入库管理系统: 功能简单,适合学习以及 ...

  5. 【JAVA程序设计】(C00067)基于SSM(非maven)图书馆座位预约管理系统

    基于SSM(非maven)图书馆座位预约管理系统 项目简介 项目获取 开发环境 项目技术 运行截图 项目简介 基于ssm框架非maven开发的图书馆预约占座管理系统共分为三个角色:系统管理员.教师.学 ...

  6. 【JAVA程序设计】【C00106】基于SSM(非maven)的演唱会网上订票系统——有文档

    [C00106]基于SSM(非maven)的演唱会网上订票系统--有文档 项目简介 项目获取 开发环境 项目技术 运行截图 项目简介 基于SSM+Bootstrap+MYSQL演唱会网上订票系统分为二 ...

  7. 手把手教你搭建微信点餐系统环境(springmvc+ibatis+maven+git)

    2019独角兽企业重金招聘Python工程师标准>>> 1.微信点餐系统简介 首先该系统的设计主要是用来接收移动端IOS/Android的请求, 对于订单将统一由后台进行处理, 系统 ...

  8. HDFS的API调用,创建Maven工程,创建一个非Maven工程,HDFS客户端操作数据代码示例,文件方式操作和流式操作

    1. HDFS的java操作 hdfs在生产应用中主要是客户端的开发,其核心步骤是从hdfs提供的api中构造一个HDFS的访问客户端对象,然后通过该客户端对象操作(增删改查)HDFS上的文件 1.1 ...

  9. JEECG 3.7.1 非Maven版本源码下载,企业级JAVA快速开发平台

    考虑到很多同学对Maven不熟悉,特提供非Maven版本,下载地址如下: JEECG 3.7.1 版本(非maven-myeclipse) 链接:http://pan.baidu.com/s/1gfM ...

最新文章

  1. php 去掉img,php怎样去掉img标签
  2. php上传照片到s3云服务器,PHP上传文件到AWS S3生成下载文件URL
  3. Cisco交换机中的flash,Rom,RAM,nvram的区别
  4. oracle备份及恢复
  5. 视频直播中 | 5G到底有多快?现场测速,带你走进5G生活
  6. 安装、卸载、查看软件时常用的命令
  7. 好的飞鸽传书2007未必是“语言律师”
  8. css3图像边框:border-image - 代码篇
  9. 集成druid实现数据库密码加密功能
  10. Java 枚举(enum)剖析
  11. 把路由器改成无线网卡
  12. 太空帝国5(Space Empires V SE5)攻略
  13. 代理服务器的工作原理是什么?
  14. Meta-Weight-Net[NIPS‘2019]:关于元学习/域自适应(meta learning/domain adaptation)优化噪声标签与类别不平衡的问题
  15. android charles 证书_手机安装Charles证书
  16. 精简压缩优化 Docker 镜像几百MB
  17. Table表格的一些记录
  18. martin fowler_Martin Kleppmann的大型访谈:“弄清楚分布式数据系统的未来”
  19. 库卡工业机器人负载曲线图_KUKA/库卡机器人 KR8 R1620 机械手臂 负载8kg 臂展16
  20. 【Visual c++】+【EasyX】游戏组件1 移动的小人

热门文章

  1. nojy 105 九的余数
  2. 使用Spring操作Redis的key-value数据
  3. 关于Android学习
  4. QA32中的出口 “STATTEXT”
  5. ExFat文件系统DBR受损恢复案例
  6. 资源管理器方法访问FTP服务
  7. Delphi 调用VC的DLL
  8. [翻译]帮助文档-jQuery 选择器
  9. Clone Detective java home
  10. 【记录一个问题】cuda核函数可能存在栈溢出,导致main()函数退出后程序卡死30秒CUDA...