org.springframework.web.context.support.WebApplicationContextUtils Java Examples

The following examples show how to use org.springframework.web.context.support.WebApplicationContextUtils. 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: DelegatingFilterProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the {@code WebApplicationContext} passed in at construction time, if available.
 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
 * the well-known "root" application context attribute. The
 * {@code WebApplicationContext} must have already been loaded and stored in the
 * {@code ServletContext} before this filter gets initialized (or invoked).
 * <p>Subclasses may override this method to provide a different
 * {@code WebApplicationContext} retrieval strategy.
 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
 * @see #DelegatingFilterProxy(String, WebApplicationContext)
 * @see #getContextAttribute()
 * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
 * @see WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
 */
protected WebApplicationContext findWebApplicationContext() {
	if (this.webApplicationContext != null) {
		// The user has injected a context at construction time -> use it...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
			ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.webApplicationContext;
			if (!cac.isActive()) {
				// The context has not yet been refreshed -> do so before returning it...
				cac.refresh();
			}
		}
		return this.webApplicationContext;
	}
	String attrName = getContextAttribute();
	if (attrName != null) {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
	}
	else {
		return WebApplicationContextUtils.findWebApplicationContext(getServletContext());
	}
}
 
Example #2
Source File: CalendarCollectionProvider.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * @param collectionItem
 * @return
 */
private Calendar getCalendarFromCollection(DavRequest req, CollectionItem collectionItem) {
    Calendar result = new Calendar();

    if (productId == null) {
        synchronized (this) {
            if (productId == null) {
                Environment environment = WebApplicationContextUtils
                        .findWebApplicationContext(req.getServletContext()).getEnvironment();
                productId = environment.getProperty(PRODUCT_ID_KEY);
            }
        }
    }

    result.getProperties().add(new ProdId(productId));
    result.getProperties().add(Version.VERSION_2_0);
    result.getProperties().add(CalScale.GREGORIAN);

    for (Item item : collectionItem.getChildren()) {
        if (!NoteItem.class.isInstance(item)) {
            continue;
        }
        for (Stamp s : item.getStamps()) {
            if (BaseEventStamp.class.isInstance(s)) {
                BaseEventStamp baseEventStamp = BaseEventStamp.class.cast(s);
                result.getComponents().add(baseEventStamp.getEvent());
            }
        }
    }
    return result;
}
 
Example #3
Source File: CORSContextListener.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Initializes CORS filter
 */
private void initCORS(ServletContext servletContext)
{
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    Properties gP = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES);
    Boolean corsEnabled = new Boolean(gP.getProperty(CORS_ENABLED));

    if(logger.isDebugEnabled())
    {
        logger.debug("CORS filter is" + (corsEnabled?" ":" not ") + "enabled");
    }
    if (corsEnabled)
    {
        FilterRegistration.Dynamic corsFilter = servletContext.addFilter("CorsFilter", "org.apache.catalina.filters.CorsFilter");
        corsFilter.setInitParameter(CORS_ALLOWED_ORIGINS, gP.getProperty(CORS_ALLOWED_ORIGINS));
        corsFilter.setInitParameter(CORS_ALLOWED_METHODS, gP.getProperty(CORS_ALLOWED_METHODS));
        corsFilter.setInitParameter(CORS_ALLOWED_HEADERS, gP.getProperty(CORS_ALLOWED_HEADERS));
        corsFilter.setInitParameter(CORS_EXPOSED_HEADERS, gP.getProperty(CORS_EXPOSED_HEADERS));
        corsFilter.setInitParameter(CORS_SUPPORT_CREDENTIALS, gP.getProperty(CORS_SUPPORT_CREDENTIALS));
        corsFilter.setInitParameter(CORS_PREFLIGHT_CREDENTIALS, gP.getProperty(CORS_PREFLIGHT_CREDENTIALS));
        corsFilter.addMappingForUrlPatterns(DISPATCHER_TYPE, false, "/*");
    }
}
 
Example #4
Source File: GeoWaveApiKeySetterFilter.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * This class is only responsible for setting two servlet context attributes: "userName" and
 * "apiKey"
 */
