Servlet - doPut() Example

[Updated: Aug 27, 2017, Created: Aug 21, 2017]

An HTTP PUT request is used to store the enclosed entity at the requested URI. If the requested URI refers to an already existing resource then it may be modified otherwise it should be stored at the new URI.

The difference between POST and PUT is that, POST creates a resource without defining the new resource path. whereas, PUT creates a new resource by defining complete resource path.

In Java Servlet, HttpServlet#doPut() method is overridden to handle a PUT request. Let's see an example to see how to do that.

Example

In this example, we will send a PUT request from the web browser via JQuery.

src/main/webapp/index.html

<html>
<head>
    <script
            src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
    </script>
</head>
<body>
<h2>Create New User</h2>
<form id="user-form">
    <table>
        <tr>
            <td> User id:</td>
            <td><input type="text" name="userId"/></td>
        </tr>
        <tr>
            <td> Name:</td>
            <td><input type="text" name="name"/></td>
        </tr>
        <tr>
            <td> email:</td>
            <td><input type="text" name="email"/></td>
        </tr>
    </table>
    <input type="submit" value="Submit"/>
</form>

<div id="msg"></div>

<script>
 $("#user-form").submit(function(event){
            event.preventDefault();
            var $form = $(this);
            var userId = $form.find('input[name="userId"]').val();
            var url = 'http://localhost:8080/users/'+userId;
            var userName = $form.find('input[name="name"]').val();
            var userEmail = $form.find('input[name="email"]').val();

            $.ajax({
                type : 'PUT',
                url : url,
                contentType: 'application/json',
                data : JSON.stringify({name: userName, email: userEmail}),
                success : function(data, status, xhr){
                   window.location.replace("http://localhost:8080/users/"+userId);
                },
                error: function(xhr, status, error){
                $('#msg').html('<span style=\'color:red;\'>'+error+'</span>')
                }
            });
        });

</script>
</body>
</html>

The Servlet

@WebServlet(name = "userServlet", urlPatterns = {"/users/*"})
public class UserServlet extends HttpServlet {
  @Override
  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      System.out.println("--put--");
      int userId = retrieveUserid(req);
      String body = inputStreamToString(req.getInputStream());
      System.out.println("body: " + body);
      UserDataService.Instance.saveUserById(userId, body);
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      System.out.println("--get--");
      int userId = retrieveUserid(req);
      String user = UserDataService.Instance.getUserById(userId);
      PrintWriter writer = resp.getWriter();
      writer.write(user);
  }

  private static int retrieveUserid(HttpServletRequest req) {
      String pathInfo = req.getPathInfo();
      if (pathInfo.startsWith("/")) {
          pathInfo = pathInfo.substring(1);
      }
      return Integer.parseInt(pathInfo);
  }

  private static String inputStreamToString(InputStream inputStream) {
      Scanner scanner = new Scanner(inputStream, "UTF-8");
      return scanner.hasNext() ? scanner.useDelimiter("\\A").next() : "";
  }
}
public enum UserDataService {
  Instance;
  private Map<Integer, String> dataMap = new HashMap<>();

  public void saveUserById(int id, String data){
      dataMap.put(id, data);
  }
  public String getUserById(int id){
      return dataMap.get(id);
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Submitting PUT request at 'http://localhost:8080':

Example Project

Dependencies and Technologies Used :

  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Servlet Do Put Example Select All Download
  • put-request-method-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also