技术:struts2,spring4,hibernate4,shiro2,h2database,jetty,easyui 1.36
功能:用户的CRUD,登陆,页面与后台权限验证,
使用maven 构建项目,下载代码后,运行start.bat或mvn jetty:run 一键启动项目。
1、UserLoginActioin.java
[java] view plaincopy
- package com.jst.myjstBase.web;
- public class UserLoginAction extends BaseAction<User> {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private Log log = LogFactory.getLog(UserLoginAction.class);
- private User user;
- private String verifyCode;
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public String getVerifyCode() {
- return verifyCode;
- }
- public void setVerifyCode(String verifyCode) {
- this.verifyCode = verifyCode;
- }
- public String login() throws Exception {
- // SecurityUtils.getSubject().login(new
- // UsernamePasswordToken(user.getUserCode(), user.getPassword()));
- try {
- if (request.getSession() != null && request.getSession().getAttribute("USERNAME") != null) {
- return SUCCESS;
- }
- HttpSession session = request.getSession();
- // 判断验证码
- if (verifyCode == null || !verifyCode.equals((String) session.getAttribute("verifyCode"))) {
- addActionMessage("验证码错误");
- log.debug("验证码错误");
- return LOGIN;
- }
- // 清除验证码
- session.removeAttribute("verifyCode");
- // 判断用户名密码
- UsernamePasswordToken token = new UsernamePasswordToken(user.getUserCode(), user.getPassword());
- // UsernamePasswordToken token = new UsernamePasswordToken(
- // user.getUserCode(),EncryptUtils.encryptMD5(user.getPassword()));
- // token.setRememberMe(true);
- try {
- currentUser.login(token);
- session.setAttribute("USERNAME", "admin");
- } catch (AuthenticationException e) {
- log.error(e, e);
- addActionMessage("用户名或密码错误");
- return LOGIN;
- }
- return SUCCESS;
- } catch (Exception e) {
- log.error(e, e);
- }
- return LOGIN;
- }
- }<strong>
- </strong>
2、ShiroDbRealm.java
[java] view plaincopy
- package com.jst.common.service.impl;
- public class ShiroDbRealm extends AuthorizingRealm {
- protected IUserService userService;
- /**
- * 认证回调函数,登录时调用.
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
- UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
- User user = userService.findUserByLoginName(token.getUsername());
- if (user != null) {
- byte[] salt = Encodes.decodeHex(user.getSalt());
- return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getUserCode(), user.getUserName()),
- user.getPassword(), ByteSource.Util.bytes(salt), getName());
- }
- return null;
- }
- /**
- * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
- // User user = userService.findUserByLoginName(shiroUser.loginName);
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- info.addRole("user");
- if(shiroUser.loginName.equals("admin")){
- info.addStringPermission("user:add");
- info.addStringPermission("user:edit");
- info.addStringPermission("user:update");
- info.addStringPermission("user:delete");
- info.addStringPermission("user:query");
- }else{
- info.addStringPermission("user:query");
- }
- // info.addRoles(user.getRoleList());
- return info;
- }
- }
3、applicationContext-shiro.xml
[html] view plaincopy
- <?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-3.1.xsd"
- default-lazy-init="true">
- <description>Shiro安全配置</description>
- <!-- Shiro's main business-tier object for web-enabled applications -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroDbRealm" />
- <property name="cacheManager" ref="shiroEhcacheManager" />
- </bean>
- <!-- 項目自定义的Realm-->
- <bean id="shiroDbRealm" class="com.jst.common.service.impl.ShiroDbRealm">
- <property name="userService" ref="userServiceImpl"/>
- </bean>
- <!-- Shiro Filter -->
- <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="/" /> -->
- <property name="unauthorizedUrl" value="/error/noperms.jsp" />
- <property name="filterChainDefinitions">
- <value>
- /logout = logout
- /Images/** = anon
- /system/verifyCode.action* = anon
- /system/userLogin_login.action* = anon
- /error/** = anon
- /Json/** = anon
- /Css/** = anon
- /Js/** = anon
- /admin/** = roles[admin]
- /** = authc
- </value>
- </property>
- </bean>
- <!-- 用户授权信息Cache, 采用EhCache -->
- <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
- <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>
- </bean>
- <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
- <!-- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> -->
- </beans>
4、UserList.jsp页面权限控制代码
[php] view plaincopy
- <div style="padding: 5px; height: auto">
- <shiro:hasPermission name="user:edit">
- <span style="white-space:pre"> </span><a id="edit" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true">编辑</a>
- </shiro:hasPermission>
- <shiro:hasPermission name="user:delete">
- <span style="white-space:pre"> </span><a id="delete" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
- </shiro:hasPermission>
- </div>
5、BaseAction.java权限控制
[java] view plaincopy
- package com.jst.common.web;
- public abstract class BaseAction<T> extends ActionSupport implements ServletRequestAware, ServletResponseAware {
- private final Log log = LogFactory.getLog(BaseAction.class);
- public abstract String getPremissionModelCode();
- protected Subject currentUser;
- // public abstract IBaseService<T> getBaseService();
- protected void setPages(Page<T> tmppage) {
- tmppage.setPageNo(page);
- tmppage.setPageSize(rows);
- tmppage.setOrder(order);
- tmppage.setOrderBy(sort);
- }
- public BaseAction() {
- ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
- modelClass = (Class) pt.getActualTypeArguments()[0];
- currentUser = SecurityUtils.getSubject();
- }
- /**
- * 继承BaseAction的action需要先设置这个方法,使其获得当前action的业务服务
- *
- * @param service
- */
- public void setService(IBaseService<T> baseService) {
- this.service = baseService;
- }
- public String toAdd() throws Exception {
- if (currentUser.isPermitted(getPremissionModelCode() + ":add")) {
- return ADD;
- }
- WriterUtil.writerJson(response, "无权访问"+getPremissionModelCode() + ":add");
- return null;
- }
7、登陆成功并返回index.jsp