java ssh 单点登录 拦截器

1、登录拦截器类

package cn.com.cardinfo.merchantlink.protal.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

import cn.com.cardinfo.merchantlink.globlevar.GlobleVarClass;

public class LoginFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httprequest = (HttpServletRequest) request;
		HttpServletResponse httpresponse = (HttpServletResponse) response;
		
		HttpSession session = httprequest.getSession();
		Cookie[] cs = httprequest.getCookies();
		String path = httprequest.getRequestURI();
		if (path.endsWith("/LoginPage.jsp")||path.endsWith("/RegisterPage.jsp")) {
			chain.doFilter(httprequest, httpresponse);
		} else {
			boolean isok = false;

			if (session.getAttribute("loginname") != null) {
				//HttpSession sess = (HttpSession) GlobleVarClass.SESSTIONLIST.get(session.getAttribute("loginname"));
			//if (sess.getId().equals(session.getId())) {
					isok = true;
				//}
			}
			/*else {
				if (cs != null) {
					String loginname = null;
					String password = null;
					String sessionid = null;
					for (Cookie c : cs) {
						if ("loginname".equals(c.getName())) {
							loginname = c.getValue();
						} else if ("password".equals(c.getName())) {
							password = c.getValue();
						} else if ("seesionid".equals(c.getName())) {
							sessionid = c.getValue();
						}
					}
					if (loginname != null && password != null
							&& sessionid != null) {
						HttpSession sess = (HttpSession) GlobleVarClass.SESSTIONLIST
								.get(loginname);
						if (sess != null) {
							if (sess.getId() == sessionid) {
								session.setAttribute("loginname", loginname);
								session.setAttribute("password", password);
								// GlobleVarClass.SESSTIONLIST.put(loginname,
								// session);
								isok = true;
							}
						}

					}
				}
			}*/

			if (isok) {
				chain.doFilter(httprequest, httpresponse);
			} else {
				session.setAttribute("preurl", httprequest.getRequestURI());
				httpresponse.sendRedirect("../portal/webcontent/LoginPage.jsp");
			}
		}

	}

	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub

	}

}

2、web.xml配置文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <filter>
        <filter-name>LoginFilter</filter-name>
        <filter-class>cn.com.cardinfo.merchantlink.protal.filter.LoginFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
    
    <!-- 需要? -->
    <listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener> 
	<!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
		 <!--<param-value>classpath:applicationContext.xml</param-value> -->
	</context-param>
    <session-config> 
    <session-timeout>30</session-timeout> 
</session-config> 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

这样就会过滤所有的页面了,然后配合session 的使用,就可以单点登录了

package cn.com.cardinfo.merchantlink.protal.PageAction;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.*;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.com.cardinfo.merchantlink.entity.UserEntity;
import cn.com.cardinfo.merchantlink.globlevar.GlobleVarClass;
import cn.com.cardinfo.merchantlink.service.iservice.IUserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller
public class UserLoginAction extends ActionSupport {

	private String loginname;

	@Autowired
	private IUserService<UserEntity> UserServiceCase;

	private String nickname;

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getLoginname() {
		return loginname;
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	private String isauto = "off";

	/*
	 * private String username;
	 * 
	 * public String getUsername() { return username; }
	 * 
	 * public void setUsername(String username) { this.username = username; }
	 */

	public String getIsauto() {
		return isauto;
	}

	public void setIsauto(String isauto) {
		this.isauto = isauto;
	}

	private String password;

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		//HttpServletResponse response=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
		nickname = UserServiceCase.loginUser(loginname, password);
		
		System.out.println(isauto);
		System.out.println(nickname);
		
		if (nickname != null) {

			setcands(request, response, nickname);
			response.sendRedirect("../index.jsp");
			return SUCCESS;
		} else {
			nickname = null;
			return ERROR;
		}
	}

	@Override
	public void validate() {
		if ("".equals(loginname)) {
			addFieldError("loginname", "用户密码不能为空");
		}
		if ("".equals(password)) {
			addFieldError("password", "密码不能为空!");
		}
	}

