AngularJS & Java Servlet POST Request Example

I tried simple POST request with AngularJS but it didn’t work properly, then looked for solution in stackoverflow and found answer in here [1]. According to that explanation I wrote simple snippet.

<!doctype html>
<html ng-app="myApp">
<head>
<script src="js/angular.min.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
	<div ng-controller="myCtrl">
		<form ng-submit="sendPost()">
			<input ng-model="name" />
			<button type="submit">Send</button>
		</form>
		<p>Message from servlet: {{message}}
	</div>
</body>
</html>
var helloAjaxApp = angular.module("myApp", []);

helloAjaxApp.controller("myCtrl", [ '$scope', '$http', function($scope, $http) {

	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
	
	$scope.sendPost = function() {
		$http({
			url : 'MyServlet',
			method : "POST",
			data : {
				'name' : $scope.name
			}
		}).then(function(response) {
			console.log(response.data);
			$scope.message = response.data;
		}, function(response) {
			//fail case
			console.log(response);
			$scope.message = response;
		});

	};
} ]);
package com;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;

public class MyServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LogManager.getLogger(MyServlet.class);

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = request.getReader();
		String str = null;
		while ((str = br.readLine()) != null) {
			sb.append(str);
		}
		JSONObject jObj = new JSONObject(sb.toString());
		String name = jObj.getString("name");

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("hello from java. you entered : " + name);

	}

}

[1] http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data

[2] https://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example

Advertisements

6 thoughts on “AngularJS & Java Servlet POST Request Example

  1. Neha says:

    Thank you, this is one of the right examples I have been looking for.

  2. Ankit Ostwal says:

    Thank you.Perfect example i was looking for.Saved me 4-5 hrs.Made my day being a newbie in angular js.

  3. sayyad mujahed says:

    thank you.!!

  4. Amal says:

    But I am having some trouble showing incompatible type exception – in constructor of JSONobject()!? Comment is – Required Map,Found String!!! How can i solve this?

  5. Sheikabdulkather says:

    realy nice example thank you.

  6. Hey, thanks for the example. I was wondering, what is the file structure for this example? How can I combine Angular and Java servlet so that Angular is able to access the Java servlet with the $http call? Do I put all the files in the same directory?

    Also, do I need to use JSP, or can I just use an HTML file with Angular?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: