文档章节

使用filter + cookie实现单点登录

放手的风筝
 放手的风筝
发布于 2016/04/21 10:46
字数 1355
阅读 28
收藏 0

1.什么事单点登录

单点登录其实就是实现这么一个功能。例如你登陆了www.bbs.kite.com这个网站,当你再登陆www.news.kite.com这个网站时,

就不需要再登陆了。以上两个网站一个很大的相似点,就是都有相同的域名.kite.com 。

二、单点登录的代码实现

1、新建一个webproject ,名为sso_bbs

2.新建一个servlet

 1 package kite.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.Cookie;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 public class LoginServlet extends HttpServlet
13 {
14     public void doGet(HttpServletRequest request, HttpServletResponse response)
15             throws ServletException, IOException
16     {
17         this.doPost(request, response);
18     }
19 
20     public void doPost(HttpServletRequest request, HttpServletResponse response)
21             throws ServletException, IOException
22     {
23         String userName = request.getParameter("userName");
24         String password = request.getParameter("password");
25         
26         if(userName != null && password != null)
27         {
28             if(userName.equals(password))
29             {
30                 request.getSession().setAttribute("user", userName);
31                 
32                 Cookie cookie = new Cookie("sso", userName);
33                 cookie.setMaxAge(60*60);
34                 cookie.setDomain(".kite.com");
35                 cookie.setPath("/");
36                 response.addCookie(cookie);
37             }
38         }
39         response.sendRedirect(request.getContextPath() + "/index.jsp");
40     }
41 
42 }

3.修改host文件

到C:\Windows\System32\drivers\etc目录下找到名为host文件,并在其中加上以下代码:

 

127.0.0.1        localhost
127.0.0.1        www.bbs.kite.com
127.0.0.1        www.news.kite.com  

4.修改tomcat/config/server.xml文件
  1 <?xml version='1.0' encoding='utf-8'?>
  2 <!--
  3   Licensed to the Apache Software Foundation (ASF) under one or more
  4   contributor license agreements.  See the NOTICE file distributed with
  5   this work for additional information regarding copyright ownership.
  6   The ASF licenses this file to You under the Apache License, Version 2.0
  7   (the "License"); you may not use this file except in compliance with
  8   the License.  You may obtain a copy of the License at
  9 
 10       http://www.apache.org/licenses/LICENSE-2.0
 11 
 12   Unless required by applicable law or agreed to in writing, software
 13   distributed under the License is distributed on an "AS IS" BASIS,
 14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 15   See the License for the specific language governing permissions and
 16   limitations under the License.
 17 -->
 18 <!-- Note:  A "Server" is not itself a "Container", so you may not
 19      define subcomponents such as "Valves" at this level.
 20      Documentation at /docs/config/server.html
 21  -->
 22 <Server port="8005" shutdown="SHUTDOWN">
 23   <!-- Security listener. Documentation at /docs/config/listeners.html
 24   <Listener className="org.apache.catalina.security.SecurityListener" />
 25   -->
 26   <!--APR library loader. Documentation at /docs/apr.html -->
 27   <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
 28   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
 29   <Listener className="org.apache.catalina.core.JasperListener" />
 30   <!-- Prevent memory leaks due to use of particular java/javax APIs-->
 31   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
 32   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
 33   <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
 34 
 35   <!-- Global JNDI resources
 36        Documentation at /docs/jndi-resources-howto.html
 37   -->
 38   <GlobalNamingResources>
 39     <!-- Editable user database that can also be used by
 40          UserDatabaseRealm to authenticate users
 41     -->
 42     <Resource name="UserDatabase" auth="Container"
 43               type="org.apache.catalina.UserDatabase"
 44               description="User database that can be updated and saved"
 45               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
 46               pathname="conf/tomcat-users.xml" />
 47   </GlobalNamingResources>
 48 
 49   <!-- A "Service" is a collection of one or more "Connectors" that share
 50        a single "Container" Note:  A "Service" is not itself a "Container",
 51        so you may not define subcomponents such as "Valves" at this level.
 52        Documentation at /docs/config/service.html
 53    -->
 54   <Service name="Catalina">
 55 
 56     <!--The connectors can use a shared executor, you can define one or more named thread pools-->
 57     <!--
 58     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
 59         maxThreads="150" minSpareThreads="4"/>
 60     -->
 61 
 62 
 63     <!-- A "Connector" represents an endpoint by which requests are received
 64          and responses are returned. Documentation at :
 65          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
 66          Java AJP  Connector: /docs/config/ajp.html
 67          APR (HTTP/AJP) Connector: /docs/apr.html
 68          Define a non-SSL HTTP/1.1 Connector on port 8080
 69     -->
 70     <Connector port="8080" protocol="HTTP/1.1"
 71                connectionTimeout="20000"
 72                redirectPort="8443" />
 73     <!-- A "Connector" using the shared thread pool-->
 74     <!--
 75     <Connector executor="tomcatThreadPool"
 76                port="8080" protocol="HTTP/1.1"
 77                connectionTimeout="20000"
 78                redirectPort="8443" />
 79     -->
 80     <!-- Define a SSL HTTP/1.1 Connector on port 8443
 81          This connector uses the JSSE configuration, when using APR, the
 82          connector should be using the OpenSSL style configuration
 83          described in the APR documentation -->
 84     <!--
 85     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
 86                maxThreads="150" scheme="https" secure="true"
 87                clientAuth="false" sslProtocol="TLS" />
 88     -->
 89 
 90     <!-- Define an AJP 1.3 Connector on port 8009 -->
 91     <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
 92 
 93 
 94     <!-- An Engine represents the entry point (within Catalina) that processes
 95          every request.  The Engine implementation for Tomcat stand alone
 96          analyzes the HTTP headers included with the request, and passes them
 97          on to the appropriate Host (virtual host).
 98          Documentation at /docs/config/engine.html -->
 99 
