ssm分布式+dubbo+zookeeper

注:由于是学习阶段搭建的项目,命名和代码很多不规范

  • 基本准备
    创建maven的父项目
    注意:父项目为maven project,直接创建一个简单工程

    将ssm项目中的模块抽出分别创建maven的子项目
    在父项目的基础上创建maven module
    dao层:


entity层:

interface层(service层):


创建为jar项目
serviceImpl层:


web层:


以上为war包的方式创建项目

注意:若项目报错,请手动在webapp下的WEB-INF下添加web.xml文件

  • 配置文件

    父项目引入jar包依赖

    注意

    1. dubbo的jar包与springframework存在冲突,jar包依赖导入时解决
    2. shiro的缓存技术和ehcache存在冲突,引入低版本的ehcache的依赖,在pom中已解决
    <dependencies><dependency><groupId>junitgroupId><artifactId>junitartifactId><version>3.8.1version><scope>testscope>dependency><dependency><groupId>javaxgroupId><artifactId>javaee-apiartifactId><version>7.0version>dependency><dependency><groupId>net.sf.json-libgroupId><artifactId>json-libartifactId><version>2.4version><classifier>jdk15classifier>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-coreartifactId><version>${spring.version}version>dependency><dependency><groupId>com.alibabagroupId><artifactId>dubboartifactId><version>2.5.3version><exclusions><exclusion><artifactId>springartifactId><groupId>org.springframeworkgroupId>exclusion>exclusions>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-webartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-oxmartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-txartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-jdbcartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-webmvcartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-aopartifactId><version>${spring.version}version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-context-supportartifactId><version>${spring.version}version>dependency><dependency><groupId>net.sf.ehcachegroupId><artifactId>ehcache-coreartifactId><version>2.4.8version>dependency><dependency><groupId>org.apache.shirogroupId><artifactId>shiro-ehcacheartifactId><version>1.2.3version>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-testartifactId><version>${spring.version}version>dependency><dependency><groupId>org.mybatisgroupId><artifactId>mybatisartifactId><version>${mybatis.version}version>dependency><dependency><groupId>org.mybatisgroupId><artifactId>mybatis-springartifactId><version>1.2.2version>dependency><dependency><groupId>mysqlgroupId><artifactId>mysql-connector-javaartifactId><version>5.1.30version>dependency><dependency><groupId>commons-dbcpgroupId><artifactId>commons-dbcpartifactId><version>1.2.2version>dependency><dependency><groupId>jstlgroupId><artifactId>jstlartifactId><version>1.2version>dependency><dependency><groupId>log4jgroupId><artifactId>log4jartifactId><version>${log4j.version}version>dependency><dependency><groupId>com.alibabagroupId><artifactId>fastjsonartifactId><version>1.1.41version>dependency><dependency><groupId>org.slf4jgroupId><artifactId>slf4j-apiartifactId><version>${slf4j.version}version>dependency><dependency><groupId>org.slf4jgroupId><artifactId>slf4j-log4j12artifactId><version>${slf4j.version}version>dependency><dependency><groupId>org.codehaus.jacksongroupId><artifactId>jackson-mapper-aslartifactId><version>1.9.13version>dependency><dependency><groupId>commons-fileuploadgroupId><artifactId>commons-fileuploadartifactId><version>1.3.1version>dependency><dependency><groupId>commons-iogroupId><artifactId>commons-ioartifactId><version>2.4version>dependency><dependency><groupId>commons-codecgroupId><artifactId>commons-codecartifactId><version>1.9version>dependency><dependency><groupId>org.mybatis.generatorgroupId><artifactId>mybatis-generator-coreartifactId><version>1.3.2version>dependency><dependency><groupId>org.apache.shirogroupId><artifactId>shiro-coreartifactId><version>${shiro.version}version>dependency><dependency><groupId>org.apache.shirogroupId><artifactId>shiro-webartifactId><version>${shiro.version}version>dependency><dependency><groupId>org.apache.shirogroupId><artifactId>shiro-springartifactId><version>${shiro.version}version>dependency><dependency><groupId>org.apache.zookeepergroupId><artifactId>zookeeperartifactId><version>3.3.3version>dependency><dependency><groupId>com.101tecgroupId><artifactId>zkclientartifactId><version>0.10version>dependency>dependencies>
    

    maven父项目下载完所有jar包之后进行更新

