从后台向前台传递数据,需将数据转化为json格式:JSONArray jsonArray = JSONArray.fromObject(list);
从前台向后台传递数据:都是以键值对的形式,一名称,一值,通过http中params属性来实现;
如从前台接收一名为bookName的参数,同时从后台向前台传递一个List<Book> 对象list的java代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setStatus(200);
String bookName = request.getParameter("bookName");//通过参数名称接收从前台传来的数据
String bookType = request.getParameter("bookType");
BookService bookService=new BookService();
List<Book> list = null;
List<Map<String,Object>> bookTypeList = null;
if(!"".equals(bookName)&&bookName != null){
bookTypeList = bookService.selectSomeBookByBookName(bookName);
list = getBookList(bookTypeList);
}else if(!"".equals(bookType)&&bookType != null){
int type = Integer.parseInt(bookType);
bookTypeList = bookService.selectSomeBookByBookType(type);
list = getBookList(bookTypeList);
}else{
bookTypeList = bookService.selectAllBooks();
list = getBookList(bookTypeList);
}
//System.out.println(bookTypeList);
JSONArray jsonArray = JSONArray.fromObject(list);
PrintWriter out = response.getWriter();
out.print(jsonArray);//将jsonArray从后台传到前台
}
对应前台向后台传递数据与后台接收数据js代码:
$http({
method : 'post',
url : '/AngularJsDemo/BookServlet',
params :{bookName:$scope.book.bookName}, // 传递数据作为字符串,从前台传到后台
}).success(function(data) {//这里的data,就是后台传递过来的数据jsonArray
}).error(function(data,status,headers,config){
alert("错误");
});