常用框架(三):spring+springMvc+mybatis+maven+shiro+freemarker

SpringBoot+Spring data JPA+FreeMarker+shiro+log4jdbc 一个用SpringBoot+Spring data JPA+FreeMarker+shiro+log4jdbc完成的demo。 立即下载

在之前的博文,常用框架(一)中讲述了spring+springMvc+mybatis+maven框架的搭建,而在常用框架(二)中又集成了redis,

这篇文章主要讲述如何集成shiro+freemarker及其简单应用,还是在原有项目上做扩展,

需要回顾的请点链接跳转:http://blog.youkuaiyun.com/mynoteblog/article/details/54922775


项目说明:

(1) 使用freemarker模板,在html页面中可以获取attribute参数,替代jsp。

(2) 使用shiro做登录验证,以及权限分配

(3) pom.xml 追加依赖,这里加入了日志框架,源码会分享,这里就不做介绍了:


		<!-- freemarker -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.23</version>
		</dependency>		
		
		<!-- Spring 整合Shiro需要的依赖 -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-web</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-ehcache</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-freemarker-tags</artifactId>
			<version>0.1-SNAPSHOT</version>
			<exclusions>
				<exclusion>
					<artifactId>javax.servlet-api</artifactId>
					<groupId>javax.servlet</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- slf4j日志框架 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.logback-extensions</groupId>
			<artifactId>logback-ext-spring</artifactId>
			<version>0.1.2</version>
		</dependency>
		

一,整合freemarker,新建Spring-freemarker.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

	<!-- 配置freeMarker的模板路径 -->
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- 模板页面放置位置 -->
		<property name="templateLoaderPaths" value="/WEB-INF/template/" />
		<property name="freemarkerSettings">
            <props>
                <prop key="tag_syntax">auto_detect</prop>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="output_encoding">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="whitespace_stripping">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>

</beans>

二,在Spring-config.xml中引入以上新建的配置文件,配置如下:

<import resource="classpath:Spring-freemarker.xml" />

三,修改Spring-servlet.xml,配置freeMarker视图解析器,如下:

<!-- 配置freeMarker视图解析器 -->	
	<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="contentType" value="text/html; charset=UTF-8" />
		<property name="suffix" value=".ftl" />
	</bean>