dao层:

dao层与mybatis的整合,可以使用逆向工程进行创建,这里不使用逆向工程,自己编写mapper与xml

配置文件:

注意:若dubbo标签报错,请手动引入xsd


<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"xmlns:context="http://www.springframework.org/schema/context"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd    http://code.alibabatech.com/schema/dubbohttp://code.alibabatech.com/schema/dubbo/dubbo.xsdhttp://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc.xsd"><dubbo:application name="demo-serviceImpl" /><dubbo:registry address="zookeeper://47.100.126.191:2181">dubbo:registry><dubbo:annotation package="cn.xuxiaonan.serviceimpl" /><dubbo:protocol name="dubbo" port="20880" /><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="classpath:jdbc.properties" />bean><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="initialSize" value="${jdbc.initialSize}" /><property name="maxActive" value="${jdbc.maxActive}" /><property name="maxIdle" value="${jdbc.maxIdle}" /><property name="minIdle" value="${jdbc.minIdle}" /><property name="maxWait" value="${jdbc.maxWait}" />bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:mapping/*.xml" />bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="cn.xuxiaonan.dao" /><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />bean>
beans>  

jdbc配置:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:/xuxiaonan?useUnicode=true&characterEncoding=UTF-8
jdbc.username=
jdbc.password=
jdbc.initialSize=0
jdbc.maxActive=20      
jdbc.maxIdle=20   
jdbc.minIdle=1    
jdbc.maxWait=60000

日志配置:

#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B  
#log4j.rootLogger=INFO,Console,File  
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0  
#log4j.appender.Console=org.apache.log4j.ConsoleAppender  
#log4j.appender.Console.Target=System.out  
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F  
#log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
#log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  #\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6  
#log4j.appender.File = org.apache.log4j.RollingFileAppender  
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55  
#log4j.appender.File.File = logs/ssm.log  
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F  
#log4j.appender.File.MaxFileSize = 10MB  
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7  
#log4j.appender.File.Threshold = ALL  
#log4j.appender.File.layout = org.apache.log4j.PatternLayout  
#log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  log4j.rootLogger=Debug,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO 8601 format
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN

serviceImpl层:

web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1" metadata-complete="true"><context-param><param-name>contextConfigLocationparam-name><param-value>classpath:applicationContext-dao.xmlparam-value>context-param> <listener><listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>listener>
web-app>

web层:

