org.apache.struts2.StrutsStatics Java Examples

The following examples show how to use org.apache.struts2.StrutsStatics. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigInterceptor.java    From S-mall-ssh with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {

    HttpServletRequest request = (HttpServletRequest) actionInvocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
    Object action = actionInvocation.getAction();
    Map<String,String> config = configService.map();
    //配置首页SEO参数
    if(action.getClass().getSimpleName().equals("ShowAction")&&actionInvocation.getProxy().getMethod().equals("home")){
        String indexTitle = config.get("index_title");
        String indexKeyword = config.get("index_keyword");
        String indexDescription = config.get("index_description");
        request.setAttribute("SEOTitle",indexTitle);
        request.setAttribute("keywords",indexKeyword);
        request.setAttribute("description",indexDescription);
    }
    request.setAttribute("website_name",config.get("website_name"));
    request.setAttribute("productImgDir",config.get("path_product_img"));
    request.setAttribute("categoryImgDir",config.get("path_category_img"));
    return  actionInvocation.invoke();

}
 
Example #2
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext=actionInvocation.getInvocationContext();  
	Map<String, Object> session=actionContext.getSession();  
	this.accountObj = (AccountObj)session.get(Constants.SESS_ACCOUNT);
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String currentId = StringUtils.defaultString( dataMap.get("currentId") );
	String accountId = StringUtils.defaultString( dataMap.get("account") );
	if (accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) ) {
		if ( StringUtils.isBlank(currentId) ) {
			currentId = "NULL";
		}
		String sessSysCurrentId = (String)session.get(Constants.SESS_SYSCURRENT_ID);
		if ( !currentId.equals(sessSysCurrentId) ) {
			logger.warn( "currentId: " + currentId + " not equals session variable currentId: " + sessSysCurrentId );
			return this.redirectLogin(actionInvocation, session, currentId, accountId);
		}
		if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId)<1) {
			return this.redirectLogin(actionInvocation, session, currentId, accountId);
		}						
		return actionInvocation.invoke();
	} 
	return this.redirectLogin(actionInvocation, session, currentId, accountId);
}
 
Example #3
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 1. 先用admin登入
 * 2. 登出admin 改用 tester登入
 * 這樣的話 gsbsc-web 的 http-session 還是admin , 所以非core-web用tester登入的session , 要檢查當前CURRENT cookie 中的帳戶是否與 gsbsc-web 一樣
 * 要是不同的話就讓這個 http-session 失效掉
 *  
 * @param actionContext
 * @throws Exception
 */
private void invalidCurrentSessionForDifferentAccount(ActionContext actionContext) throws Exception {
	if (this.accountObj == null) {
		return;
	}
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String account = StringUtils.defaultString( dataMap.get("account") );
	if (StringUtils.isBlank(account)) {
		return;
	}
	if (this.accountObj.getAccount().equals(account)) {
		return;
	}
	this.accountObj = null;		
	UserAccountHttpSessionSupport.remove(actionContext.getSession());
	Subject subject = SecurityUtils.getSubject();		
	if (subject.isAuthenticated() && !account.equals(subject.getPrincipal()) ) {
		subject.logout();
	}
}
 
Example #4
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 取出core-web 登入後產生的cookie, 這個cookie放了 account 與 current-id
 * 拿這兩個去 TB_SYS_USESS 查看有沒有在core-web有登入過
 * 如果有在core-web登入, 產生 AccountVO 與回傳 true
 * 
 * @param actionContext
 * @return
 * @throws Exception
 */
private boolean getUserCurrentCookie(ActionContext actionContext) throws Exception {
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String account = StringUtils.defaultString( dataMap.get("account") );
	String currentId = StringUtils.defaultString( dataMap.get("currentId") );
	//String sessionId = StringUtils.defaultString( dataMap.get("sessionId") );
	if (StringUtils.isBlank(account) || currentId.length()!=36 /*|| StringUtils.isBlank(sessionId)*/ ) { 	
		return false;
	}
	// 發現有時 UserCurrentCookie 寫入的 sessionId 與當前 sessionId 會不一樣
	if (this.uSessLogHelper.countByCurrent(account, currentId) >0 ) { // this.uSessLogHelper.countByCurrent(account, currentId, sessionId) >0 		 	
		accountObj = new AccountVO();
		((AccountVO)accountObj).setAccount(account);
		DefaultResult<AccountVO> result = this.accountService.findByUK( ((AccountVO)accountObj) );
		if (result.getValue()==null) {
			accountObj = null;
		} else {
			accountObj = result.getValue();
		}			
	}					
	return ( accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) );
}
 
Example #5
Source File: UserLoginInterceptor_20141120_bak.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 1. 先用admin登入
 * 2. 登出admin 改用 tester登入
 * 這樣的話 gsbsc-web 的 http-session 還是admin , 所以非core-web用tester登入的session , 要檢查當前CURRENT cookie 中的帳戶是否與 gsbsc-web 一樣
 * 要是不同的話就讓這個 http-session 失效掉
 *  
 * @param actionContext
 * @throws Exception
 */
private void invalidCurrentSessionForDifferentAccount(ActionContext actionContext) throws Exception {
	if (this.accountObj == null) {
		return;
	}
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String account = StringUtils.defaultString( dataMap.get("account") );
	if (StringUtils.isBlank(account)) {
		return;
	}
	if (this.accountObj.getAccount().equals(account)) {
		return;
	}
	this.accountObj = null;		
	UserAccountHttpSessionSupport.remove(actionContext.getSession());
	SecurityUtils.getSubject().logout();
}
 
Example #6
Source File: UserLoginInterceptor_20141120_bak.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 取出core-web 登入後產生的cookie, 這個cookie放了 account 與 current-id
 * 拿這兩個去 TB_SYS_USESS 查看有沒有在core-web有登入過
 * 如果有在core-web登入, 產生 AccountVO 與回傳 true
 * 
 * @param actionContext
 * @return
 * @throws Exception
 */
private boolean getUserCurrentCookie(ActionContext actionContext) throws Exception {
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String account = StringUtils.defaultString( dataMap.get("account") );
	String currentId = StringUtils.defaultString( dataMap.get("currentId") );
	//String sessionId = StringUtils.defaultString( dataMap.get("sessionId") );
	if (StringUtils.isBlank(account) || currentId.length()!=36 /*|| StringUtils.isBlank(sessionId)*/ ) { 	
		return false;
	}
	// 發現有時 UserCurrentCookie 寫入的 sessionId 與當前 sessionId 會不一樣
	if (this.uSessLogHelper.countByCurrent(account, currentId) >0 ) { // this.uSessLogHelper.countByCurrent(account, currentId, sessionId) >0 		 	
		accountObj = new AccountVO();
		((AccountVO)accountObj).setAccount(account);
		DefaultResult<AccountVO> result = this.accountService.findByUK( ((AccountVO)accountObj) );
		if (result.getValue()==null) {
			accountObj = null;
		} else {
			accountObj = result.getValue();
		}			
	}					
	return ( accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) );
}
 
Example #7
Source File: CategoryNamesBelowSearchInterceptor.java    From S-mall-ssh with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
    ServletContext servletContext= (ServletContext) actionInvocation.getInvocationContext().get(StrutsStatics.SERVLET_CONTEXT);
    Long oldTime = (Long)servletContext.getAttribute("csTimeOut");
    if(oldTime == null || System.currentTimeMillis()>oldTime) {
        servletContext.setAttribute("cs", categoryService.list("desc", "recommend", "max", 7));
        //1分钟内,全站用户只统一获取一次
        servletContext.setAttribute("csTimeOut", System.currentTimeMillis() + 60 * 1000);
    }
    return  actionInvocation.invoke();
}
 
Example #8
Source File: PlainTextErrorResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void execute( ActionInvocation invocation )
    throws Exception
{
    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(
        StrutsStatics.HTTP_RESPONSE );

    response.setContentType( "text/plain; charset=UTF-8" );
    response.setHeader( "Content-Disposition", "inline" );
    response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );

    ValueStack stack = ActionContext.getContext().getValueStack();
    String finalMessage = parse ? TextParseUtil.translateVariables( message, stack ) : message;

    finalMessage = formatFinalMessage( finalMessage );

    // ---------------------------------------------------------------------
    // Write final message
    // ---------------------------------------------------------------------

    PrintWriter writer = null;

    try
    {
        writer = response.getWriter();
        writer.print( finalMessage );
        writer.flush();
    }
    finally
    {
        if ( writer != null )
        {
            writer.close();
        }
    }
}
 
Example #9
Source File: JsonOutermostBracketsInterceptor.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext context=actionInvocation.getInvocationContext();
	HttpServletResponse response=(HttpServletResponse)context.get(StrutsStatics.HTTP_RESPONSE);
	response.setCharacterEncoding("utf8");
	response.setContentType("text/html");
	PrintWriter writer=response.getWriter();
	writer.print("[");
	writer.flush();
	String forward=actionInvocation.invoke();
	writer.print("]");
	writer.flush();
	return forward;
}
 
Example #10
Source File: NoCacheHeaderInterceptor.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext context=actionInvocation.getInvocationContext();
	HttpServletResponse response=(HttpServletResponse)context.get(StrutsStatics.HTTP_RESPONSE);
	if (response!=null ) {
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "0");			
	}
	return actionInvocation.invoke();
}
 
Example #11
Source File: Struts2InterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    struts2Interceptor = new Struts2Interceptor();
    when(request.getRequestURI()).thenReturn("/test/testRequestURL");
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/test/testRequestURL"));
    when(response.getStatus()).thenReturn(200);

    mockStatic(ActionContext.class);
    actionContext = mock(ActionContext.class);
    when(actionContext.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE)).thenReturn(response);
    when(actionContext.get(StrutsStatics.HTTP_REQUEST)).thenReturn(request);
    when(ActionContext.getContext()).thenReturn(actionContext);

    arguments = new Object[] {
        request,
        response
    };
    argumentType = new Class[] {
        request.getClass(),
        response.getClass()
    };

    exceptionArguments = new Object[] {
        request,
        response,
        new RuntimeException()
    };
    exceptionArgumentType = new Class[] {
        request.getClass(),
        response.getClass(),
        new RuntimeException().getClass()
    };
}
 
Example #12
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext=actionInvocation.getInvocationContext();  
	Map<String, Object> session=actionContext.getSession();  
	this.accountObj = (AccountObj)session.get(Constants.SESS_ACCOUNT);
	boolean getUserCurrentCookieFail = false; // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
	/*
	 * String contextPath = ServletActionContext.getServletContext().getContextPath();
	 * if (!contextPath.endsWith( ApplicationSiteUtils.getContextPathFromMap(Constants.getMainSystem()) ) ) {
	 */
	if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) {
		/**
		 * 1. 先用admin登入
		 * 2. 登出admin 改用 tester登入
		 * 這樣的話 gsbsc-web 的 http-session 還是admin , 所以非core-web 要檢查當前CURRENT cookie 中的帳戶是否與 gsbsc-web 一樣
		 * 要是不同的話就讓這個 http-session 失效掉
		 */
		this.invalidCurrentSessionForDifferentAccount(actionContext);								
		if (accountObj==null) {
			getUserCurrentCookie(actionContext);
			if (accountObj==null && UserCurrentCookie.foundCurrent( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) ) ) {
				 // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
				getUserCurrentCookieFail = true;
			}				
		}			
	}
	if (accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) ) {
		Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
		String currentId = StringUtils.defaultString( dataMap.get("currentId") );
		if ( StringUtils.isBlank(currentId) ) {
			currentId = "NULL";
		}
		if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId)<1) {
			return this.redirectLogin(session, getUserCurrentCookieFail);
		}						
		boolean isUnknownSession = false;
		SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") );
		Subject subject = SecurityUtils.getSubject();
		try {
			if (subject.isAuthenticated() && !accountObj.getAccount().equals(subject.getPrincipal()) ) {
				subject.logout();
			}				
		} catch (ExpiredSessionException ese) {
			logger.warn( ese.getMessage().toString() );
			return this.redirectLogin(session, getUserCurrentCookieFail);
		} catch (UnknownSessionException ue) {
			logger.warn( ue.getMessage().toString() );
			isUnknownSession = true;
		}
		
		/**
		 * core-web 有 session了, 但gsbsc-web 沒有session, 所以產生gsbsc-web 的 http session
		 * 或是 apache shiro session 失效 expires
		 */			
		if ( !subject.isAuthenticated() || isUnknownSession ) {
			GreenStepBaseUsernamePasswordToken token = new GreenStepBaseUsernamePasswordToken();
			//token.setRememberMe(true);
			token.setRememberMe(false);
			token.setCaptcha("");
			token.setUsername(accountObj.getAccount());		
			token.setPassword( ((AccountVO)accountObj).getPassword().toCharArray() );
			try {					
				subject.login(token);
			} catch (UnknownAccountException uae) {
				logger.warn( uae.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();	
			    subject.login(token);
			} catch (UnknownSessionException use) {
				logger.warn( use.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();					
				/*
				Serializable sessionId = subject.getSession().getId();
				System.out.println("SESSION_ID=" + sessionId);
				subject = new Subject.Builder( (DefaultSecurityManager)AppContext.getBean("securityManager") )
					.sessionId(sessionId)
					.buildSubject();
				*/
			    subject.login(token);		
			} 
			UserAccountHttpSessionSupport.create(actionContext, accountObj);
		}
		return actionInvocation.invoke();
	}	
	return this.redirectLogin(session, getUserCurrentCookieFail);
}
 
