使用filter + cookie實現單點登陸

1.什麼事單點登陸html

單點登陸其實就是實現這麼一個功能。例如你登錄了www.bbs.kite.com這個網站,當你再登錄www.news.kite.com這個網站時,java

就不須要再登錄了。以上兩個網站一個很大的類似點,就是都有相同的域名.kite.com 。web

2、單點登陸的代碼實現express

一、新建一個webproject ,名爲sso_bbsapache

2.新建一個servlettomcat

 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>

五、將sso_bbs項目中的webroot拷貝一份到tomcat的安裝目錄下的bbs、news文件夾,並更名爲ROOT(由於服務器啓動時會默認在ROOT文件夾中cookie

6.新建一個攔截器session

 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文件中配置filterapp

8.測試登陸

相關文章
相關標籤/搜索