我有一个运行的jetty-server,具有基本的身份验证功能。现在我想在应用程序中看到哪些用户已登录并具有活动会话。我希望用户保存jpa数据库中的更改,因此我需要在我的JpaService类中获取信息以保存用户的更改。我正在运行的服务器是
public class TestServer {
public static void main(String[] args) {
startServer();
}
public static void startServer() {
Server server = new Server(8899);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setSecurityHandler(basicAuth());
server.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", JpaService.class.getCanonicalName());
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
server.destroy();
}
}
private static final SecurityHandler basicAuth() {
HashLoginService l = new HashLoginService();
l.putUser("user1", Credential.getCredential("pass1"), new String[] {"user"});
l.putUser("user2", Credential.getCredential("pass2"), new String[] { "admin"});
l.setName("Private Server");
Constraint constraint = new Constraint();
constraint.setName(Constraint.__BASIC_AUTH);
constraint.setRoles(new String[] { "admin", "user" });
constraint.setAuthenticate(true);
ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");
ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
csh.setAuthenticator(new BasicAuthenticator());
csh.setRealmName("NameOfRealm");
csh.addConstraintMapping(cm);
csh.setLoginService(l);
return csh;
}
}
那么我如何“阅读”相关信息呢?我使用jetty 9.2.3而Get jetty realm credentials in application似乎过时了。
我尝试添加以下几种方法来添加以下内容,但没有任何反应。
public class HttpSessionCollector implements HttpSessionListener {
private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
sessions.put(session.getId(), session);
System.out.println("Created Session: "+event.getSession().getId());
System.out.println("Last Accessed: "+new Date(event.getSession().getLastAccessedTime()));
System.out.println("Attributes: "+ event.getSession().getAttributeNames());
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
sessions.remove(event.getSession().getId());
System.out.println("Destroyed Session: "+event.getSession().getId());
}
public static HttpSession find(String sessionId) {
return sessions.get(sessionId);
}
public static Map<String, HttpSession> getSessions() {
return sessions;
}
}
当我添加context.getSessionHandler().getState()
时,它会显示“已停止”。当我尝试.start()
时,我得到一个NullPointerException。也许我做错了,但它是如何完成的,所以我在我的网络应用程序中登录用户?