JAX-RSでアクセスした拡張子に応じて出力形式を変える+Spring連携
web.xml
<web-app> <display-name>Archetype Created Web Application</display-name> <!-- read default applicationContext.xml --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>jersey</servlet-name> <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>test.package.front</param-value> </init-param> <init-param> <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name> <param-value>test.package.UriConnegFilterImpl</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
UriConnegFilterImpl.java
public class UriConnegFilterImpl extends UriConnegFilter { private static final Map<String, MediaType> MEDIA_TYPE_MAPPING = new HashMap<String, MediaType>(); static { MEDIA_TYPE_MAPPING.put("json", MediaType.APPLICATION_JSON_TYPE); MEDIA_TYPE_MAPPING.put("xml", MediaType.APPLICATION_XML_TYPE); } public UriConnegFilterImpl() { super(MEDIA_TYPE_MAPPING); } }
フロントのインターフェース用クラス
import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import test.package.bean.InfoResponseBean; import test.package.service.InfoService; import com.sun.jersey.api.core.InjectParam; import com.sun.jersey.spi.resource.Singleton; @Singleton @Path("/app") public class InfoResource { // AutowiredとかではなくInjectParamでインジェクション @InjectParam InfoService infoService; @GET @Path("/info") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public InfoResponseBean info( @DefaultValue("") @QueryParam("userId") Long userId) { return infoService.info(userId); } }
こんな感じでアクセスしてレスポンスを切り替えられる。 http://localhost:8080/context_path/app/info.xml?userId=xxx http://localhost:8080/context_path/app/info.json?userId=xxx
参考: