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>

猜你喜欢

转载自dtt3401885.iteye.com/blog/2261031