Angular JavaScript Framework: Interacting with Java Servlet Backend

In my last article, I introduced the Angular JavaScript framework with working samples. Among all these JavaScript frameworks, I think Angular is the first one that does it right (I can be wrong on this as my exposure of JavaScript is limited). If your project needs Web GUI for example vSphere Web Client plug-ins, it’s definitely a good choice to consider.

The previous samples I wrote work without any backend. That is nice because you can try it out without setting up any application server. At the same time, it’s not very useful without interacting with a server that can serve dynamic content and persist data. This article would illustrate how to make Angular work with Java Servlet. To keep it simple therefore easy to digest, I just code the basics.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

The web page has two fields for user to enter: name and password. Once the “Add” button is pressed, a status message would show up to confirm the user has been added.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!doctype html>
<html ng-app>
  <head>
    <script src="lib/angular/angular.js"></script>
    <script src="js/form.js"></script>
  </head>
 
  <body>
    <form ng-controller="UserController" ng-submit="createUser()">
    <legend>Add New User</legend>
 
      <label>Name: </label> 
      <input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name"> 
 
      <label>Password:</label>
      <input type="text" id="pwd" name="pwd" ng-model="user.pwd" placeholder="Your Password">
 
      <button class="btn btn-primary">Add</button>
      <br/>
      <label>{{status}}</label>
    </form>
  </body>
 
</html>

The Javascript file form.js includes the following function UserController as the C in the MVC. It submits the user object back to the server and reads back the response message to the $scope.status upon success. The failure case is easy but not handled here for simplicity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function UserController($scope, $http)
{
  $scope.user = {};
 
  $scope.createUser = function() 
  {
    $http({
      method: 'POST',
      url: 'http://localhost:8080/WebAppSample/user',
      headers: {'Content-Type': 'application/json'},
      data:  $scope.user
    }).success(function (data) 
      {
    	$scope.status=data;
      });
  };
}

Behind the URL as listed in the above Javascript code is a Java Servlet as listed below. It’s a normal Java servlet except the part that reads the JSON payload. As it’s not part of the parameter, you cannot use the getParameter method. Instead, you get the Reader and read all the content before parsing it into JSON object. For the parsing part, I used json-simple which is very simple as its name suggests. Once you download the jar file json-simple-1.1.1.jar, you can place it in the lib directory of WEB-INFO.

From the JSON object, we can retrieve the value of the user and send back confirmation. In real project, there should be more logic to create a new user account, and/or persist into database. The useful code is ignored because the key here is to show how to send information back to server. You can find ton of information on database and persistence frameworks over the Internet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package org.doublecloud.rest.demo;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
@WebServlet("/user")
public class UserServlet extends HttpServlet 
{
  private static final long serialVersionUID = 1L;
 
  public UserServlet()
  {
    super();
  }
 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  {
    StringBuffer sb = new StringBuffer();
 
    try 
    {
      BufferedReader reader = request.getReader();
      String line = null;
      while ((line = reader.readLine()) != null)
      {
        sb.append(line);
      }
    } catch (Exception e) { e.printStackTrace(); }
 
    JSONParser parser = new JSONParser();
    JSONObject joUser = null;
    try
    {
      joUser = (JSONObject) parser.parse(sb.toString());
    } catch (ParseException e) { e.printStackTrace(); }
 
    String user = (String) joUser.get("name");
 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("A new user " + user + " has been created.");
    out.flush();
    out.close();
  }
}
This entry was posted in Software Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