注意:这里在整合shiro的时候,由于要配置过滤器的原因,我将shiro整合在了web层。然后应该公共抽取还是整合在web层中这一点我还不会。

  
<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"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.1.xsd  http://code.alibabatech.com/schema/dubbohttp://code.alibabatech.com/schema/dubbo/dubbo.xsd  http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">    <mvc:annotation-driven >mvc:annotation-driven><dubbo:application name="demo-web" /><dubbo:registry address="zookeeper://47.100.126.191:2181">dubbo:registry><dubbo:annotation package="cn.xuxiaonan.controller" /><dubbo:reference id="userService" interface="cn.xuxiaonan.service.userService"/><bean id="defaultAdvisorAutoProxyCreator"class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"><property name="proxyTargetClass" value="true">property>bean><beanclass="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">bean> <mvc:default-servlet-handler/>  <bean id="mappingJacksonHttpMessageConverter"  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  <property name="supportedMediaTypes">  <list>  <value>text/html;charset=UTF-8value>  list>  property>  bean>    <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  <property name="messageConverters">  <list>  <ref bean="mappingJacksonHttpMessageConverter" />   list>  property>  bean>    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix" value="/" />  <property name="suffix" value=".jsp" />  bean>    <bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      <property name="defaultEncoding" value="utf-8" />      <property name="maxUploadSize" value="10485760000" />      <property name="maxInMemorySize" value="40960" />    bean>   <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><prop key="org.apache.shiro.authz.UnauthorizedException">test/errorprop>props>property>bean><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager" /><property name="loginUrl" value="/user/login" /><property name="unauthorizedUrl" value="/error" /><property name="filters"><map><entry key="authc" value-ref="formAuthenticationFilter" />map>property><property name="filterChainDefinitions"><value>/pageResources/** = anon/user/logout = logout/user/login = authc/mform/* = authc/me/* = authcvalue>property>bean><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="customRealm" /><property name="cacheManager" ref="cacheManager" /><property name="sessionManager" ref="sessionManager" />bean><bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"><property name="cacheManagerConfigFile" value="classpath:spring/shiro-ehcache.xml" />bean><bean id="sessionManager"class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"><property name="globalSessionTimeout" value="600000" /><property name="deleteInvalidSessions" value="true" /><property name="sessionIdCookieEnabled" value="true" /><property name="sessionIdCookie" ref="sessionIdCookie" />bean><bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"><property name="usernameParam" value="username" /><property name="passwordParam" value="password" />bean><bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"><constructor-arg name="name" value="xuxiaonan.session.id" />bean><bean id="customRealm" class="cn.xuxiaonan.shiro.CustomRealm"><property name="userService" ref="userService"/>bean>
beans>  

web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1" metadata-complete="true">
<display-name>Archetype Created Web Applicationdisplay-name><filter><filter-name>encodingFilterfilter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class><async-supported>trueasync-supported><init-param><param-name>encodingparam-name><param-value>UTF-8param-value>init-param>filter><filter-mapping><filter-name>encodingFilterfilter-name><url-pattern>/*url-pattern>filter-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>listener><listener><listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>listener><context-param><param-name>contextConfigLocationparam-name><param-value>classpath:spring/spring-mvc.xmlparam-value>context-param> <filter><filter-name>shiroFilterfilter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class><init-param><param-name>targetFilterLifecycleparam-name><param-value>trueparam-value>init-param>filter><filter-mapping><filter-name>shiroFilterfilter-name><url-pattern>/*url-pattern>filter-mapping><servlet><servlet-name>SpringMVCservlet-name><servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class><init-param><param-name>contextConfigLocationparam-name><param-value>classpath:spring/spring-mvc.xmlparam-value>init-param><load-on-startup>1load-on-startup><async-supported>trueasync-supported>servlet><servlet-mapping><servlet-name>SpringMVCservlet-name><url-pattern>/url-pattern>servlet-mapping><servlet-mapping><servlet-name>defaultservlet-name><url-pattern>*.jsurl-pattern><url-pattern>*.cssurl-pattern><url-pattern>/imgs/*url-pattern><url-pattern>*.jpgurl-pattern><url-pattern>*.woffurl-pattern><url-pattern>*.tffurl-pattern>servlet-mapping><welcome-file-list><welcome-file>/test/login.jspwelcome-file>welcome-file-list>
web-app>

注意:这里在web的配置文件中我使用了context-param标签,即为上面提到的冲突问题

shiro的配置文件:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><diskStore path="F:\develop\ehcache" /><defaultCache maxElementsInMemory="1000"maxElementsOnDisk="10000000"eternal="false"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="120"timeToLiveSeconds="120"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU">defaultCache>	
ehcache>
  • 引入对应的依赖

    dao层引入entity实体层

    同理:

    service层引入实体层

    serviceImpl层引入dao层与service层

    **注意:**引入的依赖之间具有传递性

    web层引入service层

  • 代码编写:

    dao层:

    注意:这里在匹配xml时候的路径要尤为注意,否则会找不到xml

    userDao.xml:

    
    
    <mapper namespace="cn.xuxiaonan.dao.userDao"><select id="getUsername" resultType="cn.xuxiaonan.entity.vuser" parameterType="String">SELECT * FROM vuser_tb WHERE username = #{username} AND del_flag = 0;select><insert id="insertVuser" parameterType="cn.xuxiaonan.entity.vuser">insert into vuser_tb values(null,#{username},#{password},#{email},#{del_flag},#{date});insert><select id="getUser" resultType="cn.xuxiaonan.entity.vuser"parameterType="String">SELECT * FROM vuser_tb WHERE username = #{username} AND del_flag = 0;select><select id="getPermission" resultType="cn.xuxiaonan.entity.permission"parameterType="int">SELECTpermission_tb.permissionFROMpermission_tbJOIN (roleperm_tbJOIN (role_tbJOIN (roleuser_tbJOINvuser_tbON roleuser_tb.userid = vuser_tb.id) ON role_tb.id =roleuser_tb.roleid) ON roleperm_tb.roleid = role_tb.id) ON permission_tb.id = roleperm_tb.peridWHEREvuser_tb.id = #{id}select>
    mapper>
    

    userDao:

    package cn.xuxiaonan.dao;
    /**
    *
    * 

    Title:userDao

    *

    Description:TODO

    *

    PersonWeb:www.xuxiaonan.cn

    * @author dinggc * @date 2018年9月7日下午4:55:31 * @version 2018 */
    import java.util.List;import cn.xuxiaonan.entity.permission; import cn.xuxiaonan.entity.vuser;public interface userDao {public vuser getUsername(String username)throws Exception;public void insertVuser(vuser vuser)throws Exception;public vuser getUser(String username)throws Exception;public List<permission> getPermission(int id)throws Exception; }

