/** * Override to handle interception * * @param invocation * @return * @throws Exception */ public String intercept(ActionInvocation invocation) throws Exception { String _logger_method = "intercept"; if (log.isTraceEnabled()) { log.trace("> " + _logger_method); } String result; try { String nextPage = checkAccess(invocation); if (nextPage == null) { Logger invocationLog = null; if (log.isDebugEnabled()) { invocationLog = Logger.getLogger(invocation.getAction().getClass()); invocationLog.debug("> " + invocation.getProxy().getMethod()); } result = invocation.invoke(); if (log.isDebugEnabled()) { invocationLog.debug("< " + invocation.getProxy().getMethod()); } } else { result = NavConsts.POPUP_TIME_OUT; } } catch (Exception e) { String excID = Long.toString(System.currentTimeMillis()); BaseAction baseAction = (BaseAction) invocation.getAction(); baseAction.addFieldError("errorID", "Error ID: " + excID); publishException(invocation, new ExceptionHolder(e)); return NavConsts.POPUP_GLOBAL_ERROR; } if (log.isTraceEnabled()) { log.trace("< " + _logger_method); } return result; }
private void setToGoingURL( HttpServletRequest request, HttpSession session, ActionInvocation invocation) { // 如果referer不为空 直接使用它。如果为空我们分别获得命名空间,action名,以及请求参数 // 从新构造成一个URL保存在session中 String url = request.getHeader("referer"); // log.info("待转向URL:"+request.getHeader("referer")); if (url == null || url.equals("")) { url = ""; String path = request.getContextPath(); String actionName = invocation.getProxy().getActionName(); String nameSpace = invocation.getProxy().getNamespace(); if (!nameSpace.equals(null)) { url = url + path + nameSpace; } if (!actionName.equals(null)) { url = url + "/" + actionName + ".action" + "?"; } Map<String, String[]> zzMap = request.getParameterMap(); if (zzMap != null) { for (String s : zzMap.keySet()) { String[] value = zzMap.get(s); for (String val : value) { url = url + s + "=" + val + "&"; } } } // log.info("完整URL:"+url); } session.setAttribute("GOING_TO", url); }
@Override public String intercept(ActionInvocation ai) throws Exception { if (checkLegal(ai, ai.getProxy().getActionName())) { if (checkNeedUpdatePsw(ai, ai.getProxy().getActionName())) { return "login"; } return ai.invoke(); } return "login"; }
public static String dealWithResult(String finalLocation, ActionInvocation invocation) { String namespace = invocation.getProxy().getNamespace(); String action = invocation.getProxy().getActionName(); String method = invocation.getProxy().getMethod(); if (finalLocation.contains("_namespace_")) { finalLocation = finalLocation.replace("_namespace_", namespace); } if (finalLocation.contains("_action_")) { finalLocation = finalLocation.replace("_action_", action); } return finalLocation; }
@Override public String intercept(ActionInvocation invocation) throws Exception { Set<String> set = TextParseUtil.commaDelimitedStringToSet(exclude); System.out.println(invocation.getProxy().getActionName()); if (set.contains(invocation.getProxy().getActionName())) { return invocation.invoke(); } else { Map<String, Object> session = invocation.getInvocationContext().getContext().getSession(); if (session.get(loginUser) != null) { return invocation.invoke(); } } return "loginfail"; }
private void setGoingToURL(Map<String, Object> session, ActionInvocation invocation) { String url = ""; String namespace = invocation.getProxy().getNamespace(); if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")) { url += namespace; } String actionName = invocation.getProxy().getActionName(); if (StringUtils.isNotBlank(actionName)) { url += "/" + actionName + ".action"; } session.put(GOING_TO_URL_KEY, url); }
@SuppressWarnings("unused") @Override public String intercept(ActionInvocation actionInvocation) throws Exception { String methodName = actionInvocation.getProxy().getMethod(); Method currentMethod = actionInvocation.getAction().getClass().getMethod(methodName, null); // 1、判断客户是否登陆 // 从session获取当前客户信息 Employee employee = (Employee) ServletActionContext.getRequest().getSession().getAttribute("employee"); if (employee == null) { System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println("客户还没登陆或登陆已超时!!!"); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); return "index"; } // 2、进行权限控制判断 // 如果该请求方法是需要进行验证的则需执行以下逻辑 if (currentMethod.isAnnotationPresent(Auth.class)) { // 获取权限校验的注解 Auth authority = currentMethod.getAnnotation(Auth.class); // 获取当前请求的注解的actionName String actionName = authority.actionName(); // 获取当前请求需要的权限 String privilege = authority.privilege(); // 可以在此判断当前客户是否拥有对应的权限,如果没有可以跳到指定的无权限提示页面,如果拥有则可以继续往下执行。 // if(拥有对应的权限){ // return actionInvocation.invoke(); // }else{ // return "无权限"; // } System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println( "客户" + employee.getUserName() + "在" + new Date() + "执行了" + actionName + "方法,拥有" + privilege + "权限!!"); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(); return actionInvocation.invoke(); } // 3、进行非权限控制判断 System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println("我执行了没有??"); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return "index"; }
@Override public String intercept(ActionInvocation invocation) throws Exception { String methodName = invocation.getProxy().getMethod(); Class clazz = invocation.getAction().getClass(); // 获取类对象 Method currentMethod = clazz.getMethod(methodName); // 获取拦截的方法 // 方法上添加了注解 if (currentMethod.isAnnotationPresent(Authority.class)) { // 取得当前请求的注解的action ActionContext context = invocation.getInvocationContext(); Map session = context.getSession(); // Constants.UserName=="UserName" String user = (String) session.get(Constants.UserName); // System.err.println("拦截器起作用"); if (user == null) // 未登陆,跳转到登录页 { // System.err.println("进入拦截器:未登陆"); context.put("tip", "你还没有登录"); return Action.LOGIN; } else { // 已登录,继续后续流程 // System.err.println("进入拦截器:已登录"); return invocation.invoke(); } } else { // System.err.println("进入拦截器:没有使用注解"); return invocation.invoke(); } }
@Override public String intercept(ActionInvocation invocation) throws Exception { String result; try { result = invocation.invoke(); } catch (Exception e) { if (isLogEnabled()) { handleLogging(e); } List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings(); ExceptionMappingConfig mappingConfig = this.findMappingFromExceptions(exceptionMappings, e); if (mappingConfig != null && mappingConfig.getResult() != null) { Map parameterMap = mappingConfig.getParams(); // create a mutable HashMap since some interceptors will remove parameters, and parameterMap // is immutable invocation.getInvocationContext().setParameters(new HashMap<String, Object>(parameterMap)); result = mappingConfig.getResult(); publishException(invocation, new ExceptionHolder(e)); } else { throw e; } } return result; }
public void testIncludeParameterInResult() throws Exception { ResultConfig resultConfig = new ResultConfig.Builder("", "") .addParam("actionName", "someActionName") .addParam("namespace", "someNamespace") .addParam("encode", "true") .addParam("parse", "true") .addParam("location", "someLocation") .addParam("prependServletContext", "true") .addParam("method", "someMethod") .addParam("param1", "value 1") .addParam("param2", "value 2") .addParam("param3", "value 3") .addParam("anchor", "fragment") .build(); ActionContext context = ActionContext.getContext(); MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); context.put(ServletActionContext.HTTP_REQUEST, req); context.put(ServletActionContext.HTTP_RESPONSE, res); Map<String, ResultConfig> results = new HashMap<String, ResultConfig>(); results.put("myResult", resultConfig); ActionConfig actionConfig = new ActionConfig.Builder("", "", "").addResultConfigs(results).build(); ServletActionRedirectResult result = new ServletActionRedirectResult(); result.setActionName("myAction"); result.setNamespace("/myNamespace"); result.setParse(false); result.setEncode(false); result.setPrependServletContext(false); result.setAnchor("fragment"); result.setUrlHelper(new DefaultUrlHelper()); IMocksControl control = createControl(); ActionProxy mockActionProxy = control.createMock(ActionProxy.class); ActionInvocation mockInvocation = control.createMock(ActionInvocation.class); expect(mockInvocation.getProxy()).andReturn(mockActionProxy); expect(mockInvocation.getResultCode()).andReturn("myResult"); expect(mockActionProxy.getConfig()).andReturn(actionConfig); expect(mockInvocation.getInvocationContext()).andReturn(context); control.replay(); result.setActionMapper(container.getInstance(ActionMapper.class)); result.execute(mockInvocation); assertEquals( "/myNamespace/myAction.action?param1=value+1¶m2=value+2¶m3=value+3#fragment", res.getRedirectedUrl()); control.verify(); }
/** * (non-Javadoc) * * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony * .xwork2.ActionInvocation) */ public String intercept(ActionInvocation actionInvocation) throws Exception { LOGGER.info("intercept by AuthenticationInterceptor"); Map<String, Object> session = actionInvocation.getInvocationContext().getSession(); // 用户是否登陆 if (session.get(Constants.USER_NAME) == null) { return Action.LOGIN; } else { // 拦截非法权限 String nameSpace = actionInvocation.getProxy().getNamespace(); String actionName = actionInvocation.getProxy().getActionName(); // 存在nameSpace分别为('/','/test'),action name相同的情况 String findKey = Constants.POWER_REQUEST; if (!"/".equals(nameSpace)) { // 不是根目录时,可以目录名做为Key键 } // 从config.privilege.xml中获取action对应的访问权限信息 String visitPower = Config.params.getString(findKey + actionName); // 访问的action在配置信息中不存在则返回Action.LOGIN if (visitPower == null || "".equals(visitPower)) { LOGGER.info("config.privilege.xml 中不存在 " + actionName + " 配置"); return Action.LOGIN; } String[] parm = visitPower.split(Constants.POWER_SPLIT); boolean isPrive = true; if (Constants.RES_TYPE_USER.equals(session.get(Constants.RES_TYPE))) { // 登录后保存了用户的方向权限改从缓存中获取 isPrive = sysUserService.checkPrivilegeByUidAndResCodeAndFunc( (Integer) session.get(Constants.UID), parm[0], parm[1]); } else { isPrive = sysRoleService.checkPrivilegeByRidAndResCodeAndFunc( (Integer) session.get(Constants.RID), parm[0], parm[1]); } if (isPrive) { return actionInvocation.invoke(); } else { LOGGER.info("action: " + actionName + " 存在,但无权访问,跳转到Action.LOGIN"); return Action.LOGIN; } } }
public String intercept(ActionInvocation invocation) throws Exception { // 获取本次操作 // System.out.println(invocation.getAction()); // System.out.println(invocation.getProxy().getAction()); // System.out.println(invocation.getProxy().getActionName()); // System.out.println(invocation.getProxy().getMethod()); String className = invocation.getProxy().getAction().getClass().getName(); String methodName = invocation.getProxy().getMethod(); String allName = className + "." + methodName; // 获取本次操作,判断是不是EmpAction类中的login方法 // "cn.itcast.erp.auth.emp.web.EmpAction.login" // 0.如果是登陆操作,放行 String operName = invocation.getProxy().getActionName(); // page_login // 放行登陆页操作 if ("page_login".equals(operName)) { // 跳转到登陆页面,放行 return invocation.invoke(); } if ("cn.itcast.erp.auth.emp.web.EmpAction.login".equals(allName)) { return invocation.invoke(); } // 1.获取登陆人信息 EmpModel loginEm = (EmpModel) ActionContext.getContext().getSession().get(EmpModel.LOGIN_EMP_INFO); // 2.判断是否登陆,如果没有登陆,返回登陆页面 if (loginEm == null) { // 返回登陆页面 return "noLogin"; } // 如果登陆,放行 return invocation.invoke(); }
/** 每次访问Action类之前,先执行intercept方法 */ @Override public String intercept(ActionInvocation invocation) throws Exception { // 获取当前访问Action的URL String actionName = invocation.getProxy().getActionName(); // 如果当前访问Action的URL是"loginAction_login"表示此时还没有Sesion,需要放行 if (!"loginAction_login".equals(actionName)) { // 从Session中获取当前用户对象 Employee employee = SessionContext.get(); // 如果Session不存在,跳转到登录页面 if (employee == null) { return "login"; } } // 放行,访问Action类中方法 return invocation.invoke(); }
/** * This method will prefix <code>actionInvocation</code>'s <code>ActionProxy</code>'s <code>method * </code> with <code>prefixes</code> before invoking the prefixed method. Order of the <code> * prefixes</code> is important, as this method will return once a prefixed method is found in the * action class. * * <p>For example, with * * <pre> * invokePrefixMethod(actionInvocation, new String[] { "prepare", "prepareDo" }); * </pre> * * Assuming <code>actionInvocation.getProxy(),getMethod()</code> returns "submit", the order of * invocation would be as follows:- * * <ol> * <li>prepareSubmit() * <li>prepareDoSubmit() * </ol> * * If <code>prepareSubmit()</code> exists, it will be invoked and this method will return, <code> * prepareDoSubmit()</code> will NOT be invoked. * * <p>On the other hand, if <code>prepareDoSubmit()</code> does not exists, and <code> * prepareDoSubmit()</code> exists, it will be invoked. * * <p>If none of those two methods exists, nothing will be invoked. * * @param actionInvocation the action invocation * @param prefixes prefixes for method names * @throws InvocationTargetException is thrown if invocation of a method failed. * @throws IllegalAccessException is thrown if invocation of a method failed. */ public static void invokePrefixMethod(ActionInvocation actionInvocation, String[] prefixes) throws InvocationTargetException, IllegalAccessException { Object action = actionInvocation.getAction(); String methodName = actionInvocation.getProxy().getMethod(); if (methodName == null) { // if null returns (possible according to the docs), use the default execute methodName = DEFAULT_INVOCATION_METHODNAME; } Method method = getPrefixedMethod(prefixes, methodName, action); if (method != null) { method.invoke(action, new Object[0]); } }
@Override public String intercept(ActionInvocation actionInvocation) throws Exception { ActionConfig actionConfig = actionInvocation.getProxy().getConfig(); final Map<String, String> staticParams = actionConfig.getParams(); if (staticParams != null) { // --------------------------------------------------------------------- // Push the specified static parameters onto the value stack // --------------------------------------------------------------------- Map<String, Object> matches = new HashMap<>(); for (Map.Entry<String, String> entry : staticParams.entrySet()) { if (standardParams.contains(entry.getKey())) { matches.put(entry.getKey(), entry.getValue()); } else if (commaSeparatedParams.contains(entry.getKey())) { String[] values = entry.getValue().split(","); for (int i = 0; i < values.length; i++) { values[i] = values[i].trim(); } matches.put(entry.getKey(), values); } } actionInvocation.getStack().push(matches); } // TODO: move this to its own systemInfoInterceptor? Map<String, Object> systemInfo = new HashMap<>(); String revision = systemService.getSystemInfo().getRevision(); if (StringUtils.isEmpty(revision)) { revision = "__dev__"; } systemInfo.put("buildRevision", revision); actionInvocation.getStack().push(systemInfo); return actionInvocation.invoke(); }
@Override protected void setUp() throws Exception { super.setUp(); annotationActionValidatorManager = (AnnotationActionValidatorManager) container.getInstance(ActionValidatorManager.class); ActionConfig config = new ActionConfig.Builder("packageName", "name", "").build(); ActionInvocation invocation = EasyMock.createNiceMock(ActionInvocation.class); ActionProxy proxy = EasyMock.createNiceMock(ActionProxy.class); EasyMock.expect(invocation.getProxy()).andReturn(proxy).anyTimes(); EasyMock.expect(invocation.getAction()).andReturn(null).anyTimes(); EasyMock.expect(invocation.invoke()).andReturn(Action.SUCCESS).anyTimes(); EasyMock.expect(proxy.getMethod()).andReturn("execute").anyTimes(); EasyMock.expect(proxy.getConfig()).andReturn(config).anyTimes(); EasyMock.replay(invocation); EasyMock.replay(proxy); ActionContext.getContext().setActionInvocation(invocation); }
public String intercept(ActionInvocation invocation) throws Exception { RailwayNetworkManager user = (RailwayNetworkManager) invocation.getInvocationContext().getSession().get(USER_OBJECT); Object action = invocation.getAction(); boolean annotated = action.getClass().isAnnotationPresent(MandatoryAuthentication.class); if (user == null && (annotated || mandatoryAuthentication(invocation.getProxy().getNamespace()))) { if (action instanceof ValidationAware) { String msg = action instanceof TextProvider ? ((TextProvider) action).getText(ERROR_MSG_KEY) : DEFAULT_MSG; ((ValidationAware) action).addActionError(msg); } return LOGIN_RESULT; } else { } return invocation.invoke(); }
public static String buildNamespace( ActionMapper mapper, ValueStack stack, HttpServletRequest request) { ActionContext context = new ActionContext(stack.getContext()); ActionInvocation invocation = context.getActionInvocation(); if (invocation == null) { ActionMapping mapping = mapper.getMapping(request, Dispatcher.getInstance().getConfigurationManager()); if (mapping != null) { return mapping.getNamespace(); } else { // well, if the ActionMapper can't tell us, and there is no existing action invocation, // let's just go with a default guess that the namespace is the last the path minus the // last part (/foo/bar/baz.xyz -> /foo/bar) String path = RequestUtils.getServletPath(request); return path.substring(0, path.lastIndexOf("/")); } } else { return invocation.getProxy().getNamespace(); } }
public String intercept(ActionInvocation invocation) throws Exception { ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); if (!(request instanceof MultiPartRequestWrapper)) { if (LOG.isDebugEnabled()) { ActionProxy proxy = invocation.getProxy(); LOG.debug( getTextMessage( "struts.messages.bypass.request", new String[] {proxy.getNamespace(), proxy.getActionName()})); } return invocation.invoke(); } ValidationAware validation = null; Object action = invocation.getAction(); if (action instanceof ValidationAware) { validation = (ValidationAware) action; } MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request; if (multiWrapper.hasErrors()) { for (String error : multiWrapper.getErrors()) { if (validation != null) { validation.addActionError(error); } if (LOG.isWarnEnabled()) { LOG.warn(error); } } } // bind allowed Files Enumeration fileParameterNames = multiWrapper.getFileParameterNames(); while (fileParameterNames != null && fileParameterNames.hasMoreElements()) { // get the value of this input tag String inputName = (String) fileParameterNames.nextElement(); // get the content type String[] contentType = multiWrapper.getContentTypes(inputName); if (isNonEmpty(contentType)) { // get the name of the file from the input tag String[] fileName = multiWrapper.getFileNames(inputName); if (isNonEmpty(fileName)) { // get a File object for the uploaded File File[] files = multiWrapper.getFiles(inputName); if (files != null && files.length > 0) { List<File> acceptedFiles = new ArrayList<File>(files.length); List<String> acceptedContentTypes = new ArrayList<String>(files.length); List<String> acceptedFileNames = new ArrayList<String>(files.length); String contentTypeName = inputName + "ContentType"; String fileNameName = inputName + "FileName"; for (int index = 0; index < files.length; index++) { if (acceptFile( action, files[index], fileName[index], contentType[index], inputName, validation)) { acceptedFiles.add(files[index]); acceptedContentTypes.add(contentType[index]); acceptedFileNames.add(fileName[index]); } } if (!acceptedFiles.isEmpty()) { Map<String, Object> params = ac.getParameters(); params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()])); params.put( contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()])); params.put( fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()])); } } } else { if (LOG.isWarnEnabled()) { LOG.warn( getTextMessage(action, "struts.messages.invalid.file", new String[] {inputName})); } } } else { if (LOG.isWarnEnabled()) { LOG.warn( getTextMessage( action, "struts.messages.invalid.content.type", new String[] {inputName})); } } } // invoke action return invocation.invoke(); }
@Override public String intercept(ActionInvocation invocation) throws Exception { ActionConfig config = invocation.getProxy().getConfig(); ActionContext ac = invocation.getInvocationContext(); Object action = invocation.getAction(); // get the action's parameters final Map<String, String> parameters = config.getParams(); if (parameters.containsKey(aliasesKey)) { String aliasExpression = parameters.get(aliasesKey); ValueStack stack = ac.getValueStack(); Object obj = stack.findValue(aliasExpression); if (obj != null && obj instanceof Map) { // get secure stack ValueStack newStack = valueStackFactory.createValueStack(stack); boolean clearableStack = newStack instanceof ClearableValueStack; if (clearableStack) { // if the stack's context can be cleared, do that to prevent OGNL // from having access to objects in the stack, see XW-641 ((ClearableValueStack) newStack).clearContextValues(); Map<String, Object> context = newStack.getContext(); ReflectionContextState.setCreatingNullObjects(context, true); ReflectionContextState.setDenyMethodExecution(context, true); ReflectionContextState.setReportingConversionErrors(context, true); // keep locale from original context context.put(ActionContext.LOCALE, stack.getContext().get(ActionContext.LOCALE)); } // override Map aliases = (Map) obj; for (Object o : aliases.entrySet()) { Map.Entry entry = (Map.Entry) o; String name = entry.getKey().toString(); String alias = (String) entry.getValue(); Object value = stack.findValue(name); if (null == value) { // workaround Map<String, Object> contextParameters = ActionContext.getContext().getParameters(); if (null != contextParameters) { value = contextParameters.get(name); } } if (null != value) { try { newStack.setValue(alias, value); } catch (RuntimeException e) { if (devMode) { String developerNotification = LocalizedTextUtil.findText( ParametersInterceptor.class, "devmode.notification", ActionContext.getContext().getLocale(), "Developer Notification:\n{0}", new Object[] { "Unexpected Exception caught setting '" + entry.getKey() + "' on '" + action.getClass() + ": " + e.getMessage() }); LOG.error(developerNotification); if (action instanceof ValidationAware) { ((ValidationAware) action).addActionMessage(developerNotification); } } } } } if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null)) stack .getContext() .put( ActionContext.CONVERSION_ERRORS, newStack.getContext().get(ActionContext.CONVERSION_ERRORS)); } else { LOG.debug("invalid alias expression:" + aliasesKey); } } return invocation.invoke(); }