AngularJS 500 server error

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?

Answer №1

If you're wondering how to transform a resultset into JSON, check out this handy class I created. The process is simple: just use jsonArr = ResultSetConverter.convert(result,"");

This class is designed to manage all SQL data types, so it's versatile for your needs.

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class ResultSetConverter {
 public static final Calendar tzUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));    

  public static JSONArray convert( ResultSet rs, String freitextlabel )
    throws SQLException, JSONException
  {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
   
    while(rs.next()) {
      int numColumns = rsmd.getColumnCount();
      JSONObject obj = new JSONObject();

      for (int i=1; i<numColumns+1; i++) {
        String column_name = rsmd.getColumnName(i);

        if(rsmd.getColumnType(i)==java.sql.Types.ARRAY){
         obj.put(column_name, rs.getArray(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT){
         obj.put(column_name, rs.getInt(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BOOLEAN){
         obj.put(column_name, rs.getBoolean(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BLOB){
            obj.put(column_name, rs.getBlob(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.DOUBLE){
            obj.put(column_name, rs.getDouble(column_name)); 
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.FLOAT){
            obj.put(column_name, rs.getFloat(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.INTEGER){
            obj.put(column_name, rs.getInt(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.NVARCHAR){
            obj.put(column_name, rs.getNString(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.VARCHAR){
           if (freitextlabel.length()>0 && column_name.equalsIgnoreCase("freitext"))
           obj.put(freitextlabel, rs.getString(column_name));
           else
           obj.put(column_name, rs.getString(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.TINYINT){
            obj.put(column_name, rs.getInt(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.SMALLINT){
            obj.put(column_name, rs.getInt(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.DATE){
            obj.put(column_name.concat("_js"), rs.getDate(column_name));
           }
           else if(rsmd.getColumnType(i)==java.sql.Types.TIMESTAMP){
           //obj.put(column_name.concat("_js"), rs.getTimestamp(column_name,tzUTC));  
           Timestamp ts = rs.getTimestamp(column_name,tzUTC);
          // obj.put (column_name, ts !=null ? new Date(ts.getTime)  : null); 
           obj.put(column_name.concat("_js"), ts != null ? new Date(ts.getTime()) : null);
           }
           else{
            obj.put(column_name, rs.getObject(column_name));
           }
         }

         json.put(obj);
       }

       return json;
     }
   }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Repeating SignalR Messages: Issue of Duplication when Stopping and Restarting

Whenever I stop and start the connection, messages sent to the client by the hub are duplicated. If I follow this sequence: $.connection.hub.stop() $.connection.hub.start() {...} and a message is sent from the server hub to the client, it is initially re ...

Verify JSON data from server using AngularJS

My understanding is that in Angular, the HTTP service has two checks for 'success' and 'error' when connecting to a service. I have already handled these checks as my first step. The issue I am facing now is with the data in my JSON fi ...

Getting the x-axis points on Google charts to start at the far left point

I have integrated the Google API for charts into my application and am using multiple charts on the same page. However, I am facing an issue with setting padding for the charts. When I include more data points, the chart area occupies more space in the div ...

Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work! I have included the $emit code in my click event to trigger a custom event. <h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)"> ...

Are there any alternatives to PHP for implementing an auto-complete search feature?

I have decided to focus on using HTML, MySQL, JavaScript, and jQuery for my project. Though I understand that learning PHP would be beneficial in the long run, I don't have enough time to master it all within a week. As for the server-side, I will be ...

Scrolling jqgrid to focus on the current day column and implementing a blinking effect on cells with stored data

I have a jqgrid with 38 columns of data, where the first 6 columns are frozen and the rest are unfrozen. Depending on the combo box selection, it shows either dates or months (see sample image here). After loading the grid, I want it to automatically scrol ...

Redirecting asynchronously in Node.js with no use of AJAX

I've been struggling with this issue for days and have already sought help, but nothing seems to be working. Whenever I attempt to redirect from a POST request in node, the browser doesn't respond. Here's how my app is structured: ./ confi ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

What is the best method to extract a specific value from a JSON object?

I have parsed a JSON file to extract data such as "Floor", "flat_no", and "Flat_id". Here is an example of the JSON structure: { "results": [ { "Flat_id": "1", "cat": "2", "Flat_no": "101", "Floor": "1", "Flat_t ...

Leverage object properties as data table field values in VueJS

In my current project, I am utilizing VueJS (version 2.5.9) to display and modify data tables within an administrative application. Initially, I used a basic Grid component for the data table, following an example provided here. However, I came across an e ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...

Begin counting starting from 1 all the way up to 24, then feel free

I've developed a counter that increments from 0 to 24, and once it reaches 24: setInterval(function(){DayAndNight()}, 1000); var iState = 12; function DayAndNight() { //console.log('test'); switch(iState) ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

Disable the full screen camera mode on iOS browsers while live streaming camera video

I recently completed a tutorial on capturing video streams from the front or rear camera of an iPhone using JavaScript. The tutorial can be found at this link. While testing the functionality on my desktop browser, everything worked perfectly. However, wh ...

Trouble encountered while setting up Firebase Auth for React Native by utilizing AsyncStorage

Trying to implement SMS authentication via Firebase has presented some challenges for me. Despite poring over the documentation and scouring Google for solutions, I've hit a dead end. My setup is pretty basic - just a single input field and a "Send" b ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

What is the best way to update HTML content using JSF reRender or Ajax load, and then rebind the updated DOM with AngularJS?

Let's analyze the following piece of code: <div id="dest"> <p>Original Content</p> <p>Some data</p> <ul> <li ng-repeat="i in items">{{i.name}}</li> </ul> </div> Alternatively, u ...