angularjs 500内部错误

时间:2015-11-27 13:57:17

标签: javascript java angularjs servlets

我正在编写一个简单的 angularjs - J2EE 应用程序来从 mysql服务器获取数据并显示在html页面上。 我在表单上调用角度函数提交为:

<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>

{{status}} 这里是来自我的angular script.js的$ scope属性:

mydiary.controller('MyDiaryLogin', function($scope, $http){
$scope.user = {};
$scope.register = function(){
    $http({
          method: 'POST',
          url: 'http://localhost:9091/Angular1/getData',
          header: {'Content-Type': 'application/json'},
          data: $scope.user
    }).success(function(data){
        $scope.status = data;
    });
};

我已经编写了一个servlet来从数据库中获取数据,但是当我在servlet中的控制台上打印一些文本时,错误就到达了servlet。 当我点击 REGISTER 按钮时,浏览器控制台会显示错误

  

POST http://localhost:9091/Angular1/getData 500(内部服务器错误)

并且此错误指向某个angular.js函数的xhr.send(...) lib:

if (responseType) {
    try {
      xhr.responseType = responseType;
    } catch (e) {
      // WebKit added support for the json responseType value on 09/03/2013
      // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
      // known to throw when setting the value "json" as the response type. Other older
      // browsers implementing the responseType
      //
      // The json response type can be ignored if not supported, because JSON payloads are
      // parsed on the client-side regardless.
      if (responseType !== 'json') {
        throw e;
      }
    }
  }

  xhr.send(post || null);
}

供您参考我的 servlet类的doPost方法

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();
    }
}

请帮我找到问题的根源,我写完整的应用程序代码有什么问题吗?我不确定如何使用angular来显示来自servlet的数据/返回json格式数据?

1 个答案:

答案 0 :(得分:0)

为了让您了解如何将结果集转换为JSON,我在此处添加了此类。您可以使用它:jsonArr = ResultSetConverter.convert(result,&#34;&#34;);

这是一个非常通用的类,可以处理所有的sql数据类型,所以选择你需要的东西。

&#13;
&#13;
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;
     }
   }
&#13;
&#13;
&#13;