18

I have an angularJS form which posts data to a Java Servlet, but I am not seeing the request go through; servlet "create" wasn't called.

Here's my code:

test.html

<body>
    <form ng-controller="UserController">

        <legend>Create User</legend>
        <label>Name</label> 
        <input type="text" id="name" name="name" ng-model="name" placeholder="User Name"> 

        <label>Email</label>
        <input type="text" id="email" name="email" ng-model="email" placeholder="ur email here"> 

        <label>Password</label>
        <input type="text" id="pwd" name="pwd" ng-model="pwd" placeholder="ur own pwd here">

        <button ng-submit="createUser()" class="btn btn-primary">Register</button>

    </form>
</body>

script.js

function UserController($scope, $http) {
    $scope.user = {};
    $scope.createUser = function() {
        $http({
            method : 'POST',
            url : '/create',
            data : 'name=' + $scope.user.name + '&email=' + $scope.user.email,
            headers : {
                'Content-Type' : 'application/x-www-form-urlencoded'
            }
        })
    }

my servlet is as below,but it doesn't print "Post" an all.

public class FirstServlet extends HttpServlet
{

    /**
     * 
     */
    private static final long   serialVersionUID    = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        System.out.println("Get");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        System.out.println("Post");
    }
}

The web server is jetty,and the web.xml as below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="2.4"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>createUser</servlet-name>
        <servlet-class>servlet.FirstServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>createUser</servlet-name>
        <url-pattern>/create</url-pattern>
    </servlet-mapping>
</web-app>
yxdming
  • 181
  • 1
  • 1
  • 4
  • I've edited my answer to include Servlet code. This is probably the most extensive answer I've written, haha – Christian Stewart Feb 24 '13 at 01:16
  • I believe his problem was that ng-submit wasn't on the form tags, as I answered below. – Christian Stewart Feb 25 '13 at 16:40
  • I'd put a console.log inside the createUser js function. Also, are you sure your http call can resolve to a proper server url? You can check that in your chrome dev tools network tab perhaps? Lastly, in your http post, you are using query string, no need to do that, just try what @ChristianStewart suggested for data param.. – mentat Oct 30 '15 at 05:08

2 Answers2

32

To post data to a web server, you will want to bind your form values to a object in the $scope, and then submit that object to the script.

The trick is to submit the entire object "user" to the server, and Angular will automatically format it in JSON. Also, "user" was not being used by the ng-model tags.

Another thing to note is that you will probably want to include something for the app to do when it finishes the request. You can use the methods ".success(function(data){})" and ".error(...)" to do this (these are methods on the promise $http returns).

I've included both PHP and Servlet code; it is the same, however, for all server scripts (JSON data from Angular).

HTML

<body>
<form ng-controller="UserController" ng-submit="createUser()">

    <legend>Create User</legend>

    <label>Name</label> 
    <input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name"> 

    <label>Email</label>
    <input type="text" id="email" name="email" ng-model="user.email" placeholder="ur email here"> 

    <label>Password</label>
    <input type="text" id="pwd" name="pwd" ng-model="user.pwd" placeholder="ur own pwd here">

    <button class="btn btn-primary">Register</button>

</form>
</body>

</html>

Controller

function UserController($scope, $http) {
    $scope.user = {};
    $scope.createUser = function() {
        $http({
            method : 'POST',
            url : '/create',
            data : $scope.user
        })
    }

Example Server Code: PHP

$data = file_get_contents("php://input");
$objData = json_decode($data);

$pwd = $objData -> pwd;
$user = $objData -> name; //etc

Example Server Code: JAVA Servlet

JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys

while(it.hasNext())
{
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    //do something with it here
    //you can also do:
    String user = jObj.get("user");
}
Christian Stewart
  • 15,217
  • 20
  • 82
  • 139
0

Changing ng-submit to ng-click should do the trick.

Community
  • 1
  • 1
  • this was voted -1, but it actually solved the problem I was having.. ng-submit would not allow me to make an ajax post calll to the same page, but changing to type=button verse type=submit and using ng-click worked –  Jan 10 '16 at 19:21
  • Did you mean `ng-click`? – rinogo Jun 02 '16 at 16:56