如何将表格数据导入角度控制器并将其传递给Serlvet?

时间:2019-05-27 09:35:19

标签: java angularjs

我有一个包含两个<select>标签的表单。 一个是年份列表,另一个是剂量列表。

当我选择这些选项时,可以使用ng-model在控制器中获取selectedYear,但无法获取selectedDosage。 当试图将这些数据发送到我的servlet时,它将返回null作为值。

任何建议,我都感激 JSON

Dosages:[
    {"name":"Tablet"},
    {"name":"Syrups and Suspension"},
    {"name":"Non-Antibiotic Capsules"},
    {"name":"Antibiotic Capsules"},
    {"name":"Dry Powder for Suspension"},
    {"name":"ORS"},
    {"name":"Antiseptics"}
]
Years:{"json1":"[
    {\"years\":2018},
    {\"years\":2017},
    {\"years\":2016},
    {\"years\":2015}]"

HTML

<form  ng-submit="Display()">

    <select class="form-control" ng-model="selectedYear">
        <option value="" selected disabled>Select Year</option>
        <option   ng-repeat="option in years" ng-value="{{option.years}}" >
          {{option.years}}
        </option>
    </select>
    <br>
    <select class="form-control" ng-model="selectedDo">
        <option value="" selected disabled>Select Dosage</option>
        <option  ng-repeat="option in section" ng-value="{{option.name}}"  >
          {{option.name}}
        </option>
    </select>

    <input type="submit" value="Submit"/>       
</form>

控制器

$scope.selectedDo;
$scope.selectedYear;
$scope.Display=function(){

    $window.alert($scope.selectedDo+"..."+ $scope.selectedYear);
    $http({
        method:"post",
        url:"/com.az.BusinessRatioAnalysis/SectionServlet",
        data:{
           year:$scope.selectedYear,
           dosage:$scope.selectedDo,
        }
    }).then(function(result){
        $window.alert("Ajex call failed" + result);                             
    });
};

Servlet

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String year=request.getParameter("year");
        String dosage=request.getParameter("dosage");
                System.out.println(year+".."+dosage);
    }


1 个答案:

答案 0 :(得分:0)

请尝试以下操作。

有效负载Bean类:

class Bean {
    Year year;
    Dosage dosage;
    //getters and setters
}

Servlet类:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    StringBuilder json = new StringBuilder();
    String str;
    while ((str = request.getReader().readLine()) != null) {
        json.append(str);
    }

    // Using Jackson
    ObjectMapper objectMapper = new ObjectMapper();
    Bean bean = objectMapper.readValue(json.toString(), Bean.class);

    System.out.println("Year ::" + bean.getYear());
    System.out.println("Dosage ::" + bean.getDosage());
}
如果是Maven项目,则

pom.xml文件,否则相应地添加jar:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

PS:以上代码中的忽略异常处理