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

What is the best method to modify the accurate phone number within my script?

I need help with a text format script. link HTML CODE: <label for="primary_phone">Primary Phone Number<span class="star">*</span></label> <br> <input type="text" name="primary_phone" id="primary_phone" class="_phone requ ...

What is the best way to retrieve the ID of the input element using a jQuery object?

After submitting a form with checkboxes, I retrieve the jQuery object containing the checked input elements. var $form = $(e.currentTarget); var $inputs = $form.find("input.form-check-input:checked") Here is an example of how the inputs are stru ...

Displaying various data sets from data tables created using Ajax on Highcharts

I am currently working on integrating multiple data series into Highcharts' plot. I want to retrieve the data from an ajax self-calling function, which would allow for almost real-time updates to the charts without redrawing the entire chart each time ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

Validation on the client side for a form that is displayed within a bootstrap modal using ajax technology

Within my ASP.Net Core application, I am faced with the need to utilize validation on both the server side and client side in a bootstrap modal form. While I have successfully implemented server side validation, I have encountered difficulties when it come ...

Changing Charset to UTF-8 for MySQL Tables Using Liquibase

My Liquibase changeset is as follows: <changeSet id="05192014.1525" author="h2"> <createTable tableName="network"> <column name="network_id" type="BIGINT(19) UNSIGNED"> <constraints nullable="false" ...

Difficulty encountered when positioning a container using BootStrap 4

As a newcomer to the world of web development, I encountered an issue while trying to align a container on my webpage. Despite my efforts to center the container using (line 30), the page seems to update but there is no visible change. Can anyone help me ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

Elevate your frontend development game with the powerful combination of Vue js 3

I've been attempting to add this dependency, but I keep receiving an error message stating that it doesn't exist and Vue 3 is unable to resolve the component. Click here to visit the npm page for vue-phone-number-input Any assistance you can pr ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

Determining if a path is within the same directory: a step-by-step guide

I need to check if the input path is located in the same folder or not Question: Is the input path in the same folder? For example, if my current path is f://learning/java and I am currently in a folder named java, then any path that directly belongs to ...

What is the best way to divide a string that includes commas into separate parts?

When splitting input strings by commas using .split(','), I encountered an issue with strings that contain commas within a single name. For example: "John, Smith". Typically, my strings appear like this: "Emily, Sasha Flora, Camille-O'neal" ...

Managing state in a live chat application

Currently seeking advice on managing state in a real-time messaging/chat app created with VueJS 2. The application is made up of multiple components as shown in the diagram below: Up to this point, I have successfully implemented the display of (fake) co ...

Create a custom key in SJCL that has an expiration time set for automatic deletion

My current project involves encrypting and decrypting data on the client-side using the SJCL library. However, I have a specific requirement that the encryption key must expire after a certain scheduled time. So my question is this: Can a key with an e ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Math variables enhancing Android computing

I am a beginner in android app development with some knowledge of Java. I have been tasked with creating an app that functions like a basic calculator, but with only two math operators (addition and subtraction) and involves variables x and y. For example, ...