从Servlet调用REST服务

时间:2019-03-08 11:23:48

标签: rest servlets jax-rs

我无法从Servlet调用REST服务,代码如下:-

1)UserManagement.jsp:-

<form action="./cs" method="post">  
        <p>ID : <input type="text" name="id" /></p>
        <p>Name : <input type="text" name="name" /></p>
        <p>Profession : <input type="text" name="profession" /></p>
        <input type="submit" name="buttonselected" value="Add User" />
        <input type="submit" name="buttonselected" value="Show User" />
        <input type="submit" name="buttonselected" value="Update User" />
        <input type="submit" name="buttonselected" value="List Users" />
    </form>

2)在ControllerServlet.java中:-

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        String str_buttonselected=request.getParameter("buttonselected");
           System.out.println("Button Selected = "+str_buttonselected);
           switch(str_buttonselected)
           {
           case "Add User":
               RequestDispatcher rd=request.getRequestDispatcher("/UserService/add");
               rd.forward(request, response);   
               break;
               .......             
           }
    }

3)UserService.java:-

@Path("/UserService")
public class UserService 
{   
   UserDao userDao = new UserDao();
   private static final String SUCCESS_RESULT="<result>success</result>";
   private static final String FAILURE_RESULT="<result>failure</result>";

   @POST
   @Path("/add")
   @Produces("application/xml") 
   @Consumes("application/x-www-form-urlencoded")
   public String createUser(@FormParam("id") int id, @FormParam("name") String name, @FormParam("profession") String profession) throws IOException
   {
      User user = new User(id, name, profession);
      int result = userDao.addUser(user);
      if(result == 1)
      {
         return SUCCESS_RESULT;
      }
      return FAILURE_RESULT;   
   }
}

请建议如何从Servlet调用REST服务网址。

感谢与问候 萨斯瓦塔·曼达尔。

0 个答案:

没有答案