100     <!-- You should set jvmRoute to support load-balancing via AJP ie :
101     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
102     -->
103     <Engine name="Catalina" defaultHost="localhost">
104 
105       <!--For clustering, please take a look at documentation at:
106           /docs/cluster-howto.html  (simple how to)
107           /docs/config/cluster.html (reference documentation) -->
108       <!--
109       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
110       -->
111 
112       <!-- Use the LockOutRealm to prevent attempts to guess user passwords
113            via a brute-force attack -->
114       <Realm className="org.apache.catalina.realm.LockOutRealm">
115         <!-- This Realm uses the UserDatabase configured in the global JNDI
116              resources under the key "UserDatabase".  Any edits
117              that are performed against this UserDatabase are immediately
118              available for use by the Realm.  -->
119         <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
120                resourceName="UserDatabase"/>
121       </Realm>
122 
123       <Host name="localhost"  appBase="webapps"
124             unpackWARs="true" autoDeploy="true">
125 
126      
127 
128         <!-- SingleSignOn valve, share authentication between web applications
129              Documentation at: /docs/config/valve.html -->
130         <!--
131         <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
132         -->
133 
134         <!-- Access log processes all example.
135              Documentation at: /docs/config/valve.html
136              Note: The pattern used is equivalent to using pattern="common" -->
137         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
138                prefix="localhost_access_log." suffix=".txt"
139                pattern="%h %l %u %t &quot;%r&quot; %s %b" />
140 
141       </Host>
142       
143        
144 
145        <Host name="www.bbs.kite.com"  appBase="bbs">
146        </Host>
147 
148        <Host name="www.news.kite.com"  appBase="news">
149        </Host>
150     </Engine>
151   </Service>
152 </Server>