@Override
public void doFilter(
    final ServletRequest request,
    final ServletResponse response,
    final FilterChain chain) throws IOException, ServletException {

  try {
    final ServletContext servletContext = getServletContext();
    final ApplicationContext ac =
        WebApplicationContextUtils.getWebApplicationContext(servletContext);
    final GeoWaveBaseApiKeyDB apiKeyDB = (GeoWaveBaseApiKeyDB) ac.getBean("apiKeyDB");
    final String userAndKey = apiKeyDB.getCurrentUserAndKey();

    if (!userAndKey.equals("")) {
      final String[] userAndKeyToks = userAndKey.split(":");
      servletContext.setAttribute("userName", userAndKeyToks[0]);
      servletContext.setAttribute("apiKey", userAndKeyToks[1]);
    }
  } catch (final Exception e) {
    return;
  } finally {
    chain.doFilter(request, response);
  }
}
 
Example #5
Source File: ExecutorShutdownListener.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
   	try {
		ServletContext servletContext = servletContextEvent.getServletContext();
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		ExecutorService workerExecutorService = (ExecutorService) webApplicationContext.getBean("WorkerExecutorService");
		Thread.sleep(1000);
		logger.info("Shutting down WorkerExecutorService");
		int retryCount = 0;
		while (!workerExecutorService.isTerminated() && retryCount < 10) {
			if (retryCount > 0) {
				logger.error("WorkerExecutorService shutdown retryCount: " + retryCount);
				Thread.sleep(1000);
			}
			workerExecutorService.shutdownNow();
			retryCount++;
		}
   	} catch (Exception e) {
		logger.error("Cannot shutdown WorkerExecutorService: " + e.getMessage(), e);
	}
}
 
Example #6
Source File: DefaultMockMvcBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * See SPR-12553 and SPR-13075.
 */
@Test
public void rootWacServletContainerAttributePreviouslySet() {
	StubWebApplicationContext child = new StubWebApplicationContext(this.servletContext);
	this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child);

	DefaultMockMvcBuilder builder = webAppContextSetup(child);
	assertSame(builder.initWebAppContext(),
		WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
 
Example #7
Source File: ExportTestCase.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param httpServletRequest servlet request
 * @param httpServletResponse servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    try {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseService testService = appContext.getBean(ITestCaseService.class);

        PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
        String test = policy.sanitize(httpServletRequest.getParameter("test"));
        String testcase = policy.sanitize(httpServletRequest.getParameter("testcase"));

        TestCase tcInfo = testService.findTestCaseByKeyWithDependency(test, testcase);

        // Java object to JSON string
        ObjectMapper mapper = new ObjectMapper();
        JSONObject jo = new JSONObject(mapper.writeValueAsString(tcInfo));
        jo.put("bugs", tcInfo.getBugs());

        JSONObject export = new JSONObject();
        export.put("version", Infos.getInstance().getProjectVersion());
        export.put("user", httpServletRequest.getUserPrincipal());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        export.put("date", formatter.format(new Date()));
        export.put("testCase", jo);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + test + "-" + testcase + ".json");
        // Nice formating the json result by putting indent 4 parameter.
        httpServletResponse.getOutputStream().print(export.toString(4));

    } catch (CerberusException | JSONException ex) {
        LOG.warn(ex);
    }
}
 
Example #8
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    LOGGER.info("Destroying Web application");
    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
    AnnotationConfigWebApplicationContext gwac = (AnnotationConfigWebApplicationContext) ac;
    gwac.close();
    LOGGER.debug("Web application destroyed");
}
 
Example #9
Source File: PresenceWebsocketServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static ILessonService getLessonService() {
if (PresenceWebsocketServer.lessonService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils
	    .getWebApplicationContext(SessionManager.getServletContext());
    PresenceWebsocketServer.lessonService = (ILessonService) ctx.getBean("lessonService");
}
return PresenceWebsocketServer.lessonService;
   }
 
Example #10
Source File: GetParameter.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String echo = request.getParameter("sEcho");

    String mySystem = request.getParameter("system");
    LOG.debug("System : '" + mySystem + "'.");

    JSONArray data = new JSONArray(); //data that will be shown in the table

    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IParameterService parameterService = appContext.getBean(ParameterService.class);
    try {
        JSONObject jsonResponse = new JSONObject();
        try {
            for (Parameter myParameter : parameterService.findAllParameter()) {
                JSONArray row = new JSONArray();
                row.put(myParameter.getParam()).put(myParameter.getValue()).put(myParameter.getValue()).put(myParameter.getDescription());
                data.put(row);
            }
        } catch (CerberusException ex) {
            response.setContentType("text/html");
            response.getWriter().print(ex.getMessageError().getDescription());
        }
        jsonResponse.put("aaData", data);
        jsonResponse.put("sEcho", echo);
        jsonResponse.put("iTotalRecords", data.length());
        jsonResponse.put("iTotalDisplayRecords", data.length());
        response.setContentType("application/json");
        response.getWriter().print(jsonResponse.toString());
    } catch (JSONException e) {
        LOG.warn(e);
        response.setContentType("text/html");
        response.getWriter().print(e.getMessage());
    }
}
 