	private void setcands(HttpServletRequest requestnew,
			HttpServletResponse responsenew, String nickname) {

		HttpSession session = requestnew.getSession();
		session.setAttribute("loginname", loginname);
		session.setAttribute("password", password);
		session.setAttribute("nickname", nickname);
		HttpSession presession = (HttpSession) GlobleVarClass.SESSTIONLIST
				.get(loginname);
		//checkCookie(requestnew, responsenew, nickname);
		if (presession != null) {
			if (presession.getId() != session.getId()) {
				GlobleVarClass.SESSTIONLIST.remove(loginname);
				presession.invalidate();
				GlobleVarClass.SESSTIONLIST.put(loginname, session);
			}
		} else {
			GlobleVarClass.SESSTIONLIST.put(loginname, session);
			/*
			 * if(isauto.equals("on")) { Cookie cid = new Cookie("sessionid",
			 * session.getId()); //cid.setDomain(pattern); Cookie cuser = new
			 * Cookie("loginname", loginname); Cookie cpw = new
			 * Cookie("password", password); cid.setMaxAge(savetime);
			 * cpw.setMaxAge(savetime); cuser.setMaxAge(savetime);
			 * responsenew.addCookie(cid); responsenew.addCookie(cpw);
			 * responsenew.addCookie(cuser); } else if(isauto.equals("off")) {
			 * Cookie[] cs= requestnew.getCookies(); for (Cookie c : cs) { if
			 * ("loginname".equals(c.getName())) { c.setMaxAge(0); } else if
			 * ("password".equals(c.getName())) { c.setMaxAge(0); } else if
			 * ("seesionid".equals(c.getName())) { c.setMaxAge(0); } } }
			 */

			// request.getSession().getId();
			// application s22;
		}
	}

	private void checkCookie(HttpServletRequest Crequestnew,
			HttpServletResponse Cresponsenew, String Cnickname) {
		int savetime = 36000000;
		HttpSession session = Crequestnew.getSession();
		if (isauto.equals("on")) {
			Cookie cid = new Cookie("sessionid", session.getId());
			// cid.setDomain(pattern);
			Cookie cuser = new Cookie("loginname", loginname);
			Cookie cpw = new Cookie("password", password);
			cid.setMaxAge(savetime);
			cpw.setMaxAge(savetime);
			cuser.setMaxAge(savetime);
			Cresponsenew.addCookie(cid);
			Cresponsenew.addCookie(cpw);
			Cresponsenew.addCookie(cuser);
		} else if (isauto.equals("off")) {
			Cookie[] cs = Crequestnew.getCookies();
			for (Cookie c : cs) {
				if ("loginname".equals(c.getName())) {
					c.setMaxAge(0);
					Cresponsenew.addCookie(c);
				} else if ("password".equals(c.getName())) {
					c.setMaxAge(0);
					Cresponsenew.addCookie(c);
				} else if ("sessionid".equals(c.getName())) {
					c.setMaxAge(0);
					Cresponsenew.addCookie(c);
				}
			}
		}
	}

	public String executeReg() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		GlobleVarClass.SESSTIONLIST.remove(session.getAttribute("loginname"));
		session.invalidate();
		return NONE;
	}
	
	public String loginJump() throws IOException
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		HttpServletResponse response = ServletActionContext.getResponse();
		boolean b=true;
		boolean islogin=false;
		b=session.isNew();
		if(b==false)
		{
			if(session.getAttribute("loginname")!=null&&!session.getAttribute("loginname").toString().equals(""))
			{
				islogin=true;
			}
		}
		if(islogin==true)
		{
			response.setCharacterEncoding("UTF_8");//设置Response的编码方式为UTF-8

		    response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头,设置浏览器的解码方式为UTF-8,其实设置了本句,也默认设置了Response的编码方式为UTF-8,但是开发中最好两句结合起来使用

		    //response.setContentType("text/html;charset=UTF-8");同上句代码作用一样

		    PrintWriter writer = response.getWriter();

		    writer.write("true");
		}
		else
		{
			response.setCharacterEncoding("UTF_8");//设置Response的编码方式为UTF-8

		    response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头,设置浏览器的解码方式为UTF-8,其实设置了本句,也默认设置了Response的编码方式为UTF-8,但是开发中最好两句结合起来使用

		    //response.setContentType("text/html;charset=UTF-8");同上句代码作用一样

		    PrintWriter writer = response.getWriter();

		    writer.write("false");
		}
		
		return NONE;
	}
	
}

这里还可以再次晋级就是因为session是服务端存储,可以和客户端存储的cookie配合起来使用,这样就可以做出保存登录状态这样的功能了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值