星期三, 8月 01, 2012

[Java] 快快樂樂使用 Jersey MVC 架構

先前利用jersey都只有在controller端直接將JSON物件轉成字串輸出,
jersey也提供MVC的方式來支援JSP來做template(View)
讓畫ui結構更直覺多了。




步驟一:設定 web.xml config檔,需先前的設定方法不太一樣,這次是指定filter。
經過測試如果沒改filter的用法,會map不到對應的樣版XD

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5"> 
 <filter>
  <filter-name>jersey</filter-name>
  <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
  
  <init-param>
   <param-name>com.sun.jersey.config.property.packages</param-name>
   <param-value>sample</param-value>
  </init-param>
  <init-param>
   <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
   <param-value>/WEB-INF/views</param-value>
  </init-param>
  <init-param>
   <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
   <param-value>/(resources|(WEB-INF/views))/.*</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>jersey</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  
</web-app>


步驟二:建立controller,可以定義回傳物件為Viewable或Response

package com.ezakus.web;
 
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
 
import com.sun.jersey.api.view.Viewable;
 
@Stateless
@Path("/")
public class MyController {
 
    @GET
    @Produces("text/html")
    public Viewable index() {
        return new Viewable("/index");
    }
 
}
package com.ezakus.web;
 
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
 
import com.sun.jersey.api.view.Viewable;
 
@Stateless
@Path("/")
public class MyController {
 
    @GET
    @Produces("text/html")
    public Response index() {
        return Response.ok(new Viewable("/index")).build();
    }
 
}



步驟三:建立View的樣版
TIP:新建index.jsp樣版檔,需要放在WEB-INF/views裡面。
jersey會在樣版對應一個it的變數,透過it所存的內容就可以利用JSTL來畫出來


<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Welcome ${it.user}!</h1>
  <p>
    items in your cart :<br />
    <c:forEach var="item" items="${it.items}">
        ${item}<br />
    </c:forEach>
  </p>
</body>
</html>


Reference:
https://blogs.oracle.com/sandoz/entry/mvcj
Using Jsp in a Jersey JAX-RS RESTful application

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails