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

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

Html+js代码:

<!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代码:

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代码:

<?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 条评论
登录 后参与评论

相关文章

来自专栏张善友的专栏

LINQ via C# 系列文章

LINQ via C# Recently I am giving a series of talk on LINQ. the name “LINQ via C...

2665
来自专栏张善友的专栏

Silverlight + Model-View-ViewModel (MVVM)

     早在2005年,John Gossman写了一篇关于Model-View-ViewModel模式的博文,这种模式被他所在的微软的项目组用来创建Expr...

2988
来自专栏我和未来有约会

Kit 3D 更新

Kit3D is a 3D graphics engine written for Microsoft Silverlight. Kit3D was inita...

2586
来自专栏我和未来有约会

Silverlight第三方控件专题

这里我收集整理了目前网上silverlight第三方控件的专题,若果有所遗漏请告知我一下。 名称 简介 截图 telerik 商 RadC...

4045
来自专栏杨龙飞前端

scrollto 到指定位置

2534
来自专栏张善友的专栏

Miguel de Icaza 细说 Mix 07大会上的Silverlight和DLR

Mono之父Miguel de Icaza 详细报道微软Mix 07大会上的Silverlight和DLR ,上面还谈到了Mono and Silverligh...

2717
来自专栏一个会写诗的程序员的博客

Spring Reactor 项目核心库Reactor Core

Non-Blocking Reactive Streams Foundation for the JVM both implementing a Reactiv...

2192
来自专栏落花落雨不落叶

canvas画简单电路图

63311
来自专栏张善友的专栏

Mix 10 上的asp.net mvc 2的相关Session

Beyond File | New Company: From Cheesy Sample to Social Platform Scott Hansel...

2597
来自专栏大内老A

The .NET of Tomorrow

Ed Charbeneau(http://developer.telerik.com/featured/the-net-of-tomorrow/) Exciti...

32010

扫码关注云+社区