首先启动一个Server:
public Server getServer() {
Server server = new Server(new InetSocketAddress("localhost", 8081));
ServletContextHandler jerseyHandler = getJerseyHandler();
setSecurity(jerseyHandler);
server.setHandler(jerseyHandler);
return server;
}
其中的JerseyHandler如下:
public ServletContextHandler getJerseyHandler() {
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
handler.setContextPath("/ws/v1");
//add jersey container
ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class);
jerseyServletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
"com.sun.jersey.api.core.PackagesResourceConfig");
jerseyServletHolder.setInitParameter("com.sun.jersey.config.property.packages", "rest/resouce");
handler.addServlet(jerseyServletHolder, "/*");
return handler;
}
这里使用的是Jetty自带的安全认证方式:SecurityHandler:
private void setSecurity(ServletContextHandler handler) {
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
handler.setSecurityHandler(securityHandler);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec("ws/v1/*");
mapping.setConstraint(constraint);
securityHandler.setConstraintMappings(Collections.singletonList(mapping));
securityHandler.setAuthenticator(new FormAuthenticator());
securityHandler.setLoginService(new HashLoginService("MyRealm","realm.properties"));
}
其中的realm.properties的内容如下,其格式为:用户名 : 密码 : 角 {MOD}1:角 {MOD}2......
jetty: MD5:164c88b302622e17050af52c89945d44,user
admin: CRYPT:adpexzg3FUZAk,server-administrator,content-administrator,admin,user
other: OBF:1xmk1w261u9r1w1c1xmq,user
plain: plain,user
user: password,user
运行如下:
public void run() {
Server server = getServer();
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
上述代码包装过的ServletContextHandler后的情况下,ws/v1/*的所有路径都必须先经过认证之后才能访问。
下面是web页面的Jetty嵌入式代码:
public HandlerWrapper getWebHandler() {
WebAppContext context = new WebAppContext();
context.setContextPath("/");
context.setDescriptor("hugetable-core/src/main/webapp/WEB-INF/web.xml");
context.setResourceBase("hugetable-core/src/main/webapp");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setParentLoaderPriority(true);
return context;
}