OSGI系列 Servlet-Rest发布Http服务

除了WebService 和 Restful,我们还希望通过把servlet发布出去

1、在blueprint.xml中定义

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
           http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">

  <!-- to setup camel servlet with OSGi HttpService -->
  <reference id="httpService" interface="org.osgi.service.http.HttpService"/>

  <bean class="org.apache.camel.component.servlet.osgi.OsgiServletRegisterer"
        init-method="register"
        destroy-method="unregister">
    <property name="alias" value="/test/rest"/>
    <property name="httpService" ref="httpService"/>
    <property name="servlet" ref="camelServlet"/>
  </bean>

  <bean id="camelServlet" class="org.apache.camel.component.servlet.CamelHttpTransportServlet"/>

  <!-- a bean for user services -->
  <bean id="userService" class="jmust.demo.test.servlet_rest_blueprint.UserService"/>

  <camelContext xmlns="http://camel.apache.org/schema/blueprint">

    <!-- configure rest to use the camel-servlet component, and use json binding mode -->
    <!-- and tell to output json in pretty print mode -->
    <!-- setup context path and port number that Apache Tomcat will deploy this application with,
         as we use the servlet component, then we need to aid Camel to tell it these details so Camel
         knows the url to the REST services.
         Notice: This is optional, but needed if the RestRegistry should enlist accurate information.
         You can access the RestRegistry from JMX at runtime -->
    <restConfiguration component="servlet" bindingMode="json" contextPath="/test/rest"
                       port="8181">
      <dataFormatProperty key="prettyPrint" value="true"/>
    </restConfiguration>

    <!-- defines the rest services using the context-path /user -->
    <rest path="/user" consumes="application/json" produces="application/json">
      <description>User rest service</description>

      <!-- this is a rest GET to view an user by the given id -->
      <get uri="/{id}" outType="jmust.demo.test.servlet_rest_blueprint.bean.User">
        <description>Find user by id</description>
        <to uri="bean:userService?method=getUser(${header.id})"/>
      </get>

      <!-- this is a rest PUT to create/update an user -->
      <put type="jmust.demo.test.servlet_rest_blueprint.bean.User">
        <description>Updates or create a user</description>
        <to uri="bean:userService?method=updateUser"/>
      </put>

      <!-- this is a rest GET to find all users -->
      <get uri="/findAll" outType="jmust.demo.test.servlet_rest_blueprint.bean.User[]">
        <description>Find all users</description>
        <to uri="bean:userService?method=listUsers"/>
      </get>
 
 
    </rest>
  </camelContext>
</blueprint>

2、定义user对象

public class User {

    private int id;
    private String name;
    
    public User() {
        super();
    }

    public User(int id,String name){
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

3、定义UserService实现

public class UserService {
    
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    private final Map<String,User> users= new TreeMap<String, User>();
    
    public UserService(){
        users.put("123", new User(123,"xxxx"));
        users.put("456", new User(456,"yyyy"));
    }
    
    
    public User getUser(String id){
        return users.get(id);
    }
    
    
    public Collection<User> listUsers(){
        return users.values();
    }
    
    public void updateUser(User user){
        users.put(""+user.getId(),user);
    }
    
}

4、定义UserServlet

public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    private static final Logger log = LoggerFactory.getLogger(UserServlet.class);
    public UserServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        PrintWriter writer = null;
        try{
            response.setContentType("text/html");
            writer = response.getWriter();
            writer.println("{name:'"+name+"',pwd:'"+pwd+"'");
        }catch(Exception e){
            log.error("系统异常:",e);
        }finally{
            if(writer != null){
                writer.close();
            }
        }
        
    }

}

5、pom.xml

<plugins>
            <!-- to generate the MANIFEST-FILE of the bundle -->
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                  <manifestLocation>target/META-INF</manifestLocation>
                  <instructions>
                    <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
                    <Export-Package>jmust.demo.test.servlet_rest_blueprint*</Export-Package>
                    <Import-Package>
                      *
                    </Import-Package>
                  </instructions>
                </configuration>
          </plugin>
</plugins>


你可能感兴趣的:(OSGI系列,Servlet-Rest发)