四,测试,新建hello.ftl页面,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
[#--从Attribute中获取参数--]
<h1>${msg}</h1>

[#--判断句式--] 
<h1>${(1 == 1)?string("yes", "no")}</h1>

[#--集合遍历--]
<ul>
[#list list as item]
<li>${item}</li>
[/#list]
</ui>

[#if msg=='hello']
<h1>say hello</h1>
[#else]
<h1>say goodbye</h1>
[/#if]

</body>
</html>
这里用的了[#if],[#list] 指令,其他freemarker常用指令,大家可以百度学习。

五,新建测试Controller,FreemarkerController,代码如下:

package com.maven.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {

	@RequestMapping(value="/hello",method=RequestMethod.GET)
	public String sayHello(Model model){
		String msg = "Hello World";
		List<String> list = new ArrayList<String>(3);
		list.add("a");
		list.add("b");
		list.add("c");
		model.addAttribute("msg", msg);
		model.addAttribute("list", list);
		return "hello";
	}
	
}
六,启动tomcat,访问测试:


***************************************************************

单独集成freemarker演示到此结束,下面重点来看shiro集成。

一,添加Spring-shiro.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
	
	<!-- Shiro主过滤器的拦截 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- 权限管理器 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 登录地址 -->
		<property name="loginUrl" value="/template/login.ftl" />
		<!-- 登录后跳转到业务页面 -->
		<property name="successUrl" value="/template/main.ftl" />
		<!-- 错误页面 -->
		<property name="unauthorizedUrl" value="/template/error.ftl" />
		<!-- 鉴权过滤器 -->
		<property name="filters">
			<map>
				<entry key="logout" value-ref="logoutFilter" />
				<entry key="authc" value-ref="myAuthenticationFilter" />
			</map>
		</property> 
		<!-- 权限配置 -->
		<property name="filterChainDefinitions">
			<value>
				 <!-- 对静态资源不需要进行认证 -->  
                /static/** = anon
                /tags/** = anon
                <!-- 登录退出不需要验证 -->
                /login/**=anon  
				/logout = logout
                <!-- 对所有url都需要进行认证 -->  
				/** = authc
			</value>
		</property>
	</bean>
	
	<!-- 配置权限管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<!-- 缓存管理器 --> 
		<property name="cacheManager" ref="cacheManager" />
		<!-- 我们自定义的realm -->
		<property name="realm" ref="myRealm" />
	</bean>
	
    <!-- 自定义的Realm,若有多个Realm,可使用'realms'属性代替 -->  
    <bean id="myRealm" class="com.maven.web.shiro.MyRealm" />
    
    <!-- 重写的认证filter-->
    <bean id="myAuthenticationFilter" class="com.maven.web.shiro.MyAuthenticationFilter" />
    
    <!-- 使用shiro提供的logout filter -->
    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="/template/login.ftl" />
    </bean>
    
    <!-- shiro 缓存管理 -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
    
    <!-- Shiro生命周期处理器 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    	
</beans>
*********************************************************************************************************************

这里需要注意:

默认的shiro authc 认证参数是username+password,我这里重写了认证方法,改为认证phone+password,

如果没有此需要的,去掉上面配置文件中的以下配置即可,采用默认过滤器




同理,其他anon,logout过滤器也可以重写,还可以自定义过滤器,这些大家可以根据需要来实现,不多介绍。


二,在web.xml 中添加shiro核心过滤器,配置如下:

<!-- shiro过滤器 -->
	<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>

三,在Spring-config.xml中引入shiro配置文件,配置如下:

<import resource="classpath:Spring-shiro.xml" />

四,重写自己的Realm授权+认证方法,在此之前,先实现我们需要的认证参数。

(一) 新建MyAuthenticationToken继承UsernamePasswordToken,添加我们需要的phone属性,代码如下:

(如果不需要自定义属性就不需要写这一步了,直接用UsernamePasswordToken即可)

package com.maven.web.shiro;

import org.apache.shiro.authc.UsernamePasswordToken;

/**
 * 重新token,对用户名的认证改为手机号
 * @author Administrator
 *
 */
public class MyAuthenticationToken extends UsernamePasswordToken{

	private static final long serialVersionUID = 1425855488092920451L;
	
	/** 手机号 */
	private String phone;

	public MyAuthenticationToken(String phone, String password, boolean rememberMe, String host) {
		super(null, password, rememberMe, host);
		this.phone = phone;
	}

	/** 默认是返回用户名,改写返回手机号 */
	@Override
	public Object getPrincipal() {
		return phone;
	}

	@Override
	public void clear() {
		super.clear();
		phone = null;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	

}
(二) 新建MyAuthenticationFilter继承FormAuthenticationFilter,实现用户认证,代码如下:
package com.maven.web.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 重写token认证
 * @author Administrator
 *
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter{

	public static final String DEFAULT_PHONE_PARAM = "phone";
	
	private String phoneParam = DEFAULT_PHONE_PARAM;
	
	public MyAuthenticationFilter(){
		setFailureKeyAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
	}
	
	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String phone = getPhone(request);
		String password = getPassword(request);
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request); 
		
		return new com.maven.web.shiro.MyAuthenticationToken(phone,password,rememberMe,host);
	}

	public String getPhoneParam() {
		return phoneParam;
	}

	public void setPhoneParam(String phoneParam) {
		this.phoneParam = phoneParam;
	}

	protected String getPhone(ServletRequest request) {
		return WebUtils.getCleanParam(request, getPhoneParam());
	} 
	
}
(三) 新建自己的Realm类,MyRealm 继承AuthorizingRealm,代码如下:

package com.maven.web.shiro;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.maven.web.entity.MenuChild;
import com.maven.web.entity.RoleInfo;
import com.maven.web.entity.UserInfo;
import com.maven.web.exception.AuthenticateException;
import com.maven.web.mapper.MenuChildMapper;
import com.maven.web.mapper.RoleInfoMapper;
import com.maven.web.service.impl.UserService;

public class MyRealm extends AuthorizingRealm{
	
	@Resource
	private UserService userService;
	
	@Resource
	private MenuChildMapper menuChildMapper;
	
	@Resource
	private RoleInfoMapper roleInfoMapper;
	
	public MyRealm() {
		setAuthenticationTokenClass(AuthenticationToken.class);
	}

	/**
	 * 重写认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UserInfo userInfo = null;
		if(token instanceof MyAuthenticationToken){
			MyAuthenticationToken myToken = (MyAuthenticationToken) token;
			String phone = myToken.getPhone();
			String password = new String(myToken.getPassword());
			try {
				userInfo = userService.getUserInfoNyPhone(phone,password);
			} catch (AuthenticateException e){
				throw new IncorrectCredentialsException(e);
			}
			
			if (null == userInfo) {
				throw new IncorrectCredentialsException("账号或密码错误!");
			}
			
			if (!"0".equals(userInfo.getStatus())) {
				throw new DisabledAccountException("帐号"+myToken.getPrincipal()+"已失效!");
			}
			
			//比对成功则返回authcInfo
    	    AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword().toCharArray(),this.getName());  
//    	    this.setSession("currentUser", userInfo);  
    	    return authcInfo; 
		}
		return null;
	}
	
    /**
     * 为认证成功的用户授权,然后就可以调用subject.hasRole等方法进行逻辑判断
     */
    @Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	//认证通过后会将需要的身份信息放到SimpleAuthenticationInfo中返回,这是是获取到其中的principal对象
    	Iterator<?> iterator = principals.fromRealm(getName()).iterator();
    	if (iterator.hasNext()) {
    		UserInfo userInfo = (UserInfo) iterator.next();
    		if (null != userInfo) {
    			List<String> roleList = new ArrayList<String>();
    			List<String> permissionList = new ArrayList<String>();
    			//查询用户角色
    			RoleInfo userRole = roleInfoMapper.selectByUserId(userInfo.getId());
    			if(null !=userRole){
    				roleList.add(userRole.getRoleName());
    				List<MenuChild> roleMenus = menuChildMapper.getMenuChildByRoleId(userRole.getId());
    				if(null !=roleMenus){
    					for(MenuChild menu:roleMenus){
    						permissionList.add(menu.getMenuName());
    					}
    				}
    			}
    			
    			//为用户添加权限,角色
    			SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
    			simpleAuthorInfo.addRoles(roleList);
    			simpleAuthorInfo.addStringPermissions(permissionList);
    			return simpleAuthorInfo;
    		}
    	}
    	
		return null;
	}

    /** 
     * 将一些数据放到ShiroSession中,以便于其它地方使用 
     * @see  比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 
     * 也可以直接从subject的身份对象中取
     */  
   /* private void setSession(Object key, Object value){  
        Subject currentUser = SecurityUtils.getSubject();  
        if(null != currentUser){  
            Session session = currentUser.getSession();  
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
            if(null != session){  
                session.setAttribute(key, value);  
            }  
        }  
    }*/

}
*******************************************************************************************************************

这里说明一下:

认证方法,是对用户在登录页面提交的信息做校验,登录成功才会跳转到主页。

授权方法,用户登录成功后可以根据用户信息查找相关角色,权限,存储到授权对象中。

以后就可以通过java代码,shiro标签等,获取当前用户的角色,权限,进行模块功能分配等等。下面会演示。


五,用户登录

(一) 新建登录页面,login.ftl,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/com.maven.web/login/login" method="post" id="form">
<article>手机号:</article>
<input type="text" name="phone"/>
<article>密码:</article>
<input type="password" name="password"/>
<br/>
<br/>
<input type="submit" value="登录" />
<br/>
</form>
<span style="color:red">${msg}</span>
</body>
</html>

(二) 新建 LoginContoller,代码如下:

package com.maven.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.maven.web.entity.UserInfo;
import com.maven.web.shiro.MyAuthenticationToken;
import com.maven.web.util.LoggerUtils;

@Controller
@RequestMapping("/login")
public class LoginController {
	private final Logger logger = LoggerUtils.getLogger("LoginController");

	/**
	 * 基于手机号和密码的身份认证
	 * @param userInfo
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String checkLogin(UserInfo userInfo,Model model,HttpServletRequest request){

		logger.debug("userInfo", userInfo);;
		
		MyAuthenticationToken token = new MyAuthenticationToken(userInfo.getPhone(), userInfo.getPassword(), true, null);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);//会到自定义的Realm中进行验证返回
			if(subject.isAuthenticated()){
				return "redirect:/menu/list";
			}else{
				token.clear();
			}
		}catch(AuthenticationException e){
			model.addAttribute("msg",e.getMessage());
		}
		return "login";
	}
	
	 /** 
     * 用户登出 
     */  
    @RequestMapping("/logout")  
    public String logout(){  
         SecurityUtils.getSubject().logout();  
         return "login";  
    } 
}

(三) 新建登录成功页面,main.ftl,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<span>菜单栏</span>
	<ul>
		[#list menus as menu]
		<li><a href="#">${menu.menuParent.menuName}</a></li>
		<li>
			<ul>
				[#list menu.menuChilds as menuChild]
				<li><a href=${menuChild.menuUrl}>${menuChild.menuName}</a></li> 
				[/#list]
			</ul>
		</li> 
		[/#list]
	</ul>
	<span>${msg}</span>
	<br/>
	<div>
	[@shiro.hasRole name="管理员"]
	<span>角色是管理员才能看到此信息</span>
	[/@shiro.hasRole]
	</div>
	<a href="/com.maven.web/login/logout">logout</a>
</body>
</html>
(四) 新建MenuController,动态查询菜单权限返回主页面main.ftl,代码如下:
package com.maven.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.maven.web.entity.MenuChild;
import com.maven.web.entity.MenuParent;
import com.maven.web.mapper.MenuChildMapper;
import com.maven.web.mapper.MenuParentMapper;
import com.maven.web.vo.Menu;

@Controller
@RequestMapping("/menu")
public class MenuController {
	
	@Resource
	private MenuParentMapper menuParentMapper; 
	
	@Resource
	private MenuChildMapper menuChildMapper; 
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String listMenu(Model model){
		List<Menu> menus = new ArrayList<Menu>();
		List<MenuParent> parents = menuParentMapper.getMenuParentList();
		if(parents!=null && !parents.isEmpty()){
			for(MenuParent parent:parents){
				Menu menu = new Menu();
				menu.setMenuParent(parent);
				List<MenuChild> childs = menuChildMapper.getMenuChildByPid(parent.getId());
				if(childs!=null && !childs.isEmpty()){
					menu.setMenuChilds(childs);
				}
				menus.add(menu);
			}
		}
		model.addAttribute("menus",menus);
		Subject subject = SecurityUtils.getSubject();
		if(subject.hasRole("管理员")){
			model.addAttribute("msg","这里是管理员私人信息!");
		}
		return "main";
	}
	
}

六,启动tomcat,测试:

这里先给大家看一下我数据库的用户信息:


启动访问,未登录会跳转到登录页面

测试一:错误用户信息



测试二:新注册用户状态为未激活



测试三:管理员登录



测试四:普通用户登录



*******************************************************************************************************

这里请大家注意,管理员登录成功后可以看到红色框和黄色框两条信息,普通用户登录后看不到。

(1) 红色框信息:

这是因为在MenuController中做了角色判断,注意代码片段:

Subject subject = SecurityUtils.getSubject();
		if(subject.hasRole("管理员")){
			model.addAttribute("msg","这里是管理员私人信息!");
		}

(2) 黄色框信息:

这是因为在main.ftl页面中使用了shiro标签,注意代码片段:

<div>
	[@shiro.hasRole name="管理员"]
	<span>角色是管理员才能看到此信息</span>
	[/@shiro.hasRole]
	</div>
********************************************************************************************************
接下来说明shiro标签的使用:

(一) 在freemarker中需要先引入shiro-freemarker-tags-0.1-SNAPSHOT.jar,本例已经添加到pom.xml文件中,

大家可以下载源码,在lib中找到jar包添加到本地,也可以到网上下载,下面会贴出链接。


(二) 新建CustomFreeMarkerConfigurer 继承FreeMarkerConfigurer,代码如下:

package com.maven.web.template;

import java.io.IOException;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.jagregory.shiro.freemarker.ShiroTags;

import freemarker.template.TemplateException;

/**
 * 编写自己的freemarker配置
 * @author Administrator
 *
 */
public class CustomFreeMarkerConfigurer extends FreeMarkerConfigurer{
	

	/**
	 * 重写导入shiro标签
	 */
	@Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        super.afterPropertiesSet();
        this.getConfiguration().setSharedVariable("shiro", new ShiroTags());
    }
}
(三) 修改Spring-freemarker.xml配置文件,改成自定义的CustomFreeMarkerConfigurer



关于shiro标签与freemarker的整合,大家可以跳转链接学习:http://blog.youkuaiyun.com/lingyundouer/article/details/50487459


如果使用默认的authc认证,只需要将代码中MyAuthenticationToken替换成UsernamePasswordToken,

然后获取到的phone参数替换成username就可以,其他都是一样的。

以上就介绍完毕了,可能有所遗漏,大家可以下载源码参考:http://pan.baidu.com/s/1dFilb6h



springmvc+freemarker+shiro 整合了springmvc+FreeMarker+shiro的小Demo! 立即下载

相关推荐

springMVC+spring+mybatis(shiro+redis)框架样本

这个ssm框架样本提供了shiro权限管理,是一个完整的能运行的项目样本。

FreeMarker简介

什么是 FreeMarker? FreeMarker 是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。 模板编写为FreeMarker Template Language (FTL)。它是简单的,专用的语言,不...

weixin_30872733的博客 214

【Hypermesh】TetraMesh Panel 常用选项详解

结合Hypermesh 2020 帮助文档和自己的一点使用经验,整理了这个博客。

qgm1702的博客 3676

Spring、SpringMVC、Shiro、Maven

1、Spring框架就像一个家族,有众多衍生产品例如:boot、security、jpa等等。但它们的基础都是Spring的ioc、aop等;ioc提供了依赖注入的容器,aop解决了面向横切面编程,然后在此两者的基础上实现了其他产品的高级功能;2、SpringMVC主要解决WEB开发的问题,是基于Servlet的一个MVC框架,通过XML配置,统一开发前端视图和后端逻辑。

inexaustible的博客 1181

RK3568 开发实战:手动构建 Linux 4.19 内核镜像与设备树优化

本文详细介绍了为RK3568开发板手动编译Linux 4.19内核的完整实战流程。从环境搭建、源码获取、内核配置,到设备树深度定制与优化,再到镜像打包与烧写,旨在帮助开发者脱离官方SDK依赖,实现对嵌入式Linux系统的完全掌控,提升硬件适配与性能优化能力。

weixin_29175469的博客 269

从Delphi 7到Delphi 10.4.1的代码迁移:关键挑战与实用解决方案

本文详细探讨了从Delphi 7升级到Delphi 10.4.1进行代码迁移的关键挑战与实用解决方案。核心内容包括应对Unicode字符串处理、64位数据类型变化、VCL/FMX界面框架选择、第三方组件迁移以及数据库层现代化改造(如从BDE迁移至FireDAC)。文章为开发者提供了系统的迁移前准备、核心问题攻克策略及测试落地指南,旨在帮助团队高效、平稳地完成系统现代化升级。

weixin_29250403的博客 531

Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解

一. 环境搭建: 1. 开发工具:myeclipse 2014 / IDEA; 2. maven管理版本:apache-maven-3.0+; 3. jdk 1.7.0+ 4. Tomcat8.0 二:工程搭建: 1、修改pom.xml添加对应的包依赖 ? 1 2 3 4 5 6 7 8 9 10 ...

soo_co的专栏 385

从零搭建A股量化交易系统:开源框架选型与实战部署指南

本文详细介绍了从零搭建A股量化交易系统的完整流程,重点分析了开源框架VNPY和QMT的选型与实战部署。内容涵盖系统架构设计、策略开发、性能优化及实盘过渡方案,为开发者提供了一套完整的A股实盘量化交易解决方案,助力高效构建稳定可靠的量化交易系统。

sugar的博客 1271

FreeMarker 获取页面request、session

使用Request里的Attribute值最简单的方法就是直接${AttributeName}或者安全一点:${AttributeName!"default Value"}1.取Application范围的对象xml 代码   1.     2.      ${Application.myApplicationAttribute}      3.  或者 :

想飞的鱼 9万+

光学设计必看:如何用泽尼克系数优化镜头像差?从Zemax到实际案例解析

本文深入解析了如何利用泽尼克系数优化镜头像差,从理解其工程价值、解码软件报告,到在Zemax中主动设置优化目标。通过高倍显微物镜等实际案例,详细展示了如何通过分析泽尼克系数诊断问题,并实施针对性优化策略,从而实现对球差、彗差等像差的精准控制,提升光学设计的精细度和系统稳健性。

gg901的博客 1027

OpenClaw实战三|电商自动化AI工具:自动上下架+智能客服+订单统计,小店运营效率直接翻3倍

对电商小团队、夫妻店、个人商家来说,最缺的不是流量,而是省时间的工具。OpenClaw这套电商自动化AI工具,不用懂代码、不用买昂贵的SaaS软件,一台服务器、简单配置,就能把最耗时间的工作全部交给AI。人只做最有价值的事:选品、拍图、搞流量、处理复杂售后,剩下的上下架、回复、统计,全都让AI帮你打工。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1459

spring篇-(ssm整合shiro)

ssm整合shiro初始化项目结构启动项目 初始化项目结构 项目基于maven的ssm架构,最终打包的结果为war 结构如下图 项目pom文件 <?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:schemaLo

qq_42413011的博客 344

5-EP4CE10F17C8-引脚配置

EP4CE10F17C8-引脚配置

weixin_44479192的博客 719

发布一个demo maven+freemarker+shiro+springmvc+spring+mybatis+redis+mysql

maven+freemarker+shiro+springmvc+spring+mybatis+redis+mysql+jquery easy ui  demo 地址demo

mark's technic world 1591

STM32实战开发(121):基于STM32的智能电导率检测系统设计与实现

STM32系列是由意法半导体(STMicroelectronics)推出的32位微控制器。STM32系列基于ARM Cortex-M处理器架构,具有高性能、低功耗、丰富的外设接口和强大的开发支持库。STM32的低功耗特性使其在嵌入式系统中非常受欢迎,特别是在便携式设备和传感器网络中。

2201_76125393的博客 1041

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

java springmvc mybaits maven shiro

下载地址   QQ 313596790 A 调用摄像头拍照,自定义裁剪编辑头像 B 集成代码生成器 [正反双向](单表、主表、明细表、树形表,开发利器)+快速构建表单;  技术:313596790 freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面、建表sql脚本,处理类,service等完整模块 C 集成阿里巴巴数据库连接池druid;   数据库连接池  

qq_37113065的博客 284

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Spring+SpringMVC+Mybatis+shiro权限登录管理

最近公司要做一个新闻发布的系统,需要实现前台展示新闻页面,任何人都可以访问,后台需要权限登录,实现管理功能。 我使用Spring 4.3.6.RELEASE,mybatis 3.4.2版本,shiro 1.2.3版本,maven搭建项目。 一. 环境搭建: 1. 开发工具:myeclipse 2014; 2. maven管理版本:apache-maven-3.3.9;

夏蚊成雷的博客 1万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

CMS小项目02---Spring+SpringMVC+Mybatis+shiro框架搭建

整体框架还是选用Spring+SpringMVC+MyBatis 连接池选用阿里巴巴的Druid 项目管理使用的是Maven 日志管理log4j 安全框架使用Shiro 页面模板引擎常用的FreeMarker (这个以前没用过,研究了不少时间) 前台JavaScript+JQ+各类插件 数据库MySql - SSM框架的组装以前写过一个,这一篇就只是贴上大致的配置文件 1.配置文...

black-ant 2371

java 整合redis缓存 SSM 后台框架 rest接口 shiro maven

三大数据库 mysql  oracle  sqlsever   更专业、更强悍、适合不同用户群体 【新录针对本系统的视频教程,手把手教开发一个模块,快速掌握本系统】 A 调用摄像头拍照,自定义裁剪编辑头像 B 集成代码生成器 [正反双向](单表、主表、明细表、树形表,开发利器)+快速构建表单;  技术:313596790 freemaker模版技术 ,0个代码不用写,生成完整的一个模块

likungs886的博客 3371

SSM springmvc mybatis 整合 bootstrap maven shiro druid ehcache SSM框架源码

获取【下载地址】 QQ: 313596790 官网 http://www.fhadmin.org/ A 调用摄像头拍照,自定义裁剪编辑头像,头像图片色度调节 B 集成代码生成器 [正反双向](单表、主表、...

cherry123519的博客 146

maven常见开发配置spring,hibernate,structs,jdbc,log4j,mybatis

maven的通用配置,包含了structs,springMVC,spring,hibernate,json,mabatis,oracle,模板,缓存,日志,数据库接口配置。

August 1381

JavaEE框架Bootstrap HTML5 jQuery SpringMVC maven mybatis shiro ehcache

获取【下载地址】 QQ: 313596790 官网 http://www.fhadmin.org/ A 调用摄像头拍照,自定义裁剪编辑头像,头像图片色度调节 B 集成代码生成器 [正反双向](单表、主表、...

155

Spring+SpringMVC+Shiro+Redis+Maven权限管理

Shiro Demo 准备工作 运行前申明 请看完本页面的所有细节,对你掌握这个项目来说很重要,别一上来就搞,你不爽,我也不爽。本项目需要一定的Java功底,需要对SpringMvc,Mybatis,有基本的了解,其次对Redis有了解和使用更佳。本项目理论上,只需要一个Redis,然后一个Mysql和一个有Maven环境的开发工具即可运行起来。 运行步骤 从

白驹过隙 5337
上一篇: CtripDal 携程数据库访问框架简析
下一篇: dubbo+zookeeper 简单实现远程接口调用
小小小爬虫
博客等级 码龄10年 16粉丝 61原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值