29 Comments

  1. Ricardo
    Posted January 16, 2014 at 1:29 pm | Permalink

    There is a full source download?

  2. Posted January 16, 2014 at 3:43 pm | Permalink

    That is pretty much all I had. Anything in particular you need?

    Steve

  3. Ricardo
    Posted January 16, 2014 at 5:29 pm | Permalink

    I never configured and angularjs project, so I need the full source

  4. Posted January 17, 2014 at 10:07 am | Permalink

    I see. You may want to check out an earlier post: http://www.doublecloud.org/2013/09/angular-javascript-framework-mvc-simplified-in-html5/. Hope it helps.

    Steve

  5. esr
    Posted June 17, 2014 at 8:44 am | Permalink

    I was having trouble with angularJS POST method until I’ve seen your post. The problem was headers: {'Content-Type': 'application/json'} part.

    Thank you very much!

  6. mask
    Posted July 24, 2014 at 4:26 am | Permalink

    Hi !

    Thanks for this very clear and useful guide. It helped me a lot.
    I have one more little problem, maybe you could help me.
    It seems that as I try to parse my request parameters, the default parser configuration expects quoted strings, and the values returned by angularjs as it submits the request are unquoted, witch leads to an error (Unexpected character (m) at position 0.).

    Is it possible to enable unquoted strings in this process?

    Thanks again for the good toturial !

  7. Pratap A.K
    Posted August 8, 2014 at 10:22 am | Permalink

    I have tried almost 1 week for one perfect example, finally found this.. very helful.. Thanks a lot

  8. Arun
    Posted August 19, 2014 at 7:06 am | Permalink

    Hi steve…thank you so much !! i got stucked in call rest services !! after seeing ur blog …everything went perfect !!!

  9. Preet
    Posted September 9, 2014 at 12:42 am | Permalink

    when I am deploying it on apache-tomcat-7.0.55, It just does not call the servlet :( What can go wrong?

  10. Posted September 9, 2014 at 3:04 pm | Permalink

    You may want to check the Web app name and the path annotation. Good luck!

  11. vinod
    Posted October 12, 2014 at 6:07 pm | Permalink

    Thank you for this example, some thing like this I was looking for couple of days and this just answered most of my questions. I have few questions though, you have mentioned localhost in the URI, can that remain as local host when we deploy the code in different environment? and if there is Basic Atuthentication involved, does the system complain about it?
    I see lot of examples using AngularJS, with RestAPI, but for web development we need to have the GUI integrated with Servlet inorder to maintain the user session and to do form level business validation . See if you can refer me or let me know your thoughts

  12. Posted October 14, 2014 at 7:10 pm | Permalink

    Glad it helped Vinod,

    If you want to have basic authentication, you can use a filter, or handle it before the main logic in the method. Another alternative is to have Nginx as your proxy which can handle the authentication before the request coming to your Servlet. I think I have a few posts on Nginx. Please feel free to search for them.

    Steve

  13. Muralidhar
    Posted November 24, 2014 at 7:41 am | Permalink

    what if I had to do the above example with doGet method?

  14. ravikanth
    Posted December 30, 2014 at 6:36 am | Permalink

    I am not getting the application…..the error like following
    Error: [$injector:unpr] Unknown provider: $scope, $httpProvider <- $scope, $http
    http://errors.angularjs.org/1.3.5/$injector/unpr?p0=%24scope%2C%20%24httpProvider%20%3C-%20%24scope%2C%20%24http
    at file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:63:12
    at file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:3950:19
    at Object.getService [as get] (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:4097:39)
    at file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:3955:45
    at getService (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:4097:39)
    at Object.invoke (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:4129:13)
    at extend.instance (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:8376:21)
    at file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:7624:13
    at forEach (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:330:20)
    at nodeLinkFn (file:///E:/ravikanth/AngularDemo/AngularServlet/WebContent/js/angular.js:7623:11) angular.js:11500

  15. Posted December 30, 2014 at 12:52 pm | Permalink

    Sorry to hear that. There are pretty good discussions on the cause of the issue in the URL as included in your comment. You may want to read them.
    Steve

  16. Prateek
    Posted March 18, 2015 at 9:37 am | Permalink

    Can you please do it the other way? I mean to say return some values from servlet into the angular app and do something like this?

    Please help

  17. wasim mankar
    Posted March 24, 2015 at 8:12 am | Permalink

    hiii,
    I am trying to insert values from form fields (registration form) into database(mysql)
    and i need to do it using angular js..can anybody please help

  18. pavan
    Posted April 27, 2015 at 5:40 am | Permalink

    I’m using netbeans 8 IDE. I’ve used the similar code what you’ve mentioned but upon submitting nothing happens.
    I opened the console of the web browser there I saw the url pattern
    localhost:myapp:8080/url gives 404 error.
    meanwhile in my servlet class i’ve used the annotation in the same way as you’ve. I hope here we don’t need web.xml file.

  19. Posted April 27, 2015 at 10:54 am | Permalink

    Hi Pavan, for the url pattern I don’t think you need :myapp between localhost and port number. You may want to try it again.

    Steve

  20. Posted October 15, 2015 at 9:53 am | Permalink

    Very Good article sir .Very clean Explanation

  21. Ashish Kumar
    Posted January 1, 2016 at 11:53 pm | Permalink

    Thank you so much.It helped a lot…..

  22. lalit
    Posted January 13, 2016 at 10:04 am | Permalink

    Thaks this is good artical and its help me to solve my proble

  23. Posted January 13, 2016 at 6:21 pm | Permalink

    Thanks for letting me know. Glad it helped.

    -Steve

  24. Posted March 12, 2016 at 1:11 am | Permalink

    Has been looking for right example on this. This is useful, thanks for Sharing.

  25. gautam
    Posted April 18, 2016 at 5:52 am | Permalink

    url: ‘http://localhost:8080/WebAppSample/user’

    what is the “WebAppSample” in this? Is it name of the project or app or what? please let me know!

  26. Geoff
    Posted April 18, 2016 at 5:43 pm | Permalink

    Just what I needed. Believe it or not, there are not many google search results for exactly this!

  27. Anil
    Posted June 10, 2016 at 7:25 am | Permalink

    thanks
    i like you

  28. omar
    Posted June 26, 2016 at 3:02 am | Permalink

    I have a trouble with same example I do a post on client side and I have a :
    XMLHttpRequest cannot load http://localhost:8080/myapp. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access.

    any ideas ?

    Regards

  29. Posted June 26, 2016 at 2:03 pm | Permalink

    Hi Omar, I think you may have got so called CORS (cross origin resource sharing) issue. Searching the Web should get you more info there. Good luck! Steve

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.