entity层:

注意:由于在网络上传输所以要实现Serializable

BaseEntity:

package cn.xuxiaonan.entity;import java.io.Serializable;/**
*
* 

Title:BaseEntity

*

Description:TODO

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年5月9日下午2:46:22 * @version 2018 */
public class BaseEntity implements Serializable{private String date;//创建信息日期private int del_flag;//删除标记 0存在 1删除public BaseEntity() {super();}public String getDate() {return date;}public void setDate(String date) {this.date = date;}public int getDel_flag() {return del_flag;}public void setDel_flag(int del_flag) {this.del_flag = del_flag;}}

permission:

package cn.xuxiaonan.entity;import java.io.Serializable;/**
*
* 

Title:permission

*

Description:TODO

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年9月11日下午7:00:58 * @version 2018 */
public class permission extends BaseEntity{private int id;private String permission;private String describe;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPermission() {return permission;}public void setPermission(String permission) {this.permission = permission;}public String getDescribe() {return describe;}public void setDescribe(String describe) {this.describe = describe;} }

vuser:

package cn.xuxiaonan.entity;import java.io.Serializable;/**
*
* 

Title:vuser

*

Description:TODO

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年9月7日下午4:33:19 * @version 2018 */
public class vuser extends BaseEntity{private int id;private String username;private String password;private String email;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;} }

interface(service)层:

package cn.xuxiaonan.service;import java.util.List;import org.springframework.context.annotation.Lazy;import cn.xuxiaonan.entity.permission;
import cn.xuxiaonan.entity.vuser;/**
*
* 

Title:userService

*

Description:user接口

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年10月28日下午5:13:55 */
public interface userService {public vuser getUsername(String username)throws Exception;public vuser getUser(String username)throws Exception;public List<permission> getPermission(int id)throws Exception; }

serviceImpl层:

注意:@Service使用dubbo的注解,否则无法上传到注册中心