Example #11
Source File: AddToExecutionQueue.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init() throws ServletException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
    inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
    executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
    testCaseService = appContext.getBean(ITestCaseService.class);
    campaignParameterService = appContext.getBean(ICampaignParameterService.class);
}
 
Example #12
Source File: ViewScopeContainsAOPSessionScope.java    From JSF-on-Spring-Boot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
  private void init() {
  	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      ServletContext servletContext = (ServletContext) externalContext.getContext();
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).
                                 getAutowireCapableBeanFactory().
                                 autowireBean(this);
  }
 
Example #13
Source File: ServerListener.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    springContext = WebApplicationContextUtils
            .getWebApplicationContext(event.getServletContext());
    initService = springContext.getBean(InitService.class);
    initService.start();
}
 
Example #14
Source File: ViewScopeContainsRequestScope.java    From JSF-on-Spring-Boot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
  private void init() {
  	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      ServletContext servletContext = (ServletContext) externalContext.getContext();
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).
                                 getAutowireCapableBeanFactory().
                                 autowireBean(this);
  }
 
Example #15
Source File: ShiroConfigService.java    From layui-admin with MIT License 5 votes vote down vote up
/**
 * 更新权限,解决需要重启tomcat才能生效权限的问题
 */
public void updatePermission() {
    try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ServletContext servletContext = request.getSession().getServletContext();
        AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("myShiroFilter");

        synchronized (shiroFilter) {
            // 获取过滤管理器
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
            // 清空初始权限配置
            manager.getFilterChains().clear();
            // 重新获取资源
            Map<String, String> chains = loadFilterChainDefinitions();

            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");

                manager.createChain(url, chainDefinition);
            }
            log.info("更新权限成功!!");
        }
    } catch (Exception e) {
        log.error("更新权限到shiro异常", e);
    }
}
 
Example #16
Source File: ShowImageServlet.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Return existing cache or create new one
 */
public ImageCache getImageCache() {
	if (imageCache == null) {
		imageCache = WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean("ImageCache", ImageCache.class);
	}

	return imageCache;
}
 
Example #17
Source File: ViewScopeContainsAOPPrototypeScope.java    From JSF-on-Spring-Boot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
  private void init() {
  	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      ServletContext servletContext = (ServletContext) externalContext.getContext();
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).
                                 getAutowireCapableBeanFactory().
                                 autowireBean(this);
  }
 
Example #18
Source File: SpringBeanUtil.java    From phone with Apache License 2.0 5 votes vote down vote up
public static String[] getWebBeanNamesForType(HttpServletRequest request,Class<?> clazz){
	ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
	if(ac!=null){
		return ac.getBeanNamesForType(clazz);
	}
	return null;
}
 
Example #19
Source File: StoreApplicationContext.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init (ServletConfig config) throws ServletException {
  super.init(config);
  if (ctx == null){
    ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(config.getServletContext());
    SpringBeanLocator.setApplicationContext(ctx);

    ContextUtil.setServletContext(config.getServletContext());
  }
}
 
Example #20
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    LOGGER.info("Destroying Web application");
    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
    AnnotationConfigWebApplicationContext gwac = (AnnotationConfigWebApplicationContext) ac;
    gwac.close();
    LOGGER.debug("Web application destroyed");
}
 
Example #21
Source File: ComRdirUserForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private MailingContentTypeCache getMailingContentTypeCache() {
	if (mailingContentTypeCache == null) {
		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		mailingContentTypeCache = (MailingContentTypeCache) applicationContext.getBean("MailingContentTypeCache");
	}
	return mailingContentTypeCache;
}
 
Example #22
Source File: ExtensionsAdminController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * hmmm, does not work yet, how to get a list with all overwritten beans like the output from to the log.info
 * http://www.docjar.com/html/api/org/springframework/beans/factory/support/DefaultListableBeanFactory.java.html
 * 
 * @return
 */
