下面列出了怎么用org.eclipse.jetty.server.session.SessionHandler的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Starts the JETTY server
*/
public void run() {
Server server = new Server(port);
Handler handler = new Handler();
SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
sh.setHandler(handler);
server.setHandler(sh); // set session handle
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private TransactionServer() {
this.server = new Server(port);
try {
ServletContextHandler handler = new ServletContextHandler();
handler.setContextPath("/");
handler.setSessionHandler(new SessionHandler());
handler.addServlet(EnvServlet.class, "/api/env");
handler.addServlet(PropertiesServlet.class, "/api/props");
handler.addServlet(TaskServlet.class, "/api/tasks");
handler.addServlet(StaticContentServlet.class, "/*");
handler.addServlet(StartServlet.class, "/api/start");
server.setHandler(handler);
} catch (Exception e) {
log.error("Exception in building AdminResourcesContainer ", e);
}
}
private TransactionServer() {
this.server = new Server(port);
try {
ServletContextHandler handler = new ServletContextHandler();
handler.setContextPath("/");
handler.setSessionHandler(new SessionHandler());
handler.addServlet(EnvServlet.class, "/api/env");
handler.addServlet(PropertiesServlet.class, "/api/props");
handler.addServlet(TaskServlet.class, "/api/tasks");
handler.addServlet(StaticContentServlet.class, "/*");
handler.addServlet(StartServlet.class, "/api/start");
server.setHandler(handler);
} catch (Exception e) {
log.error("Exception in building AdminResourcesContainer ", e);
}
}
@Test
public void emptyPac4jInConfig() {
setup(App.class, "empty-pac4j.yaml");
App app = dropwizardTestSupport.getApplication();
ObjectMapper om = dropwizardTestSupport.getObjectMapper();
Environment env = dropwizardTestSupport.getEnvironment();
Config config = app.bundle.getConfig();
assertThat(config).isNotNull();
// this is the default url resolver!
assertThat(config.getClients().getUrlResolver())
.isInstanceOf(JaxRsUrlResolver.class);
assertThat(om.findMixInClassFor(Client.class)).isNotNull();
assertThat(env.jersey().getResourceConfig().getSingletons())
.haveAtLeastOne(CONDSI);
assertThat(env.getApplicationContext().getSessionHandler())
.isInstanceOf(SessionHandler.class);
}
@Override
public void init(ServletContextHandler sc) {
CoreConfig cc = CoreConfig.getInstance("defines");
String dh = cc.getProperty("jetty.session.manager.db", "default");
Server sv = sc . getServer ( );
DefaultSessionIdManager im = new DefaultSessionIdManager(sv);
im.setWorkerName (Core.SERVER_ID);
sv.setSessionIdManager (im);
SessionHandler sh = sc . getSessionHandler ( );
DefaultSessionCache ch = new DefaultSessionCache (sh);
JDBCSessionDataStore sd = new JDBCSessionDataStore( );
sd.setDatabaseAdaptor (getAdaptor(dh));
ch.setSessionDataStore (sd);
sh.setSessionCache (ch);
sc.setSessionHandler (sh);
}
private static void setupRestApiContextHandler(WebAppContext webapp, ZeppelinConfiguration conf) {
final ServletHolder servletHolder =
new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());
servletHolder.setInitParameter("javax.ws.rs.Application", ZeppelinServer.class.getName());
servletHolder.setName("rest");
servletHolder.setForcedPath("rest");
webapp.setSessionHandler(new SessionHandler());
webapp.addServlet(servletHolder, "/api/*");
String shiroIniPath = conf.getShiroPath();
if (!StringUtils.isBlank(shiroIniPath)) {
webapp.setInitParameter("shiroConfigLocations", new File(shiroIniPath).toURI().toString());
webapp
.addFilter(ShiroFilter.class, "/api/*", EnumSet.allOf(DispatcherType.class))
.setInitParameter("staticSecurityManagerEnabled", "true");
webapp.addEventListener(new EnvironmentLoaderListener());
}
}
private void invalidateAllSession(HttpSession preferredSession, HttpSession localSession) {
Server server = ((Session)preferredSession).getSessionHandler().getServer();
final Handler[] handlers = server.getChildHandlersByClass(SessionHandler.class);
List<String> invalidatedSessions = new ArrayList<>();
if (handlers!=null) {
for (Handler h: handlers) {
Session session = ((SessionHandler)h).getSession(preferredSession.getId());
if (session!=null) {
invalidatedSessions.add(session.getId());
session.invalidate();
}
}
}
if(!invalidatedSessions.contains(localSession.getId())){
localSession.invalidate();
}
}
protected SessionHandler findPeerSessionMarkedPreferred(String localSessionId, Handler[] handlers) {
SessionHandler preferredHandler = null;
// are any sessions themselves marked as primary
if (handlers != null) {
for (Handler h: handlers) {
SessionHandler sh = (SessionHandler)h;
Session sessionHere = sh.getSession(localSessionId);
if (sessionHere!=null) {
if (Boolean.TRUE.equals(sessionHere.getAttribute(KEY_IS_PREFERRED))) {
if (preferredHandler!=null) {
// could occasionally happen on race, but should be extremely unlikely
log.warn("Multiple sessions marked as preferred for "+localSessionId+"; using "+info(preferredHandler)+" not "+info(sh));
sessionHere.setAttribute(KEY_IS_PREFERRED, null);
} else {
preferredHandler = sh;
}
}
}
}
}
return preferredHandler;
}
public void setAttribute(String name, Object value) {
if (setAllKnownSessions) {
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = ((SessionHandler)h).getSession(localSession.getId());
if (ss!=null) {
ss.setAttribute(name, value);
}
}
return;
} else {
if (!setLocalValuesAlso) {
// can't do all, but at least to local
configureWhetherToSetLocalValuesAlso(true);
}
}
}
preferredSession.setAttribute(name, value);
if (setLocalValuesAlso) {
localSession.setAttribute(name, value);
}
}
public void removeAttribute(String name) {
if (setAllKnownSessions) {
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = ((SessionHandler)h).getSession(localSession.getId());
if (ss!=null) {
ss.removeAttribute(name);
}
}
return;
} else {
if (!setLocalValuesAlso) {
// can't do all, but at least to local
configureWhetherToSetLocalValuesAlso(true);
}
}
}
preferredSession.removeAttribute(name);
if (setLocalValuesAlso) {
localSession.removeAttribute(name);
}
}
public MultiSessionAttributeAdapter resetExpiration() {
// force all sessions with this ID to be marked used so they are not expired
// (if _any_ session with this ID is expired, then they all are, even if another
// with the same ID is in use or has a later expiry)
Integer maxInativeInterval = MAX_INACTIVE_INTERVAL.getDefaultValue();
if(this.mgmt != null){
maxInativeInterval = mgmt.getConfig().getConfig(MAX_INACTIVE_INTERVAL);
}
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = ((SessionHandler)h).getSession(getId());
if (ss!=null) {
ss.setMaxInactiveInterval(maxInativeInterval);
}
}
}
return this;
}
@Override
public void start() throws Exception {
for (MutableServletContextHandler environment : listeners.keySet()) {
final SessionHandler sessionHandler = environment.getSessionHandler();
if (sessionHandler == null) {
final String msg = String.format(
"Can't register session listeners for %s because sessions support is not enabled: %s",
environment.getDisplayName().toLowerCase(),
Joiner.on(',').join(listeners.get(environment).stream()
.map(it -> FeatureUtils.getInstanceClass(it).getSimpleName())
.collect(Collectors.toList())));
if (failWithoutSession) {
throw new IllegalStateException(msg);
} else {
logger.warn(msg);
}
} else {
listeners.get(environment).forEach(sessionHandler::addEventListener);
}
}
}
/**
* Starts the JETTY server
*/
public void run() {
Server server = new Server(port);
Handler handler = new Handler();
SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
sh.setHandler(handler);
server.setHandler(sh); // set session handle
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Starts the JETTY server
*/
public void run() {
Server server = new Server(port);
Handler handler = new Handler();
try {
SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
sh.addEventListener(new CustomListener());
sh.setHandler(handler);
server.setHandler(sh);
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Swagger core handler - Needed for the RestFul api documentation
*
* @return ServletContextHandler of Swagger
*/
private static ServletContextHandler setupSwaggerContextHandler(int port) {
// Configure Swagger-core
final ServletHolder SwaggerServlet = new ServletHolder(
new com.wordnik.swagger.jersey.config.JerseyJaxrsConfig());
SwaggerServlet.setName("JerseyJaxrsConfig");
SwaggerServlet.setInitParameter("api.version", "1.0.0");
SwaggerServlet.setInitParameter("swagger.api.basepath", "http://localhost:" + port + "/api");
SwaggerServlet.setInitOrder(2);
// Setup the handler
final ServletContextHandler handler = new ServletContextHandler();
handler.setSessionHandler(new SessionHandler());
handler.addServlet(SwaggerServlet, "/api-docs/*");
return handler;
}
private void initializeShiro(final ShiroConfiguration config, Environment environment) {
if (config.isEnabled()) {
LOG.debug("Shiro is enabled");
if (config.isDropwizardSessionHandler() && environment.getApplicationContext().getSessionHandler() == null) {
LOG.debug("Adding DropWizard SessionHandler to environment.");
environment.getApplicationContext().setSessionHandler(new SessionHandler());
}
// This line ensure Shiro is configured and its .ini file found in the designated location.
// e.g., via the shiroConfigLocations ContextParameter with fall-backs to default locations if that parameter isn't specified.
environment.servlets().addServletListeners( new EnvironmentLoaderListener() );
final String filterUrlPattern = config.getSecuredUrlPattern();
LOG.debug("ShiroFilter will check URLs matching '{}'.", filterUrlPattern);
environment.servlets().addFilter("shiro-filter", new ShiroFilter()).addMappingForUrlPatterns( EnumSet.allOf(DispatcherType.class), true, filterUrlPattern );
} else {
LOG.debug("Shiro is not enabled");
}
}
public SessionHandler build() {
SessionHandler sessionHandler = new SessionHandler() {
{
// no setter available for maxCookieAge
_maxCookieAge = (int) cookieMaxAge.toSeconds();
}
};
SessionCache sessionCache = new DefaultSessionCache(sessionHandler);
sessionHandler.setSessionCache(sessionCache);
FileSessionDataStore dataStore = new FileSessionDataStore();
sessionCache.setSessionDataStore(dataStore);
sessionHandler.setHttpOnly(true);
sessionHandler.setSessionTrackingModes(ImmutableSet.of(SessionTrackingMode.COOKIE));
sessionHandler.setMaxInactiveInterval((int) maxInactiveInterval.toSeconds());
sessionHandler.setRefreshCookieAge((int) cookieRefreshAge.toSeconds());
dataStore.setDeleteUnrestorableFiles(true);
dataStore.setStoreDir(new File(path));
dataStore.setSavePeriodSec((int) savePeriod.toSeconds());
return sessionHandler;
}
private static void setupRestApiContextHandler(WebAppContext webapp, SubmarineConfiguration conf) {
final ServletHolder servletHolder =
new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());
servletHolder.setInitParameter("javax.ws.rs.Application", SubmarineServer.class.getName());
servletHolder.setName("rest");
servletHolder.setForcedPath("rest");
webapp.setSessionHandler(new SessionHandler());
webapp.addServlet(servletHolder, "/api/*");
}
public InfoBoard(String appName, int port) {
this.appName = appName;
this.server = new Server(port);
this.statusInfo = new StatusInfo();
this.jvmStatsReporter = new JvmStatsReporter(appName, 60000);
this.jvmStatsReporter.addStatsHandler(statusInfo);
this.jvmStatsReporter.start();
try {
ServletContextHandler handler = new ServletContextHandler();
handler.setContextPath("/");
handler.setSessionHandler(new SessionHandler());
handler.addServlet(EnvServlet.class, "/api/env");
handler.addServlet(PropsServlet.class, "/api/props");
handler.addServlet(StaticServlet.class, "/*");
handler.addServlet(HystrixServlet.class, "/breaker");
handler.addServlet(HystrixMetricsStreamServlet.class, "/hystrix.stream");
handler.addServlet(new ServletHolder(new StatusServlet(statusInfo)), "/api/status");
server.setHandler(handler);
} catch (Exception e) {
logger.error("start jetty error!", e);
}
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
JPAWebConfigurer configurer = new JPAWebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
protected synchronized void init() {
try {
buildJettyProperties();
server = new Server(new ExecutorThreadPool(HttpExcutors.getThreadPool()));
ServerConnector connector = this.createConnector();
Logs.http().info("listen port: {}", port);
String host = StartContext.httpHost();
if (host != null && host.length() > 0) {
connector.setHost(host);
}
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
ServletContextHandler context = createServletContextHandler();
context.setContextPath(AppInfo.get("sumk.jetty.web.root", "/"));
context.addEventListener(new SumkLoaderListener());
addUserListener(context, Arrays.asList(ServletContextListener.class, ContextScopeListener.class));
String resourcePath = AppInfo.get("sumk.jetty.resource");
if (StringUtil.isNotEmpty(resourcePath)) {
ResourceHandler resourceHandler = JettyHandlerSupplier.resourceHandlerSupplier().get();
if (resourceHandler != null) {
resourceHandler.setResourceBase(resourcePath);
context.insertHandler(resourceHandler);
}
}
if (AppInfo.getBoolean("sumk.jetty.session.enable", false)) {
SessionHandler h = JettyHandlerSupplier.sessionHandlerSupplier().get();
if (h != null) {
context.insertHandler(h);
}
}
server.setHandler(context);
} catch (Throwable e) {
Log.printStack("sumk.http", e);
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
log.info("Server starting...");
var server = new Server(8080);
var context = new WebAppContext();
context.setBaseResource(findWebRoot());
context.addServlet(VaadinServlet.class, "/*");
context.setContextPath("/");
context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*vaadin/.*\\.jar|.*/classes/.*");
context.setConfigurationDiscovered(true);
context.getServletContext().setExtendedListenerTypes(true);
context.addEventListener(new ServletContextListeners());
server.setHandler(context);
var sessions = new SessionHandler();
context.setSessionHandler(sessions);
var classList = Configuration.ClassList.setServerDefault(server);
classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
WebSocketServerContainerInitializer.initialize(context); // fixes IllegalStateException: Unable to configure jsr356 at that stage. ServerContainer is null
try {
server.start();
server.join();
} catch (Exception e) {
log.error("Server error:\n", e);
}
log.info("Server stopped");
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
ServletContextHandler contextHandler = new ServletContextHandler();
WebConfigurer configurer = new WebConfigurer();
configurer.setContext(context);
contextHandler.addEventListener(configurer);
// Create the SessionHandler (wrapper) to handle the sessions
HashSessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
contextHandler.setHandler(sessions);
return contextHandler;
}