In my current project, I am developing a straightforward angularjs - J2EE application that fetches data from a mysql server and then displays it on an HTML page. The angular function is triggered on form submission as shown below:
<div id="register_form" ng-controller="MyDiaryLogin">
<form>
<ul>
<li><input type="text" name="firstname" ng-model="user.firstname" /></li>
<li><input type="text" name="lastname" ng-model="user.lastname" /></li>
<li><input type="text" name="email" ng-model="user.email" /></li>
<li><input type="password" name="password" ng-model="user.password" /></li>
<li><input type="password" name="confpass" ng-model="user.confpass" /></li>
<li><input type="text" name="age" ng-model="user.age" /></li>
<li><input type="text" name="occupation" ng-model="user.occupation" /></li>
<li><input type="button" name="register" ng-click="register()" value="REGISTER" /></li>
</ul>
</form>
<p><h2>{{status}}</h2></p>
</div>
The {{status}} mentioned above represents the $scope property in my Angular script.js file:
mydiary.controller('MyDiaryLogin', function($scope, $http){
$scope.user = {};
$scope.register = function(){
$http({
method: 'POST',
url: 'http://localhost:9091/Angular1/getData',
headers: {'Content-Type': 'application/json'},
data: $scope.user
}).success(function(data){
$scope.status = data;
});
};
I have created a servlet to retrieve data from the database. However, before reaching the servlet, an error occurs while trying to print some text in the console within the servlet. Upon clicking the REGISTER button, the browser console shows the following error:
POST http://localhost:9091/Angular1/getData 500 (Internal Server Error)
This error refers to the angular.js
library at the xhr.send(...)
function:
if (responseType) {
try {
xhr.responseType = responseType;
} catch (e) {
if (responseType !== 'json') {
throw e;
}
}
}
xhr.send(post || null);
}
For your information, here is the doPost method in my servlet class:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
try{
System.out.println("CALLING THE METHOD");
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/mydiary","root","");
String query = "SELECT * FROM users";
pstmt = cn.prepareStatement(query);
rs = pstmt.executeQuery();
String json = new Gson().toJson(rs);
response.setContentType("text/html");
out = response.getWriter();
out.write(json);
}
catch(Exception e){
e.printStackTrace();
}
try{
try{}
finally{
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(out!=null)
out.flush();
out.close();
if(cn!=null)
cn.close();
}
}
catch(Exception e1){
e1.printStackTrace();
}
}
I need assistance in identifying the root cause of this issue. Could there be any errors in the entire codebase I have developed? My main concern is regarding how to utilize Angular for displaying and returning JSON format data from a servlet?