package cn.xuxiaonan.serviceimpl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;import cn.xuxiaonan.dao.userDao;
import cn.xuxiaonan.entity.permission;
import cn.xuxiaonan.entity.vuser;
import cn.xuxiaonan.service.userService;/**
*
* 

Title:userServiceImpl

*

Description:用户接口实现类

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年10月28日下午5:14:49 */
@Service public class userServicei implements userService{@AutowireduserDao userdao;@Overridepublic vuser getUsername(String username) throws Exception {// TODO Auto-generated method stubreturn userdao.getUsername(username);}@Overridepublic vuser getUser(String username) throws Exception {// TODO Auto-generated method stubSystem.out.println(userdao);return userdao.getUser(username);}@Overridepublic List<permission> getPermission(int id) throws Exception {// TODO Auto-generated method stubreturn userdao.getPermission(id);} }

web层:

整合shiro:

自定义realm:

package cn.xuxiaonan.shiro;import java.util.ArrayList;
import java.util.List;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;import com.alibaba.dubbo.config.annotation.Reference;import cn.xuxiaonan.entity.permission;
import cn.xuxiaonan.entity.vuser;
import cn.xuxiaonan.service.userService;/**
*
* 

Title:CustomRealm

*

Description:自定义realm

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年9月11日下午6:51:21 */
public class CustomRealm extends AuthorizingRealm{private userService userService;public void setUserService(userService userService) {this.userService = userService;}//设置realm的名称@Overridepublic void setName(String name) {super.setName("customRealm");;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//token是用户输入的//第一步从token中取出身份信息String userCode = (String)token.getPrincipal();vuser vuser = null;try {vuser = userService.getUser(userCode);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}//模拟从数据库查询密码//如果查询不到返回null//数据库中用户账号是zhangsanif(vuser==null) {return null;}String PIN = vuser.getPassword();SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(vuser, PIN,this.getName());return simpleAuthenticationInfo;}@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//从principals获取主身份信息//将getPrimaryPrincipal方法返回值转为真实身份信息(在上边的doGetAuthecticationInfo认证通过填充到SimpleAuthenticationInfo)vuser vuser = (vuser) principals.getPrimaryPrincipal();//根据信息获取权限信息//连接数据库。。。//模拟从数据库获取到数据List<permission> permissions = null;try {permissions = userService.getPermission(vuser.getId());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}//...List<String> permission = new ArrayList<String>();for(permission syspermission:permissions) {permission.add(syspermission.getPermission());}//查询到权限数据,返回SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();//将上边查询到授权信息填充到simpleAuthorizationInfo对象中simpleAuthorizationInfo.addStringPermissions(permission); return simpleAuthorizationInfo;} }

controller层:

注意:这里的controller应使用@Reference来引用服务

package cn.xuxiaonan.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;/**
*
* 

Title:mainController

*

Description:TODO

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年11月3日下午10:15:18 * @version 2018 */
@Controller @RequestMapping(value="/mform") public class mainController {@RequestMapping(value="/entrance")public String entrance() {return "test/main";} }
package cn.xuxiaonan.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.alibaba.dubbo.config.annotation.Reference;import cn.xuxiaonan.entity.permission;
import cn.xuxiaonan.entity.vuser;
import cn.xuxiaonan.service.userService;/**
*
* 

Title:userController

*

Description:用户层

*

PersonWeb:www.xuxiaonan.cn

* @author dinggc * @date 2018年10月28日下午5:21:45 */
@Controller @RequestMapping("/user") public class userController {@ReferenceuserService userService;@RequestMapping("/login")public String login(HttpServletRequest request,Model model)throws Exception{//如果登录失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常lei的全限定名String winfo = null;String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); //根据shiro返回的异常类路径判断,抛出指定异常信息if (exceptionClassName!=null){if(UnknownAccountException.class.getName().equals(exceptionClassName)) {//最终会抛给异常处理器winfo = "userisnotexist";}else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {winfo = "oneiswrong";}else{winfo = "other";}}else {winfo = "success";}model.addAttribute("winfo",winfo);return "test/login";}@RequestMapping("/usercheck")@ResponseBodypublic Object usercheck(HttpServletRequest request)throws Exception{String username = request.getParameter("username");vuser vuser = userService.getUsername(username);if(vuser!=null) {return "no";}else {return "yes";}}@RequestMapping("/backentrance")public String backentrance() {return "test/login";}@RequestMapping(value ="/test")public String test() throws Exception {vuser vuser = userService.getUser("dinggc");System.out.println(vuser);return "/test/login";} }
  • 前端代码的编写:

    pageResource与test文件夹已提供


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部