目次
JAX-RS Tips
入力
Form から POST されるパラメータを取得
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
}
パラメータ
| パラメータ | 内容 |
|---|---|
| @QueryParam | URLのクエリパラメータ ?a=b |
| @MatrixParam | マトリックスパラメータ セミコロン(;)で区切って入れられる |
| @FormParam | HTMLのフォーム |
| @CookieParam | クッキーの値を取得 |
| @HeadeParam | HTTPリクエストヘッダの値を取得 |
生のHTTPヘッダーを取得するには
- @Contextを使う
@GET
@Produces("text/html")
public String hoge(@Context HttpHeaders headers) {
MultivaluedMap<String, String> _header = headers.getRequestHeaders();
:
}
ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse などを取得するには
- @Context を使う
@GET
@Produces(MediaType.TEXT_HTML)
public String greet(
@Context HttpServletRequest request,
@Context UriInfo uriInfo) {
}
パスパラメータの入力を制限する
- パスに正規表現で制限を行うことが可能
- http://codezine.jp/article/detail/7190?p=2
@Path("user/{userid: [a-zA-Z][a-zA-Z0-9]*}/{mailAddress}/{phone}") …(1)
public class UserResource {
…(省略)…
}
出力
ファイルダウンロード
- 上記サイトより
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/File")
public class FileDownloadService {
@GET
@Path("/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
StringBuilder sb = new StringBuilder();
sb.append("sample content");
InputStream is = new ByteArrayInputStream(sb.toString().getBytes());
return Response.ok(is)
.header("Content-disposition", "attachment; filename=data.txt")
.build();
}
}
添付ファイルのダウンロード
public Response file(File file, String filename) {
javax.ws.rs.core.Response.ResponseBuilder response
= Response.ok((Object) file);
if (StringUtils.isBlank(filename)) {
filename = "download_file";
}
try {
filename = new String(filename.getBytes("ms932"),"iso-8859-1");
} catch (UnsupportedEncodingException e) {
int extPos = filename.lastIndexOf('.');
if (extPos > 0) {
filename += filename.substring(extPos);
}
}
response.header("Content-Disposition",
String.format("attachment; filename=\"%s\"", filename));
return response.build();
}
CSVファイルのダウンロード
public Response csv(String csvContent, String filename) {
ByteArrayInputStream in = new ByteArrayInputStream(csvContent.getBytes());
javax.ws.rs.core.Response.ResponseBuilder response =
Response.ok(in);
if (StringUtils.isBlank(filename)) {
filename = "csv_file";
}
try {
filename = new String(filename.getBytes("ms932"),"iso-8859-1");
} catch (UnsupportedEncodingException e) {
int extPos = filename.lastIndexOf('.');
if (extPos > 0) {
filename += filename.substring(extPos);
}
}
response.header("Content-Type", "application/vnd.ms-excel")
.header("Content-Disposition",
String.format("attachment; filename=\"%s\"", filename));
return response.build();
}

YAGI Hiroto (piroto@a-net.email.ne.jp)
twitter http://twitter.com/pppiroto
Copyright© 矢木 浩人 All Rights Reserved.