创建FormAuthenticator
并为ServletContextHandler
设置这对你SecurityHandler
。这段代码创建了一个包含2个servlet的普通服务器。第一个servlet使用hello messsage来响应已认证的用户名。第二个servlet实现了一个简单的登录表单。
您应该可以将代码粘贴到main[]
并运行(您需要在类路径中使用以下jar; jetty-server
,jetty-servlet
和jetty-security
)。要测试,请在http://localhost:8080
处指向浏览器,在看到hello username
的响应之前,应该提示您输入凭据(用户名/密码)。
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);
context.addServlet(new ServletHolder(new DefaultServlet() {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("hello " + request.getUserPrincipal().getName());
}
}), "/*");
context.addServlet(new ServletHolder(new DefaultServlet() {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("<html><form method='POST' action='/j_security_check'>"
+ "<input type='text' name='j_username'/>"
+ "<input type='password' name='j_password'/>"
+ "<input type='submit' value='Login'/></form></html>");
}
}), "/login");
Constraint constraint = new Constraint();
constraint.setName(Constraint.__FORM_AUTH);
constraint.setRoles(new String[]{"user","admin","moderator"});
constraint.setAuthenticate(true);
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint);
constraintMapping.setPathSpec("/*");
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
securityHandler.addConstraintMapping(constraintMapping);
HashLoginService loginService = new HashLoginService();
loginService.putUser("username", new Password("password"), new String[] {"user"});
securityHandler.setLoginService(loginService);
FormAuthenticator authenticator = new FormAuthenticator("/login", "/login", false);
securityHandler.setAuthenticator(authenticator);
context.setSecurityHandler(securityHandler);
server.start();
server.join();
没有设法使它工作... – oshai
谢谢!这对我有帮助,并且我能够使其工作。 – mwhidden
这是有帮助的,但我想知道你是如何知道这么做的。 Jetty文档是...没有粗鲁,稀疏。例如'ConstraintMapping'完全没有文档,Google根本没有提供任何有关它的信息。你是否需要阅读内部Jetty代码来学习它? – Timmmm