AngularJs与Servlet进行通信

时间:2016-02-08 13:27:03

标签: angularjs database servlets

我正在编写一个多变的简单网页,它应该接受两个输入并插入数据库,但我试图使用AngularJs。 如果我不使用Angular,我可以与Servlet通信,它可以很好地工作,但是我不能用角度来做。 我在这里告诉你我项目的所有细节。 项目名称: AngularDb

的index.html

<body data-ng-app="noteApp">
<div>
    <form data-ng-control="noteCtrl" ng-submit="addNote()">
        <div class="nameContainer">
        Inserisci il nome: <input type="text" name="nome" data-ng-model="nome"><br>
        </div>
        <div class="noteContainer">
        Inserisci qui una nota: <textarea rows="5" cols="50" name="note" data-ng-model="note"></textarea>
        <br>
        <button>Invia dati</button>
        </div>

    </form>
</div>

controller.js

var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
 $scope.myNote = function() {}
 $scope.addNote = function () {
 $http({
   method: 'POST',
   url: 'http://localhost:8080/AngularDb/WebAppDbServlet',
   data: {"nome":$scope.nome, "note":$scope.note}
  })
 }
})

Servlet在(默认包)中 的 RegisterServlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

@WebServlet("/WebAppDbServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

       // JDBC driver name and database URL
       static final String JDBC_DRIVER = "org.gjt.mm.mysql.Driver";  
       static final String DB_URL = "jdbc:mysql://localhost:3306/fabio";

       //  Database credentials
       static final String USER = "root";
       static final String PASS = "*******";


    public RegisterServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        Connection conn=null;
        try{
            String Name = request.getParameter("nome");
            String Note = request.getParameter("note");
            Class.forName("org.gjt.mm.mysql.Driver");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            String sql = "INSERT INTO fabio.appunti (nome, note) values ('"+Name+"', '"+Note+"');";
            PreparedStatement psSql = conn.prepareStatement(sql);
            psSql.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }

}

的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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>AngularDb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/WebAppDbServlet</url-pattern>
  </servlet-mapping>
</web-app>

如果,而不是

<form data-ng-control="noteCtrl" ng-submit="addNote()">

我写这个

<form action="WebAppDbServlet" method="Post" data-ng-control="noteCtrl">

我知道它运作良好所以我知道问题与AngularJs有关。

2 个答案:

答案 0 :(得分:0)

试试这个

<form data-ng-control="noteCtrl">
 <div class="nameContainer">
    Inserisci il nome: <input type="text" name="nome" data-ng-model="data.nome"><br>
 </div>
 <div class="noteContainer">
    Inserisci qui una nota: <textarea rows="5" cols="50" name="note" data-ng-model="data.note"></textarea>
    <br>
 </div> 
 <button ng-click="addNote(data)>Invia dati</button>
</form>

然后在您的控制器中

 $scope.addNote = function (data) {
   //data should return an object of $cope.nome and $scope.note all in one object
   $http.post('/AngularDb/WebAppDbServlet', data,
    headers: {'Content-Type': 'application/json'})
   .then(
    function(response) { 
     console.log('success if post worked', response) 
    },
    function(error) { 
     console.error('error if error processing post', error);
    });
  }

答案 1 :(得分:0)

我通过一些修改得到了代码的答案,它对我来说很好用: HTML代码:

    <body data-ng-app="noteApp">
<div>
    <form action="RegisterServlet" method="Post" data-ng-control="noteCtrl">

        <div class="nameContainer">
        Name: <input type="text" name="nome" data-ng-model="nome"><br>
        </div>
        <div class="noteContainer">
        Note: <textarea rows="5" cols="50" name="note" data-ng-model="note"></textarea>
        <br>
        <button>Save</button>
        </div>

    </form>
</div>
<script>
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){

 $scope.addNote = function () {
 $http({
   method: 'POST',
   url: 'http://localhost:8080/AngularJsSample/RegisterServlet',
   data: {"name":$scope.nome, "note":$scope.note}
  })
 }
})
</script>
</body>
</html>

enter code here // Servlet代码

RegisterServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;

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


public class RegisterServlet extends HttpServlet {

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

        Connection conn=null;
        try{
            String Name = request.getParameter("nome");
            String Note = request.getParameter("note");
            PrintWriter out=response.getWriter();
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","swetha","shwe");
            out.println(conn);
            PreparedStatement pst=conn.prepareStatement("insert into sample values(?,?)");
            pst.setString(1,Name);
            pst.setString(2, Note);

            int i=pst.executeUpdate();
            out.println(i);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }

}