sli*_*kas 2 java jax-rs dropwizard
(我是java世界的新手)
我正在学习dropwizard,我想创建返回视图(html)或json的资源,具体取决于请求类型(ajax与否)
例:
@Path("/")
public class ServerResource {
@GET
@Produces(MediaType.TEXT_HTML)
public MainView getMainView() {
return new MainView("Test hello world");
}
}
Run Code Online (Sandbox Code Playgroud)
如果请求是AJAX,如何在相同的Path JSON响应中添加到此资源?
更新1. 我创建了这样的东西:
@Path("/")
public class ServerResource {
@GET
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_HTML)
public MainView getMainView(@HeaderParam("X-Requested-With") String requestType) {
return new MainView("hello world test!");
}
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<String> getJsonMainView() {
List<String> list = new ArrayList<String>();
for (Integer i = 0; i < 10; i++) {
list.add(i, "test" + i.toString());
}
return list;
}
}
Run Code Online (Sandbox Code Playgroud)
看起来这是按预期工作,但我知道这不是一个好习惯.
Ajax请求USUALLY(并非总是)X-Requested-With:XMLHttpRequest请求标头.请参阅如何区分Ajax请求和正常的Http请求?
以下代码尚未经过测试.
@Path("/")
public class ServerResource {
@GET
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public MainView getMainView(@HeaderParam("X-Requested-With") String requestType) {
if(requestType != null && requestType.equals("XMLHttpRequest")) {
//The request is AJAX
} else {
//The request is not AJAX
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5013 次 |
| 最近记录: |