我正在尝试使用Angularjs作为前端和servlet插入表单数据,并使用Mysql进行备份。我无法将数据从我的angularjs传递到servlet。当我单击“保存”按钮时,表单数据未插入数据库。 这是我的index.html
<div ng-app="myApp">
<form ng-controller="myCtrl">
Name: <input type="text" name="name" ng-model="data.name"><br>
Address: <textarea rows="5" cols="50" name="address" ng- model="data.address"></textarea>
<br>
<button ng-click="add(data)">Save</button>
</form>
<script>
var app=angular.module('myApp', [])
app.controller('myCtrl', function ($scope, $http){
$scope.add = function (data) {
$http.post('/AngularDb/RegisterServlet', 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);
});
}
});
</script>
</div>
这是我的servlet:RegisterServlet.java
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/hibernate";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
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("name");
String address = request.getParameter("address");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "INSERT INTO register (name, address) values ('"+name+"', '"+address+"');";
PreparedStatement psSql = conn.prepareStatement(sql);
psSql.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}