5、将sso_bbs项目中的webroot拷贝一份到tomcat的安装目录下的bbs、news文件夹,并改名为ROOT(因为服务器启动时会默认在ROOT文件夹中

6.新建一个拦截器

 1 package kite.filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.Cookie;
12 import javax.servlet.http.HttpServletRequest;
13 
14 public class LoginFilter implements Filter
15 {
16 
17     @Override
18     public void destroy()
19     {
20         // TODO Auto-generated method stub
21         
22     }
23 
24     @Override
25     public void doFilter(ServletRequest req, ServletResponse resp,
26             FilterChain chain) throws IOException, ServletException
27     {
28         
29         HttpServletRequest request = (HttpServletRequest) req;
30         //在request中获得session 判断是否存在user对应的value  如果不存在从 cookie中获得
31         if(request.getSession().getAttribute("user") == null)
32         {
33             Cookie[] cs =  request.getCookies();
34             if(cs != null && cs.length > 0)
35             {
36                 for(Cookie c : cs)
37                 {
38                     if("sso".equals(c.getName())) 
39                     {
40                         request.getSession().setAttribute("user", c.getValue());
41                     }
42                 }
43             }
44             
45         }
46         chain.doFilter(request, resp);
47     }
48 
49     @Override
50     public void init(FilterConfig arg0) throws ServletException
51     {
52         // TODO Auto-generated method stub
53         
54     }
55 
56 }

7.在web.xml文件中配置filter

8.测试登录

 

© 著作权归作者所有

放手的风筝
粉丝 14
博文 60
码字总数 50362
作品 0
浦东
程序员
私信 提问
SSO单点登录学习总结(2)——基于Cookie+fliter单点登录实例

1、使用Cookie解决单点登录 技术点: 1、设置Cookie的路径为setPath("/").即Tomcat的目录下都有效 2、设置Cookie的域setDomain(".itcast.com");即bbs.itcast.com,或是mail.itcast.com有效。即......

zhanghaiyang
2016/01/20
34
0
JForum论坛单点登录的几种实现方式 (CAS和Cookie)

JForum论坛单点登录的几种实现方式 (CAS和Cookie) 王保政 Email:baozhengw@netease.com 2007-8-4 一、用CAS实现Jforum的单点登录 (一)CAS客户端应用的web.xml配置 CAS和jforum的安装过程本文...

迷途d书童
2012/03/09
211
0
共同父域下的单点登录

共同父域下的单点登录 址:http://blog.csdn.net/ghsau/article/details/20466351,转载请注明。 单点登录(Single Sign On),简称为SSO,SSO不仅在企业级开发很常用,在互联网中更是大行其道...

517270667
2017/06/29
0
0
完全跨域的单点登录

版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/ghsau。 本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/20545513,转载请注明。 完全跨...

james_laughing
2016/06/12
148
2
Spring Session关键类源码分析

要想使用spring session,还需要创建名为springSessionRepositoryFilter的SessionRepositoryFilter类。该类实现了Sevlet Filter接口,当请求穿越sevlet filter链时应该首先经过springSession...

芥末无疆
2018/02/17
0
0

没有更多内容

加载失败,请刷新页面

加载更多

springboot2.0 maven打包分离lib,resources

springboot将工程打包成jar包后,会出现获取classpath下的文件出现测试环境正常而生产环境文件找不到的问题,这是因为 1、在调试过程中,文件是真实存在于磁盘的某个目录。此时通过获取文件路...

陈俊凯
今天
6
0
BootStrap

一、BootStrap 简洁、直观、强悍的前端开发框架,让web开发更加迅速、简单 中文镜像网站:http://www.bootcss.com 用于开发响应式布局、移动设备优先的WEB项目 1、使用boot 创建文件夹,在文...

wytao1995
今天
10
0
小知识:讲述Linux命令别名与资源文件的区别

别名 别名是命令的快捷方式。为那些需要经常执行,但需要很长时间输入的长命令创建快捷方式很有用。语法是: alias ppp='ping www.baidu.com' 它们并不总是用来缩短长命令。重要的是,你将它...

老孟的Linux私房菜
今天
8
0
《JAVA核心知识》学习笔记(6. Spring 原理)-5

它是一个全面的、企业应用开发一站式的解决方案,贯穿表现层、业务层、持久层。但是 Spring 仍然可以和其他的框架无缝整合。 6.1.1. Spring 特点 6.1.1.1. 轻量级 6.1.1.2. 控制反转 6.1.1....

Shingfi
今天
8
0
Excel导入数据库数据+Excel导入网页数据【实时追踪】

1.Excel导入数据库数据:数据选项卡------>导入数据 2.Excel导入网页数据【实时追踪】:

东方墨天
今天
11
1

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部