从AngularJS

时间:2016-08-12 02:06:09

标签: java angularjs http servlets

我在为Json和AngularJS创建Java Servlet时正在学习本教程http://www.simplecodestuffs.com/angularjs-interacting-with-java-servlet-using-json/(您可以从页面底部下载源代码)。为了能够运行该项目,我导入了gson jar(http://repo1.maven.org/maven2/com/google/code/gson/gson/2.7/)。但是,点击我从服务器收到404未找到错误。有人可以解释一下有什么问题吗?

AngularJS:

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) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });

    };
};

网页:

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

Servlet:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.model.PersonData;

    public class AngularJsServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

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

型号:

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

    }

我测试了如果在Servlet中正确创建了json对象 - json正常工作。

服务器是Tomcat v.8

0 个答案:

没有答案