NutzCN Logo
问答 session超时后,如何返回到登录页
发布于 2625天前 作者 qq_c01e2ba8 1623 次浏览 复制 上一个帖子 下一个帖子
标签:

session超时后,如何返回到登录页,SessionFilter代码如下:
package com.wonders.tiles.extend.filter;

import javax.servlet.http.HttpSession;

import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;
import org.nutz.mvc.view.UTF8JsonView;

import com.wonders.tdsc.SystemConstants;

public class SessionFilter implements ActionFilter {

private String path;

private static final String JSON = "{\"statusCode\":\"301\",\"message\":\"登陆超时,请重新登陆!\",\"navTabId\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";

public SessionFilter() {}

public SessionFilter(String path) {
    this.path = path;
}

public View match(ActionContext context) {
    context.getResponse().setHeader("X-Frame-OPTIONS", "SAMEORIGIN");
    HttpSession session = Mvcs.getHttpSession(false);
    if (session == null)
       if (Strings.isEmpty(path))
         return null;
       else
         return new ServerRedirectView(path);
    Object obj = session.getAttribute(SystemConstants.SYSTEM_USER);
    if (null == obj){
        if (context.getRequest().getHeader("x-requested-with") != null && 
             context.getRequest().getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            context.getResponse().setHeader("sessionstatus", "timeout");
            UTF8JsonView v = new  org.nutz.mvc.view.UTF8JsonView(new JsonFormat() );  
             v.setData("timeout");//json 格式  
             return v;

            } else {   
    //            return new ViewWrapper(new RawView("htm"), JSON);
               return new ServerRedirectView("/index.jsp");

       }

    }
         return null;
    }
}
6 回复

用 “插入代码” 按钮重新贴一次

package com.wonders.tiles.extend.filter;


import javax.servlet.http.HttpSession;

import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;
import org.nutz.mvc.view.UTF8JsonView;

import com.wonders.tdsc.SystemConstants;

public class SessionFilter implements ActionFilter {
	
	private String path;

	private static final String JSON = "{\"statusCode\":\"301\",\"message\":\"登陆超时,请重新登陆!\",\"navTabId\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
	
	public SessionFilter() {}
	
	public SessionFilter(String path) {
		this.path = path;
	}
	
	public View match(ActionContext context) {
		context.getResponse().setHeader("X-Frame-OPTIONS", "SAMEORIGIN");
		HttpSession session = Mvcs.getHttpSession(false);
    	if (session == null)
    		if (Strings.isEmpty(path))
    			return null;
    		else
    			return new ServerRedirectView(path);
        Object obj = session.getAttribute(SystemConstants.SYSTEM_USER);
        if (null == obj){
        	if (context.getRequest().getHeader("x-requested-with") != null && 
        			context.getRequest().getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
        		 context.getResponse().setHeader("sessionstatus", "timeout");
        		 UTF8JsonView v = new  org.nutz.mvc.view.UTF8JsonView(new JsonFormat() );  
                 v.setData("timeout");//json 格式  
                 return v;
		        		 
		        } else {	
		//            return new ViewWrapper(new RawView("htm"), JSON);
		        	return new ServerRedirectView("/index.jsp");
		       
			}
		
		}
				return null;
		}
	}

那你不是写好了吗?

http://localhost:8080/trademanage
这个是访问地址 ,每次退出之后,再刷新,就会变成http://localhost:8080/trademanage/login

这个是那个login方法,就会返回 "redirect:/login/calogin";

package com.wonders;

import cn.apiclub.captcha.Captcha;

import com.wonders.base.service.Result;
import com.wonders.shrio.exception.CaptchaEmptyException;
import com.wonders.shrio.exception.CaptchaIncorrectException;
import com.wonders.shrio.filter.PlatformAuthenticationFilter;
import com.wonders.slog.SLogService;
import com.wonders.tdsc.SystemConstants;
import com.wonders.tiles.authority.entity.Sys_log;
import com.wonders.tiles.authority.entity.User;
import com.wonders.tiles.authority.service.SysUserService;
import com.wonders.util.SecurityUtil;
import com.wonders.util.StringUtil;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.view.ServerRedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 2016/6/22.
 */
