使用filter + cookie实现单点登录

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.测试登录

 

你可能感兴趣的:(cookie)