`
dtt3401885
  • 浏览: 17893 次
文章分类
社区版块
存档分类
最新评论

grails 统一认证加单点登录

 
阅读更多

需求:公司有两套系统 A.B ,两套系统希望统一管理公司员工信息,并且可以做到单点登录。管理系统C

思路:在AB系统登录方法内 通过HttpClient 方法访问系统C内的方法,系统C 接收登录信息后,验证。验证通过后把信息、令牌与时效性加密,通过 response. 返回给AB ,AB接收信息后,会把通过信息加入到COOK内。当A系统切换B系统时,登录方法首先读取cook,令牌通过并且在时效性内时,直接把登录信息赋值。不用再输入账号密码。直接再向C调用信息。

 

AB 系统 登录方法:包括读取COOK 以及向C调用

 

import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.codehaus.groovy.grails.web.json.JSONObject
import org.grails.plugins.springsecurity.service.AuthenticateService

import org.springframework.security.AuthenticationTrustResolverImpl
import org.springframework.security.DisabledException
import org.springframework.security.context.SecurityContextHolder as SCH
import org.springframework.security.ui.AbstractProcessingFilter
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter
import com.detao.dtma.utils.CryptUtil
import java.text.SimpleDateFormat
import javax.servlet.http.Cookie
/**
	 * Show the login page.
	 */
	def auth = {
		println "bg:auth+"+params
		def ifpass=false
		if((params?.j_password!= null&&!"".equals(params?.j_password))&&(params?.j_username!= null&&!"".equals(params?.j_username))){
			ifpass=true
		}else{
		 try{
		
			 Cookie[] cookies = request.getCookies();
			 def cokname
			 def cokpaswd
			 def coktoken
			 def coktokentime
			 def cookshixiao
			 for(Cookie cookie : cookies){
				 if(cookie.getName().equalsIgnoreCase("asiacom_name")){
					cokname = cookie.getValue();
				 }
				 if(cookie.getName().equalsIgnoreCase("asiacom_paswd")){
					 cokpaswd = cookie.getValue();
				  }
				 if(cookie.getName().equalsIgnoreCase("asiacom_token")){
					 coktoken = cookie.getValue();
					 println "coktoken"+coktoken+"=========\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
				  }
				 if(cookie.getName().equalsIgnoreCase("asiacom_tokentime")){
					 coktokentime = cookie.getValue();
				  }
				 if(cookie.getName().equalsIgnoreCase("asiacom_shixiao")){
					 cookshixiao = cookie.getValue();
				  }
				 
			 }
			 println "cokname"+cokname
			 println "cokpaswd"+cokpaswd
			 println "coktoken"+coktoken
			 println "coktokentime"+coktokentime
			 println "cookshixiao"+cookshixiao
			 if(coktoken=='true'){
				def cokcreatetime= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(coktokentime)
				println cokcreatetime
				Calendar c = Calendar.getInstance();
				c.setTime(cokcreatetime);
				//30为增加的天数
				c.add(Calendar.MINUTE,Integer.parseInt(cookshixiao));
				def youxiaotime= c.getTime()
				println youxiaotime
				def newtime=new Date()
				println newtime<youxiaotime
				if(newtime<youxiaotime){
					println "取得cook成功!"
					params?.j_username=cokname
					params?.j_password=cokpaswd
					ifpass=true
				}
				 
			 }
			 println "cokname"+cokname
			 println "cokpaswd"+cokpaswd
			 println "coktoken"+coktoken
			 println "coktokentime"+coktokentime
		 }catch(e){
		 
		 
		 
		 }
	
		}
		def logs=session.loginUser
		println  "params:========"+params
		println "ifpass"+ifpass
		if(ifpass){
			def unifiedCertification=UnifiedCertification.findByWhetherlocal(1)
			def code=''
			def systemt=''
			def url="http://192.168.0.52:8080/项目名字/unifiedCertification/reviceunifiedcertification"
			if(unifiedCertification){
				code=unifiedCertification.checkcode
				systemt=unifiedCertification.systemtype
				url=unifiedCertification.checkurl
			}else{
				code='验证的密码'
				systemt='oa'
			}
			def codename=params?.j_username+'j_passwordj_username'+params?.j_password
			def cryutil=new CryptUtil()
			def certification=cryutil.encryptAES(codename,code)
			println certification
			println "111111"
			HttpClient       httpClient   = new HttpClient();
			HttpClientParams clientParams = new HttpClientParams();
			println url
			println "2222222222"
			PostMethod method  = new PostMethod(url)
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
			method.addParameter("codename", certification);
			method.addParameter("codepaswd", systemt);
			println method
			println "333333333333"
			try {
				//httpClient.getParams().setContentCharset("GBK");
				// 执行postMethod


				int statusCode = httpClient.executeMethod(method);
				def msg=''
				if (statusCode == 200) {
					def jsonstr=method.getResponseBodyAsString();
					cryutil=new CryptUtil()
					def fication=cryutil.decryptAES(jsonstr,code)
					JSONObject jsona = new JSONObject(fication);
					def enabled=jsona.get("enabled")
					println  "禁用:"+enabled.get("enabled")
					def lingpai=jsona.get("lingpai")
					println "令牌:"+lingpai.get("lingpai")

					if(lingpai.get("lingpai")=='false'){

						if(enabled.get("enabled")=='false'){
							println "--"
							msg='账号已被禁用'
						}else{
							println "=="
							msg='账号密码不正确'
						}
					}else{
						def departinfor=jsona.get("deprest")
						println "部门信息:"+departinfor
						def shixiao=jsona.get("shixiao")
						println "时效:"+shixiao
						def item=jsona.get("ids")
						println "菜单:"+item
						def rrust=jsona.get("rrust")
						println  "权限:"+rrust
						def ulist=jsona.get("ulist")
						println  "人员:"+ulist
						def filterver=jsona.get("filterver")
						println  "访问:"+filterver
						
						
						Cookie cookiename=new Cookie("asiacom_name",params?.j_username);
						Cookie cookiepaswd=new Cookie("asiacom_paswd",params?.j_password);
						Cookie cookietoken=new Cookie("asiacom_token","true");
						def newdate=new Date();
						def cooktime=(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(newdate)
						Cookie cookietokentime=new Cookie("asiacom_tokentime",cooktime);
						//Cookie cookieshixiao=new Cookie("asiacom_shixiao",shixiao.get("shixiao").toString());
						Cookie cookieshixiao=new Cookie("asiacom_shixiao",'2');
						//cookie1.setMaxAge(3*3600*1000);
						// cookie2.setMaxAge(3*3600*1000);
						response.addCookie(cookiename);;
						response.addCookie(cookiepaswd);
						response.addCookie(cookietoken);;
						response.addCookie(cookietokentime);
						response.addCookie(cookieshixiao);
						
						
						/**
						 * 部门父级的父级
						 */


						def parenttwodepid=departinfor.get("parentdepidtwo").toString()
						def parenttwodepname=departinfor.get("parentdepnametwo").toString()
						def com=Company.get(departinfor.get("company").toString())
						def parentdepdesctwo=departinfor.get("parentdepdesctwo").toString()
						def parentdeptwoversion=0
						
						def parenttwo=null
						if(!parenttwodepid||parenttwodepid=='null'||parenttwodepid==null){//判断部门父级的父级是否存在

						}else{//部门父级的父级存在
						    parentdeptwoversion=Integer.parseInt(departinfor.get("parentdeptwoversion").toString())
							def depparenttwo=Department.findByDepdescAndDepname(parentdepdesctwo,parenttwodepname)
							if(!depparenttwo){//部门父级的父级在本系统中不存在 需要新建
								def newdepparttwo=new Department()

								newdepparttwo.company=Company.get(departinfor.get("company").toString())
								newdepparttwo.depname=departinfor.get("parentdepnametwo").toString()
								newdepparttwo.depdesc=departinfor.get("parentdepdesctwo").toString()
								newdepparttwo.deplevel=departinfor.get("parentdepleveltwo").toString()
								newdepparttwo.depnuber=departinfor.get("parentdepnubertwo").toString()
								newdepparttwo.version=parentdeptwoversion
								if(newdepparttwo.save(flush:true)){
									parenttwo=newdepparttwo
								}else{
									println "部门父级的父级创建失败"
								}
							}else{
							   if(depparenttwo.version!=parentdeptwoversion){
								depparenttwo.company=Company.get(departinfor.get("company").toString())
								depparenttwo.depdesc=departinfor.get("parentdepdesctwo").toString()
								depparenttwo.deplevel=departinfor.get("parentdepleveltwo").toString()
								depparenttwo.depnuber=departinfor.get("parentdepnubertwo").toString()
								depparenttwo.version=parentdeptwoversion
								if(depparenttwo.save(flush:true)){
									
								}else{
									println "部门父级的父级更新失败"
								}

							}
							   parenttwo= depparenttwo
						}
						}
						/**
						 * 部门父级
						 */
						def parentdep=null
						def parentdepid=departinfor.get("parentdepid").toString()
						def parentdepname=departinfor.get("parentdepname").toString()
						def parentdepdesc=departinfor.get("parentdepdesc").toString()
						def parentdepversion=0
						if(!parentdepid||parentdepid=='null'||parentdepid==null){//判断部门父级是否存在

						}else{//部门父级存在
						    parentdepversion=Integer.parseInt(departinfor.get("parentdepversion").toString())
							def depparent=Department.findByDepdescAndDepname(parentdepdesc,parentdepname)
							if(!depparent){//部门父级在本系统中不存在 需要新建
								def newdeppart=new Department()

								newdeppart.company=Company.get(departinfor.get("company").toString())
								newdeppart.depname=departinfor.get("parentdepname").toString()
								newdeppart.depdesc=departinfor.get("parentdepdesc").toString()
								newdeppart.deplevel=departinfor.get("parentdeplevel").toString()
								newdeppart.depnuber=departinfor.get("parentdepnuber").toString()
								newdeppart.parent=parenttwo
								newdeppart.version=parentdepversion
								if(newdeppart.save(flush:true)){
									parentdep=newdeppart
								}else{
									println "部门父级创建失败"
								}
							}else{ 
							    if(depparent.version!=parentdepversion){
								
								depparent.company=Company.get(departinfor.get("company").toString())
								depparent.depdesc=departinfor.get("parentdepdesc").toString()
								depparent.deplevel=departinfor.get("parentdeplevel").toString()
								depparent.depnuber=departinfor.get("parentdepnuber").toString()
								depparent.parent=parenttwo
								depparent.version=parentdepversion
								if(depparent.save()){
									
								}else{
									println "部门父级更新失败"
								}
								
								}
								parentdep=depparent
							}
						}
						/**
						 * 部门
						 */
						def depar=null
						def depid=departinfor.get("depid").toString()
						def depname=departinfor.get("depname").toString()
						def depdesc=departinfor.get("depdesc").toString()
						def depnuberversion=0
						if(!depid||depid=='null'||depid==null){//判断部门父级是否存在

						}else{//部门父级存在
						    Integer.parseInt(departinfor.get("depnuberversion").toString())
							def dep=Department.findByDepdescAndDepname(depdesc,depname)
							if(!dep){//部门父级在本系统中不存在 需要新建
								def newdep=new Department()
								newdep.company=Company.get(departinfor.get("company").toString())
								newdep.depname=departinfor.get("depname").toString()
								newdep.depdesc=departinfor.get("depdesc").toString()
								newdep.deplevel=departinfor.get("deplevel").toString()
								newdep.depnuber=departinfor.get("depnuber").toString()
								newdep.version=depnuberversion
								newdep.parent=parentdep
								if(newdep.save(flush:true)){
									depar=newdep
								}else{
									println "部门创建失败"
								}
							}else{
									if(dep.version!=depnuberversion){
										dep.company=Company.get(departinfor.get("company").toString())
										dep.depdesc=departinfor.get("depdesc").toString()
										dep.deplevel=departinfor.get("deplevel").toString()
										dep.depnuber=departinfor.get("depnuber").toString()
										dep.parent=parentdep
										dep.version=depnuberversion
										if(dep.save(flush:true)){
										
										}else{
											println "部门更新失败"
										}
									}
									depar=dep
								}
						}//部门处理完毕
						/**
						 * 人员开始处理
						 */
						def loginUser=null

						def username=ulist.get("username").toString()
						def userRealName=ulist.get("userRealName").toString()
						def uu=U.findByUserRealNameAndUsername(userRealName,username)
						def uversion=Integer.parseInt(ulist.get("uversion").toString())
						if(!uu){
							def newu=new U()
							newu.passwd=ulist.get("passwd").toString()
							newu.enabled=ulist.get("enabled").toString()
							newu.username=username
							newu.userRealName=ulist.get("userRealName").toString()
							newu.department=depar
							newu.version=uversion
							if(newu.save(flush:true)){
								loginUser=newu
							}else{
								println "登录人创建失败"
							}
						}else{
							if(uversion!=uu.version){
							
							uu.passwd=ulist.get("passwd").toString()
							uu.enabled=ulist.get("enabled").toString()
							uu.userRealName=ulist.get("userRealName").toString()
							uu.department=depar
							uu.version=uversion
							if(uu.save(flush:true)){
							
							}else{
								println "登录人更新失败"
							}
							
							}
							loginUser=uu
						}//人员处理完成
						/**
						 * 权限处理
						 */
						def rr=rrust.get("rlist")
						
						session.authority=rr
						println "authority:"+session.authority
                        session.filterver=filterver.get("filterurl").toString()
			
						/**
						 * URL item 配置
						 */


						def paItemsstrid=item.get("paItemsstrid").split(",")
						def paItemsstritemname=item.get("paItemname").split(",")
						def paItemsstritemurl=item.get("paItemurl").split(",")
						def paItemsstritemicons=item.get("paItemicons").split(",")
						def paItemsstritemorderNum=item.get("paItemorderNum").split(",")
                        def paItemorversion=item.get("paItemorversion").split(",")
						
						def chItemsstritemurl=item.get("chItemurl").split(",")
						def chItemsstritemicons=item.get("chItemicons").split(",")
						def chItemsstrid=item.get("chItemsstrid").split(",")
						def chItemsstritemname=item.get("chItemname").split(",")
						def chItemsstritemorderNum=item.get("chItemorderNum").split(",")
						def chItemsstritemparent=item.get("chItemparent").split(",")
						def chItemsion=item.get("chItemsion").split(",")
						
                        def paritem=Items.findAllByUuAndParentIsNotNull(loginUser)
						paritem.each{
							it.delete()
						}
						def ziitems=Items.findAllByUuAndParentIsNull(loginUser)
						ziitems.each{
							it.delete()
						}
						for(def i=0;i<paItemsstrid.size();i++){
								def newparentitems=new Items()
								newparentitems.unifiid=paItemsstrid[i].toString()
								newparentitems.itemname=paItemsstritemname[i].toString()
								newparentitems.itemurl=paItemsstritemurl[i].toString()
								newparentitems.itemicons=paItemsstritemicons[i].toString()
								newparentitems.itemlevel=1
								newparentitems.uu=loginUser
								try{
									newparentitems.orderNum=Integer.parseInt(paItemsstritemorderNum[i].toString())
								}catch(e){
									newparentitems.orderNum=99
								}

								if(newparentitems.save(flush:true)){
									println "新建父级items成功:"+newparentitems.id
								}else{
									println "新建items失败:"+newparentitems.errors
								}

						}//处理父级菜单完成

						for(def i=0;i<chItemsstrid.size();i++){
								def newchiitems=new Items()
								newchiitems.unifiid=chItemsstrid[i].toString()
								newchiitems.itemname=chItemsstritemname[i].toString()
								newchiitems.itemurl=chItemsstritemurl[i].toString()
								newchiitems.itemicons=chItemsstritemicons[i].toString()
								newchiitems.itemlevel=2
								newchiitems.uu=loginUser
								newchiitems.parent=Items.findByUnifiidAndUu(chItemsstritemparent[i].toString(),loginUser)
								try{
									newchiitems.orderNum=Integer.parseInt(chItemsstritemorderNum[i].toString())
								}catch(e){
									newchiitems.orderNum=99
								}
								if(newchiitems.save(flush:true)){

									println "新建items成功"+newchiitems.id
								}else{
									println "新建items失败:"+newchiitems.errors
								}

						}//处理子级菜单完成
						println "222222222"
						
						session.loginUser=loginUser.id

						redirect(controller:"home",action:"index")
					
					}





				}
			} catch (IllegalArgumentException e) {
				println e
				println "5555555555"
				e.printStackTrace();
			} catch (HttpException e) {
				println e
				println "66666666666发生致命的异常,可能是协议不对或者返回的内容有问题"
				// 发生致命的异常,可能是协议不对或者返回的内容有问题
				e.printStackTrace();
			} catch (IOException e) {
				println e
				println "7777777777发生网络异常"
				// 发生网络异常
				e.printStackTrace();
			} finally {
				println "88888888释放连接"
				// 释放连接
				method.releaseConnection();
			}
		}else{


		}

	}

 C系统接收方法

 

 

def reviceunifiedcertification={
		JSONObject responseJSONObject = new JSONObject()
		def lingpai=[:]
		def shixiao=[:]
		def enabled=[:]
		def codename=params.codename
		def codepaswd=params.codepaswd
		def code=''
		def systemt=''
		def Timeliness=0
		def unifiedCertification=UnifiedCertification.findBySystemtypeAndWhetherlocal(codepaswd,2)
		if(unifiedCertification){
		code=unifiedCertification.checkcode
		systemt=unifiedCertification.systemtype
		Timeliness=30
		}else{
		code='验证的密码'
		systemt='oa'
		}
		def cryutil=new CryptUtil()
		def certification=cryutil.decryptAES(codename,code)
		def namepass=certification.split("j_passwordj_username")
		println "namepass:"+namepass
		if(namepass.size()==2){
		def paswd= authenticateService.encodePassword(namepass[1])
		println "paswd:"+paswd
		//def u=U.findByUsernameAndPasswd(namepass[0],paswd)
		def u=U.findByUsername(namepass[0])
		println "u:"+u
		if(u&&u?.enabled){
		def r=u.authorities//权限
		println "rrrrrrrrrrrrrrrr"+r
		def dep=u.department//部门
		def ids = []//菜单列表
		def idsrest=[:]
		def rrust=[:]
		def deprest=[:]
		def ulist=[:]
		def filterver=[:]
		def rlist=''
		def filterurl=''
	
		r.each {
			if(it.cation==unifiedCertification){
				rlist+=it.authority+','
				def fil=Remap.findAllByConfigAttributeLike("%"+it.authority+"%") 
				println "authority:"+it.authority
				println "file:"+fil
				for(def ff=0;ff<fil.size();ff++){
					filterurl+=fil[ff].url+','
				}
				
				ids.add(it.id)
				}
			
			  }	
		
		def sortedtstStr = ids.sort()

		def rolesItems = []
		sortedtstStr.each {
			def roles = Authresou.findAllByRole(R.get(it),[order:"desc",sort:"orderNum"]).item
			roles.each {

				rolesItems.add(it)
			}
		}
		def paItems = []
		def chItems = []
        def paItemsstrid=''
		def paItemname=''
		def paItemurl=''
		def paItemicons=''
		def paItemorderNum=''
		def paItemorversion=''
		
		
		def chItemsstrid=''
		def chItemname=''
		def chItemurl=''
		def chItemicons=''
		def chItemorderNum=''
		def chItemparent=''
		def chItemsion=''
		rolesItems.sort { a,b->
			a.orderNum - b.orderNum
		}

		rolesItems.each{
			if(it.parent){
				if(!chItems.contains(it)){
					  chItems.add(it)
					  chItemsstrid+=removestr(it.id)+','
					  chItemname+=removestr(it.itemname)+','
					  chItemurl+=removestr(it.itemurl)+','
					  chItemicons+=removestr(it.itemicons)+','
					  chItemorderNum+=removestr(it.orderNum)+','
					  chItemparent+=removestr(it.parent.id)+','
					  chItemsion+=removestr(it.version)+','
					 
		
				}
			}else{
				if(!paItems.contains(it)){
					  paItems.add(it)
					  paItemsstrid+=removestr(it.id)+','
					  paItemname+=removestr(it.itemname)+','
					  paItemurl+=removestr(it.itemurl)+','
					  paItemicons+=removestr(it.itemicons)+','
					  paItemorderNum+=removestr(it.orderNum)+','
					  paItemorversion+=removestr(it.version)+','
					 
				}
			}
		}
		idsrest.put("chItemsstrid", chItemsstrid)
		idsrest.put("chItemname", chItemname)
		idsrest.put("chItemurl", chItemurl)
		idsrest.put("chItemicons", chItemicons)
		idsrest.put("chItemorderNum", chItemorderNum)
		idsrest.put("chItemparent", chItemparent)
		idsrest.put("chItemsion", chItemsion)
		
		idsrest.put("paItemsstrid", paItemsstrid)
		idsrest.put("paItemname", paItemname)
		idsrest.put("paItemurl", paItemurl)
		idsrest.put("paItemicons", paItemicons)
		idsrest.put("paItemorderNum", paItemorderNum)
		idsrest.put("paItemorversion", paItemorversion)
		filterver.put("filterurl", filterurl)
		rrust.put("rlist", rlist)
		deprest.put("company", dep.company?.id.toString())
		deprest.put("depid", dep.id)
		deprest.put("depname", dep.depname)
		deprest.put("depdesc", dep.depdesc)
		deprest.put("deplevel", dep.deplevel)
		deprest.put("depnuber", dep.depnuber)
		deprest.put("depnuberversion", dep.version)
		deprest.put("parentdepid", dep?.parent?.id)
		deprest.put("parentdepname", dep?.parent?.depname)
		deprest.put("parentdepdesc", dep?.parent?.depdesc)
		deprest.put("parentdeplevel", dep?.parent?.deplevel)
		deprest.put("parentdepnuber", dep?.parent?.depnuber)
		deprest.put("parentdepversion", dep?.parent?.version)
		deprest.put("parentdepidtwo", dep?.parent?.parent?.id)
		deprest.put("parentdepnametwo", dep?.parent?.parent?.depname)
		deprest.put("parentdepdesctwo", dep?.parent?.parent?.depdesc)
		deprest.put("parentdepleveltwo", dep?.parent?.parent?.deplevel)
		deprest.put("parentdepnubertwo", dep?.parent?.parent?.depnuber)
		deprest.put("parentdeptwoversion", dep?.parent?.parent?.version)
		lingpai.put('lingpai', 'true')
		enabled.put('enabled', 'true')
		shixiao.put('shixiao',Timeliness)
		ulist.put('username',u.username)
		ulist.put('uid',u.id)
		ulist.put('uversion',u.version)
		ulist.put('userRealName',u.userRealName)
		ulist.put('passwd',u.passwd)
		ulist.put('enabled',u.enabled)
		responseJSONObject.put("ids",idsrest)
		responseJSONObject.put("rrust",rrust)
		responseJSONObject.put("filterver",filterver)
		responseJSONObject.put("deprest",deprest)
		responseJSONObject.put("lingpai",lingpai)
		responseJSONObject.put("shixiao",shixiao)
		responseJSONObject.put('enabled', enabled)
		responseJSONObject.put('ulist', ulist)
		}else{
		lingpai.put('lingpai', 'false')
		if(u){
			enabled.put('enabled', 'false')
		}else{
		   enabled.put('enabled', 'null')
		}
		responseJSONObject.put("lingpai",lingpai)
		responseJSONObject.put("enabled",enabled)
		}
		def respontpstr=responseJSONObject.toString()
		 cryutil=new CryptUtil()
		 println "加密前数据:"+respontpstr
		def unication=cryutil.encryptAES(respontpstr,code)
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("application/json; charset=utf-8");
		 println "加密数据:"+unication
		 cryutil=new CryptUtil()
		 def aa=cryutil.decryptAES(unication,code)
		 println "解密数据:"+aa
		 PrintWriter out = null;
		 try {
			 out = response.getWriter();
			 out.append(unication);
			
		 } catch (IOException e) {
			 e.printStackTrace();
		 } finally {
			 if (out != null) {
				 out.close();
			 }
		 }
		}else{
		
		
		}
	}

 

 

 这样就会把信息读取出来。但是有安全性的问题,需要设置filter

package com.detao.dtma.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.detao.dtma.utils.Configuration;



public class FilterUrl implements Filter{

	private String encoding;

	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse,
			FilterChain filterchain) throws IOException, ServletException {

		servletrequest.setCharacterEncoding(encoding);
		servletresponse.setCharacterEncoding(encoding);
		HttpServletRequest req=(HttpServletRequest)servletrequest;
		HttpSession session=req.getSession();
		HttpServletResponse resp=(HttpServletResponse)servletresponse;
		String url=req.getRequestURI();
		boolean ifpass=false;
		//endsWith startsWith ---s1.startsWith(sd)
		System.out.println("url:"+url);
		 String allowurl = Configuration.getProperty("filter.allowurl.alldefault");
		 System.out.println(allowurl);
		 String[] allowu=allowurl.split(",");
		 System.out.println(allowu);
		 for(int i=0;i<allowu.length;i++){
			 if(url.contains(allowu[i])){
				 System.out.println("默认通过url:"+url);
				 ifpass=true;
				 break;
			 }
		 }
	    try{
	   
		Long loginUser=(Long) session.getAttribute("loginUser");
		System.out.println("loginUser1:"+loginUser);
		if(session.getAttribute("loginUser")!=null){
			System.out.println(session.getAttribute("filterver"));
			String filterurl=(String) session.getAttribute("filterver");
			filterurl=filterurl.replace("**", "[]");
			String[] fileterlist = filterurl.split(",");
			for(int ii=0;ii<fileterlist.length;ii++){
				String[] urluni=fileterlist[ii].split("/");
				String urlfri="/"+urluni[1]+"/";
					if((urluni.length==3)&&((url.contains(urlfri)&&url.contains(urluni[2]))||(url.contains(urlfri)&&urluni[2].equals("[]")))){//长度等于3 并且包含1、2 或者包含1 3为**
							ifpass=true;
							System.out.println("验证通过url:"+url);
							break;
					}
			}
		}
//		 	
	    }catch(Exception e){
	    	e.printStackTrace();
	    	ifpass=false;
	    }
//		if(session.getAttribute("loginUser")!=null){
//			System.out.println("loginUser++++++++++++:"+session.getAttribute("loginUser"));
//			Connection conn =  dataBase.getConnection();
//			PreparedStatement pstmt = null;
//			ResultSet rs = null;
//			System.out.println("==========================");
//		try {
//				String finditems="select t.itemurl from ITEMS t where t.uu_id=?";
//				conn = dataBase.getConnection();
//				pstmt = conn.prepareStatement(finditems);
//				pstmt.setLong(1, (Long) session.getAttribute("loginUser"));
//				rs = pstmt.executeQuery();
//			    while(rs.next()){
//			    	String urlok=rs.getString(1);
//			    	System.out.println("SQL查询结果:"+urlok);
//			    	try{
//			    		String[] urlfenzu=urlok.split("/");
//			    		String quedingurl=urlfenzu[0]+"/"+urlfenzu[1];
//			    		System.out.println("SQL查询拼接字符串:"+quedingurl);
//			    		if(url.contains(quedingurl)){
//			    			ifpass=true;
//			    		}
//			    	}catch(Exception ee){
//			    		
//			    	}
//			   }
//			
//		
//		}catch (Exception e) {
//			System.out.println(e);
//			e.printStackTrace();
//		}finally{
//			dataBase.close(conn, pstmt, rs);
//		 }
//		}
		System.out.println("ifpass:"+ifpass);
		if(ifpass){
			System.out.println("过滤前");
			filterchain.doFilter(servletrequest, servletresponse);
			System.out.println("过滤后");
			//return ;		
		}else{
			System.out.println("过滤失败前");
			resp.sendRedirect("../error404.gsp");
			System.out.println("过滤失败后");
			return ;
		}
		
		
		
		/**if(!url.equals("/kufang/login/login.jsp")&&!url.equals("/kufang/login/login.jsp")){
			if(session.getAttribute("username")==null||session.getAttribute("username")==""){
				resp.sendRedirect("login.jsp");
				return ;
			}
		}
        **/
		//filterchain.doFilter(servletrequest, servletresponse);
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("初始化了");
		encoding = "utf-8";
	}

	public void destroy() {
		System.out.println("销毁了");
	}
}

 filter  web.XML

  <filter>
  <filter-name>sessionFilter</filter-name>
  <filter-class> com.detao.dtma.filter.FilterUrl</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>sessionFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

分享到:
评论

相关推荐

    grails login

    **Grails登录系统详解** Grails是一个基于Java的开源Web应用程序框架,它使用Groovy语言进行开发,提供了高效、简洁的编程模型。在Grails中实现用户登录功能是构建任何Web应用的基础,它确保了数据的安全性和用户...

    Grails Grails Grails

    **Grails 框架详解** Grails 是一个基于 Groovy 语言的开源Web应用程序框架,它构建在Java平台之上,旨在简化开发过程并提高生产力。Grails 的设计深受Ruby on Rails的影响,提供了MVC(模型-视图-控制器)架构模式...

    Grails权威指南 Grails权威指南

    《Grails权威指南》是一本全面深入探讨Grails框架的专著,旨在帮助读者掌握这一强大的Web开发工具。Grails是一种基于Groovy语言的开源框架,它为构建现代、高效的应用程序提供了简洁高效的解决方案。本指南针对不同...

    grails-用户手册

    《Grails用户手册》 Grails,作为一个基于Groovy语言的开源Web应用框架,深受开发者喜爱,它简化了Java开发的复杂性,提供了强大的MVC(Model-View-Controller)架构,以及丰富的插件系统。这份用户手册将帮助你...

    Grails3配置单独的数据库properties.pdf

    在IT行业中,Grails是一个基于Groovy语言的开源Web应用框架,它简化了Java平台上的开发工作。Grails 3是其一个重要的版本更新,带来了许多改进和新特性。本篇将详细介绍如何在Grails 3中配置单独的数据库properties...

    Grails入门指南 -- 针对grails1.0.4更新

    ### Grails入门指南知识点 #### 一、Grails框架简介 - **背景**: Grails是一个基于Groovy语言的开源Web应用框架,适用于Java平台。它旨在简化开发过程,提高开发效率,尤其受到那些希望保留Java环境同时寻求更高效...

    Eclipse下搭建Grails项目

    【Grails项目搭建详解】 Grails是一个基于Groovy语言的开源Web应用框架,它简化了开发过程,尤其适合快速构建动态网站。在Eclipse中搭建Grails项目可能相对复杂,但通过以下步骤,即使是初学者也能顺利进行。 1. *...

    第一个grails程序

    4. **安全控制**:Grails提供了Spring Security插件,可以轻松实现权限管理和认证。在这个例子中,可能使用了该插件来处理登录验证,如检查用户名和密码是否匹配,并设置会话信息。 5. **配置**:在`Config.groovy`...

    eclipse开发grails插件

    本篇将详细讲解如何使用Eclipse开发Grails插件,以及涉及的相关知识点。 首先,让我们了解**Eclipse**。Eclipse不仅是一个IDE,它还拥有一个庞大的插件生态系统,支持多种编程语言和开发工具。对于Grails开发,我们...

    Grails中文参考手册

    **Grails 概述** Grails 是一个基于 Groovy 语言的开源 web 应用程序框架,它构建在 Java 平台上,旨在提高开发效率,简化常见 Web 开发任务。Grails 遵循 Model-View-Controller (MVC) 架构模式,允许开发者快速...

    Grails从入门指南(第二版)

    7. **安全与认证**:了解Grails的安全机制,如Spring Security插件,实现用户身份验证和授权。 8. **模板引擎与响应式编程**:学习使用GSP(Grails Server Pages)进行视图渲染,并接触响应式编程概念。 9. **插件...

    Grails登陆实例

    ### Grails登录实例详解 #### 一、简介 本文档将详细介绍如何在Grails框架下构建一个简单的登录系统。此示例不仅展示了基础的登录功能,还包括了密码加密等安全特性。通过本教程,读者可以了解到如何从零开始搭建...

    grails-2.4.4.zip

    《Grails 2.4.4 框架深度解析》 Grails 2.4.4 是一个基于Java的开源Web应用框架,它利用Groovy语言的强大特性,为开发者提供了一种高效、灵活的开发环境。这个压缩包“grails-2.4.4.zip”包含了完整的Grails 2.4.4...

    grails中文入门简介

    Grails是一个基于Groovy语言的全栈框架,它遵循约定优于配置的原则,并且紧密集成Spring和Hibernate等流行的Java库,简化了开发流程。Grails在IT行业中尤其受到重视,因为它能够帮助开发者快速搭建并部署基于MVC模式...

    Grails入门指南书籍和源码----下载不扣分,回帖加1分,欢迎下载,童叟无欺

    Grails入门指南书籍和源码----下载不扣分,回帖加1分,欢迎下载,童叟无欺 getting started with grails chinese Grails入门指南书籍和源码----下载不扣分,回帖加1分,欢迎下载,童叟无欺 getting started with ...

    grails中文参考手册

    《Grails中文参考手册》是针对Groovy编程语言构建的Web应用框架——Grails的一份详尽学习资料。Grails以其高效、灵活和强大的特性,成为开发人员在Java平台上构建Web应用的热门选择。这份手册旨在帮助初学者快速上手...

    Grails 的过滤器(Grails Filters)

    过滤器提供了统一的入口点,可以在不修改每个控制器动作代码的情况下,实现对请求处理流程的控制。 ### 2. 过滤器的生命周期 Grails 过滤器有四个主要的生命周期阶段: - `before`:在控制器动作执行前运行,如果...

    grails快速开发web

    ### Grails 快速开发 Web 应用程序 #### 一、Grails 概述 Grails 是一种基于 Groovy 的开源应用框架,用于简化 Web 应用程序的开发过程。它采用约定优于配置的原则,这使得开发者可以更快地创建功能丰富的 Web ...

    Grails1.1中文文档

    《Grails 1.1 中文文档》是一个非常宝贵的资源,尤其对于国内的开发者来说,由于Grails在中文社区中的资料相对较少,这份文档的价值不言而喻。Grails是一个基于Groovy语言的开源Web应用框架,它借鉴了Ruby on Rails...

Global site tag (gtag.js) - Google Analytics