Example #13
Source File: SyslogInterceptor.java    From hrms with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	Syslog syslog = new Syslog();
	ActionContext actionContext = actionInvocation.getInvocationContext();
	HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
	String accessIp = getIpAddr(request);
	syslog.setAccessIp(accessIp);
	StringBuffer url = request.getRequestURL();
	
	int slash = url.lastIndexOf("/");
	String linkUrl = url.substring(slash+1);
	int point = linkUrl.lastIndexOf(".");
	if (point>0) {
		linkUrl = linkUrl.substring(0,point);
	}
	int bottomLine = linkUrl.lastIndexOf("_");
	String result;
	String userId;
	String actionId = "1";
	String actionStr = linkUrl.substring(linkUrl.lastIndexOf("_")+1);
	if(actionStr.equals("add")) {
		actionId = "2";
	} else if (actionStr.equals("update")) {
		actionId = "3";
	}else if (actionStr.equals("delete")) {
		actionId = "4";
	}
	
	if(linkUrl.equals("user_login")) {
		syslog.setAction("登入");
		result = actionInvocation.invoke();
		userId = actionContext.getSession().get("userId").toString();
	}else {
		userId = actionContext.getSession().get("userId").toString();
		if(linkUrl.equals("user_loginOut")) {
			syslog.setAction("退出");
		}else {
			if (actionId != null && actionId.trim() != "") {
				Action action = (Action) actionService.findById(Integer.valueOf(actionId));
				if (action!=null) {
					syslog.setAction(action.getAction());
				}
			}
		}
		result = actionInvocation.invoke();
	}
	if (bottomLine>0) {
		linkUrl = linkUrl.substring(0,bottomLine);
	}
	if (userId != null && actionId != null && !actionId.equals("1")) {
		syslog.setDate(new Date());
		Module module = moduleService.getModuleByLinkUrl(linkUrl);
		syslog.setModule(module);
		if (result.equals("error")) {
			syslog.setType("错误");
		} else if((result.equals("input"))){
			syslog.setType("警告");
		} else {
			syslog.setType("信息");
		}
		syslog.setUser(userService.findById(Integer.valueOf(userId)));
		if (result.equals("success") || result.equals("error") || result.equals("input")) {
			syslogService.save(syslog);
		}
		return result;
	}
	return "login";
}
 
Example #14
Source File: PermissionInterceptor.java    From hrms with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext = actionInvocation.getInvocationContext();
	HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
	String userId = actionContext.getSession().get("userId").toString();
	String contextPath = request.getContextPath();
	StringBuffer url = request.getRequestURL();
	int contextPathPost = url.lastIndexOf(contextPath);
	int contextPathLength = contextPath.length();
	String linkUrl = url.substring(contextPathPost + contextPathLength + 1);
	String actionId = "";
	int bottomLine = linkUrl.lastIndexOf("_");
	String action = linkUrl.substring(bottomLine+1);
	if(bottomLine < 0 || action.equals("my")) {
		actionId = "1";
	} else if(action.equals("add")) {
		actionId = "2";
	} else if (action.equals("update")) {
		actionId = "3";
	}else if (action.equals("delete")) {
		actionId = "4";
	} else if (action.equals("approverList") || action.equals("transactorList")) {
		actionId = "5";
	} else {
		actionId = "6";
	}
	if (bottomLine>0) {
		linkUrl = linkUrl.substring(0,bottomLine);
	}
	Module module = moduleService.getModuleByLinkUrl(linkUrl);
	if (userId != null && module!=null) {
		String moduleId = module.getModuleId().toString();
		if (userPermissionService.checkPermission(userId, moduleId,actionId)) {
			return actionInvocation.invoke();
		}
	}
	if (module==null) {
		return actionInvocation.invoke();
	}
	actionContext.put("permissionMessage", "你没有该权限,请先登陆");
	return Action.NONE;
}