@IocBean // 声明为Ioc容器中的一个Bean
@At("/login") // 整个模块的路径前缀
@Ok("json:{locked:'password|createAt',ignoreNull:true}") // 忽略password和createAt属性,忽略空属性的json输出
public class LoginAt {
	private static final Log log = Logs.get();
	@Inject
	private Dao dao;
	@Inject
	private SysUserService userService;
	@Inject
	private SLogService sLogService;

	@At("")
	@Filters
	public String login(HttpServletRequest req,HttpSession session) {
		log.debug("");
		
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			String attribute ="001";
			String signs = "0";
			String value = "0";
			return "redirect:/home?attribute="+attribute+"&signs="+signs+"&value="+value;
			//return home(req,session,attribute,signs,value);
		} else {
			return "redirect:/login/calogin";//"beetl:/platform/sys/login.html";
		}
	}
	@At("/calogin")
	@Ok("jsp:/calogin.jsp")
	@Filters
	public void calogin() {
		
	}

	@At("/noPermission")
	@Ok("jsp:jsp.noPermission")
	@Filters
	public void noPermission() {
		
	}
	/**
	 * 切换样式,对登陆用户有效
	 *
	 * @param theme
	 * @param req
	 * @RequiresUser 记住我有效
	 * @RequiresAuthentication 就算记住我也需要重新验证身份
	 */
	@At("/theme")
	@RequiresAuthentication
	public void theme(@Param("loginTheme") String theme, HttpServletRequest req) {
		if (!Strings.isEmpty(theme)) {
			Subject subject = SecurityUtils.getSubject();
			if (subject != null) {
				User user = (User) subject.getPrincipal();
				userService.update(Chain.make("loginTheme", theme), Cnd.where("id", "=", user.getId()));
			}
		}
	}

	/**
	 * 切换布局,对登陆用户有效
	 *
	 * @param p
	 * @param v
	 * @param req
	 * @RequiresUser 记住我有效
	 * @RequiresAuthentication 就算记住我也需要重新验证身份
	 */
	@At("/layout")
	@RequiresAuthentication
	public void layout(@Param("p") String p, @Param("v") boolean v, HttpServletRequest req) {
		Subject subject = SecurityUtils.getSubject();
		/*if (subject != null) {
			User user = (User) subject.getPrincipal();
			if ("sidebar".equals(p)) {
				userService.update(Chain.make("loginSidebar", v), Cnd.where("id", "=", user.getUserId()));
				user.setLoginSidebar(v);
			} else if ("boxed".equals(p)) {
				userService.update(Chain.make("loginBoxed", v), Cnd.where("id", "=", user.getUserId()));
				user.setLoginBoxed(v);
			} else if ("scroll".equals(p)) {
				userService.update(Chain.make("loginScroll", v), Cnd.where("id", "=", user.getUserId()));
				user.setLoginScroll(v);
			}
		}*/

	}

	/**
	 * 登陆验证
	 *
	 * @param token
	 * @param req
	 * @return
	 */
	@At("/doLogin")
	@Ok("json")
	@Filters(@By(type = PlatformAuthenticationFilter.class))
	public Object doLogin(@Attr("loginToken") AuthenticationToken token, HttpServletRequest req, HttpSession session) {
		int errCount = 0;
		try {
			//输错三次显示验证码窗口
			errCount = NumberUtils.toInt(Strings.sNull(SecurityUtils.getSubject().getSession(true).getAttribute("errCount")));
			Subject subject = SecurityUtils.getSubject();
			ThreadContext.bind(subject);
			subject.login(token);
			User user = (User) subject.getPrincipal();
			int count = user.getLoginCount() == null ? 0 : user.getLoginCount();
			userService.update(Chain.make("loginIp", user.getLoginIp()).add("loginAt", System.currentTimeMillis())
							.add("loginCount", count + 1).add("isOnline", '1')
					, Cnd.where("id", "=", user.getId()));
			Sys_log sysLog = new Sys_log();
			sysLog.setType("info");
			sysLog.setTag("用户登陆");
			sysLog.setSrc(this.getClass().getName()+"#doLogin");
			sysLog.setMsg("成功登录系统!");
			sysLog.setIp(StringUtil.getRemoteAddr());
			sysLog.setOpBy(user.getId());
			sysLog.setOpAt(new Date());
			sysLog.setUsername(user.getUsername());
			sLogService.async(sysLog);
			session.setAttribute(SystemConstants.SYSTEM_USER, user);
			return Result.success("login.success");
		
		} catch (LockedAccountException e) {
			return Result.error(3, "login.error.locked");
		} catch (UnknownAccountException e) {
			errCount++;
			SecurityUtils.getSubject().getSession(true).setAttribute("errCount", errCount);
			return Result.error(4, "用户名或密码错误");
		} catch (AuthenticationException e) {
			errCount++;
			SecurityUtils.getSubject().getSession(true).setAttribute("errCount", errCount);
			return Result.error(5, "用户名或密码错误");
		} catch (Exception e) {
			errCount++;
			SecurityUtils.getSubject().getSession(true).setAttribute("errCount", errCount);
			return Result.error(6, "login.error.system");
		}
	}

	@Ok("jsp:jsp.index")
	@RequiresAuthentication
	//@Filters()
	public Map<String, Object> home(HttpServletRequest request,HttpSession session, Pager pager,
			String attribute,String signs,String value) {
		session.setAttribute("attribute", attribute);
		session.setAttribute("signs",signs);
		
		return null;
	}
	/**
	 * 退出系统
	 */
	@At("/logout")
	@Ok("re")
	public View logout(HttpSession session) {
		
		try {
			Subject currentUser = SecurityUtils.getSubject();
			User user = (User) currentUser.getPrincipal();
			//currentUser.logout();
			Sys_log sysLog = new Sys_log();
			sysLog.setType("info");
			sysLog.setTag("用户登出");
			sysLog.setSrc(this.getClass().getName()+"#logout");
			sysLog.setMsg("成功退出系统!");
			sysLog.setIp(StringUtil.getRemoteAddr());
			sysLog.setOpBy(user.getId());
			sysLog.setOpAt(new Date());
			sysLog.setUsername(user.getUsername());
			sLogService.async(sysLog);
			session.removeAttribute(SystemConstants.SYSTEM_USER);
			//userService.update(Chain.make("isOnline", '0'), Cnd.where("id", "=", user.getId()));
		} catch (SessionException ise) {
			log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
		} catch (Exception e) {
			log.debug("Logout error", e);
		}
		return new ServerRedirectView("/index");
		
	}

	@At("/captcha")
	@Ok("raw:png")
	public BufferedImage next(HttpSession session, @Param("w") int w, @Param("h") int h) {
		if (w * h < 1) { //长或宽为0?重置为默认长宽.
			w = 200;
			h = 60;
		}
		Captcha captcha = new Captcha.Builder(w, h)
				.addText()
//								.addBackground(new GradiatedBackgroundProducer())
//								.addNoise(new StraightLineNoiseProducer()).addBorder()
//								.gimp(new FishEyeGimpyRenderer())
				.build();
		String text = captcha.getAnswer();
		session.setAttribute("platformCaptcha", text);
		return captcha.getImage();
	}
	
	/**
	 * 修改密码
	 * @param session
	 * @param passwrod
	 * @param pw1
	 * @param pw2
	 * @return
	 */
	@At("/changepw")
	@Ok("json")
	public Object changePW(HttpSession session , @Param("passwrod")String passwrod, @Param("passw1") String pw1,@Param("passw2") String pw2){
		if(!pw1.equals(pw2) ){
			return Result.error("两次输入密码不一致");
		}
		Subject subject = SecurityUtils.getSubject();
		ThreadContext.bind(subject);
		User user = (User) subject.getPrincipal();
		//加密
		String salt = user.getSalt();
		passwrod = new Sha256Hash(passwrod, salt, 1024).toBase64();
		
		if(!user.getPassword().equals(passwrod)){
			return Result.error("原始密码错误");
		}
		pw2 = new Sha256Hash(pw2, salt, 1024).toBase64();;
		user.setPassword(pw2);
		dao.update(user,"password");
		return Result.success("修改成功!!!");
	}
}

js中有ajax控制,代码如下

$.ajaxSetup({ 
		contentType : "application/x-www-form-urlencoded;charset=utf-8", 
		complete : function(XMLHttpRequest, textStatus) { 
		var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus"); // 通过XMLHttpRequest取得响应头,sessionstatus, 
		if (sessionstatus == "timeout") { 
		// 如果超时就处理 ,指定要跳转的页面 
				window.location.replace("/trademanage/index.action");
				//window.location.replace("/trademanage/index.jsp");
		  } 
		} 
	}); 
添加回复
请先登陆
回到顶部