Angular+servlet java实现前后端数据交互

2018-03-08 15:06:53 浏览数 (1)

      每学习一个新知识我都会想到的是用它来实现对数据的CRUD,Angularjs也不例外,而实现CRUD的前提就是前后端数据能够进行交互,下面我就展示一个简易的前后端交互代码

Html js代码:

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8">
<title>servlet angularjs数据交互</title>
 <script src="framework/angular-1.3.0.14/angular.js"></script>
  <script src="framework/jquery-1.9.1.js"></script>
</head>

<body ng-app="myApp">
    <div ng-controller="demo">
            <input type="button" value="提交" ng-click="submit()"/>
    </div>
<script>
	var app=angular.module("myApp", [])
	  app.config(['$httpProvider', function($httpProvider) {
	 		$httpProvider.defaults.headers.post["Content-Type"] =
         			"application/x-www-form-urlencoded";
 			 $httpProvider.defaults.
         		 transformRequest.unshift(function(data,headersGetter) {
                var key, result = [];
            	for (key in data) {
                 if (data.hasOwnProperty(key)) {
                     result.push(encodeURIComponent(key)   "="
                              encodeURIComponent(data[key]));
                 }
             }
             return result.join("&");
        });
}]); 
		app.controller("demo", function($scope,$http) {
            $scope.submit = function () {
                var url = "demo";
                var data = {"name": "你好"};
                $http.post(url, data).success(function (data){
                console.log(data);
            });
            };
    });
</script>
</body>
</html>

Java代码:

代码语言:javascript复制
package com.whpu;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo extends HttpServlet{
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println(name);
        PrintWriter pw = resp.getWriter();
        String jsonStr="{"value":"hello"}";
        pw.println(jsonStr);
    }
}

Web.xml代码:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>AngularJs</display-name>
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>com.whpu.Demo</servlet-class>
    </servlet>
</web-app>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/demo</url-pattern>
    </servlet-mapping>

  $http.post(url, data)data是一个json对象的参数,在后台通过request即可获取,然后你就可以进行相关处理,而后台传数据到前台

          PrintWriterpw = resp.getWriter();

          StringjsonStr="{"value":"hello"}";

          pw.println(jsonStr);

通过这三行代码将{"value":"hello"}这个字符串形式的json放入流中在前台通过回调的

        $http.post(url,data).success(function (data){

               console.log(data);

            });

即可访问data及上面{"value":"hello"}这个字符串,并且angularjs会自动解析成json对象

        至于上面的$httpProvider配置则是设置了一些头部属性,以便正确获取参数并防止乱码。启动服务器后,后台java获取的值是你好而前台获得的是一个json对象

至此前后台交互已经完成.

        备注:1、servlet和Angularjs相关的包注意引入

                   2、小白写博客,不喜勿喷

                   3、有什么更好的建议希望提出来

0 人点赞