对于一个web项目,我们有时候,前后端的项目是分在两个项目中的。
那提供后端服务的时可以有两种方案,一种是使用Spring Boot. 还有一种是提供restful服务。
参考: https://segmentfault.com/a/1190000002930500
http://www.makaidong.com/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E9%97%AE%E7%AD%94/11598.shtml
以下为自己些的demo
maven配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<junit.version>4.12</junit.version>
<jersey.version>2.23.1</jersey.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
</dependencies>
提供 rest 服务
@Path("/rest")
public class RestFulTest {
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Map testRest(){
Map<String,String> map = Maps.newHashMap();
map.put("name","taohong");
return map;
}
启动服务
public class StartServer {
public static void main(String[] args) {
/* final URI uri = UriBuilder.fromUri("http://localhost").port(9998).build();*/
final ResourceConfig config = new ResourceConfig();
config.packages("com.taohong.test"); //此处包的名字为提供访问路径文件的地方
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://localhost:8081"), config, false);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown();
}
});
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
启动main方法,浏览器输入:http://localhost:8081/rest/test
得到
{"name":"taohong"}
如果要和spring 相结合
public static void main(String[] args) throws Exception {
JerseyConfig resourceConfig = new JerseyConfig();
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AnnotationTest.class);
resourceConfig.packages("com.taohong.test.httprest");
resourceConfig.property("contextConfig", appContext); //spring bean中的配置,请记得价值resr文件的bean,即如果路径文件中要使用bean,记得要扫描到该文件,才能加载变量bean。
resourceConfig.property("contextConfigLocation", new ClassPathXmlApplicationContext
("classpath:applicationContext.xml"));
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://localhost:8080"), resourceConfig, false);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
server.shutdownNow();
}
}));
server.start();
}
@Configuration
@ComponentScan(basePackages = {"com.taohong.test.rest"})
public class AnnotationTest {
}