private List getOverwrittenBeans() {
    final ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    final XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
    final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    final String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanDefinitionNames.length; i++) {
        final String beanName = beanDefinitionNames[i];
        if (!beanName.contains("#")) {
            final BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
            // System.out.println(beanDef.getOriginatingBeanDefinition());
        }
    }
    return null;
}
 
Example #23
Source File: UpdateMyUserRobotPreference.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);
    
    try {
                       
        String ss_ip = ParameterParserUtil.parseStringParam(request.getParameter("ss_ip"), "");
        String ss_p = ParameterParserUtil.parseStringParam(request.getParameter("ss_p"), "");
        String platform = ParameterParserUtil.parseStringParam(request.getParameter("platform"), "");
        String browser = ParameterParserUtil.parseStringParam(request.getParameter("browser"), "");
        String version = ParameterParserUtil.parseStringParam(request.getParameter("version"), "");

        User usr = userService.findUserByKey(request.getUserPrincipal().getName());
        usr.setRobotHost(ss_ip);
        usr.setRobotPort(ss_p);
        usr.setRobotPlatform(platform);
        usr.setRobotBrowser(browser);
        usr.setRobotVersion(version);
                        
        userService.updateUser(usr);
        
        ILogEventService logEventService = appContext.getBean(LogEventService.class);
        logEventService.createForPrivateCalls("/UpdateMyUserRobotPreference", "UPDATE", "Update user robot preference for user: " + usr.getLogin(), request);

        response.getWriter().print(usr.getLogin());
    } catch (CerberusException myexception) {
        response.getWriter().print(myexception.getMessageError().getDescription());
    }
}
 
Example #24
Source File: Config.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    LOGGER.info("STARTING APPLICATION CONTEXT CONFIGURATION FOR OPENTOSCA CONTAINER API");
    BrokerSupport mqttBroker = WebApplicationContextUtils
        .getRequiredWebApplicationContext(event.getServletContext())
        .getBean(BrokerSupport.class);
    mqttBroker.start();
}
 
Example #25
Source File: ApacheDSStartStopListener.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the server. It creates the partition, adds the index, and injects the context entries for the created
 * partitions.
 *
 * @param workDir the directory to be used for storing the data
 * @param loadDefaultContent if default content should be loaded
 * @throws Exception if there were some problems while initializing
 */
private void initDirectoryService(final ServletContext servletContext, final File workDir,
        final boolean loadDefaultContent) throws Exception {

    // Initialize the LDAP service
    service = new DefaultDirectoryService();
    service.setInstanceLayout(new InstanceLayout(workDir));

    // first load the schema
    initSchemaPartition();

    // then the system partition
    initSystemPartition();

    // Disable the ChangeLog system
    service.getChangeLog().setEnabled(false);
    service.setDenormalizeOpAttrsEnabled(true);

    // Now we can create as many partitions as we need
    addPartition("isp", "o=isp", service.getDnFactory());

    // And start the service
    service.startup();

    if (loadDefaultContent) {
        Resource contentLdif = Objects.requireNonNull(
            WebApplicationContextUtils.getWebApplicationContext(servletContext))
            .getResource("classpath:/content.ldif");
        LdifInputStreamLoader contentLoader = new LdifInputStreamLoader(service.getAdminSession(),
            contentLdif.getInputStream());
        int numEntries = contentLoader.execute();
        LOG.info("Successfully created {} entries", numEntries);
    }
}
 
Example #26
Source File: DownloadComponent.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void init() throws ServletException {
    super.init();

    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    this.userActivityLogService = ctx.getBean(UserActivityLogService.class);
}
 
Example #27
Source File: SsoHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private IUserManagementService getUserManagementService(ServletContext context) {
if (SsoHandler.userManagementService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
    SsoHandler.userManagementService = (UserManagementService) ctx.getBean("userManagementService");
}
return SsoHandler.userManagementService;
   }
 
Example #28
Source File: SessionInterceptor.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example #29
Source File: SessionInterceptor.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example #30
Source File: AbstractClickListener.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the application manager.
 *
 * @return the application manager
 */
protected ApplicationManager getApplicationManager() {
	return WebApplicationContextUtils
			.getWebApplicationContext(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
					.getRequest().getSession(true).getServletContext())
			.getBean(ApplicationManager.class);
}