无法在AngularJS中获取servlet数据

时间:2017-11-23 06:13:22

标签: java angularjs gson

我需要通过AngularJS获取html中的servlet响应,当我点击按钮然后它应该联系servlet而我应该得到响应但它没有工作,请有人建议我哪里出错。我的代码是文件

的index.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<script>
var app = angular.module('myApp', []);
function MyController($scope, $http){
$scope.getDataFromServer = function() {$http({method : 'GET',
url : 'javaAngularJS'
}).success(function(data, status, headers, config) {
$scope.person = data;
}).error(function(data, status, headers, config) {
$scope.person = status;                 
});

};
};
</script>

</head>
<body>

<div ng-app="myApp" ng-controller="MyController">
<button ng-click="getDataFromServer()">Fetch data from server</button>
<p>First Name : {{person.firstName}}</p>
<p>Last Name : {{person.lastName}}</p>
</div> 

</body>
</html>

PersonData.java

package com.jaysons;
public class PersonData {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

AngularServlet.java。

package com.jaysons;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jaysons.PersonData;

public class AngularServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public AngularServlet() {
        super();
}
protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
        PersonData personData = new PersonData();
        personData.setFirstName("Mohaideen");
        personData.setLastName("Jamil");

        String json = new Gson().toJson(personData);
        response.setContentType("application/json");
        response.getWriter().write(json);
}
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" 
version="2.5">
<display-name>Angular DB</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AngularServlet</servlet-name>
<servlet-class>com.jaysons.AngularServlet</servlet-class>  
</servlet>
<servlet-mapping>
<servlet-name>AngularServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>

当iam尝试点击fetchFromServer按钮时,它应该让我获得servlet响应,但它没有在网页中显示html代码

0 个答案:

没有答案