从servlet获得json数据Ajax解析到前台网页

时间:2021-03-07 21:13:35


1.servlet代码从数据库查询数据,转换成json数据传到页面


package zzu.zsw.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import zzu.zsw.entity.News;
import zzu.zsw.service.NewsService;
import zzu.zsw.service.impl.NewsServiceImpl;

public class AllNewsAction extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
       //得到分页的页数
String pNumber = request.getParameter("page");
//得到每一页呈现的最多行数
String pLine = request.getParameter("rows");
//获取搜索关键字
String keyWords = request.getParameter("newsTitle");
//设置默认的值
Integer page=1;
Integer rows=10;
if(pNumber!=null)
page=Integer.parseInt(pNumber);
if(pLine!=null)
rows=Integer.parseInt(pLine);
if(keyWords==null){
keyWords="";
}
try{
NewsService newsS = new NewsServiceImpl();
List<News> allNews = newsS.showAllNews(rows, page, keyWords);
Integer newsNum = newsS.total(keyWords);

Map<String,Object> map=new HashMap<String,Object>();
//在此映射中关联指定键与指定值
map.put("total", newsNum);
map.put("rows", allNews);

Gson gson=new Gson();
String json = gson.toJson(map);
//System.out.println(json);
response.setContentType("application/json");

PrintWriter pw=response.getWriter();
pw.print(json);
//request.getRequestDispatcher("/News/listNews.jsp").forward(request, response);
}catch (Exception e) {
e.printStackTrace();
}
}
}


2.用Ajax加载数据,放到网页上


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
   <title>My JSP 'listNews.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link href="css/public.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    $.ajax({  
        type:"post",//请求方式   
        url:"${pageContext.request.contextPath}/AllNewsAction",//发送请求地址   
        dataType:'json',  
  
        //请求成功后的回调函数有两个参数   
        success:function(data){  
       
            var objs=eval(data); //解析json对象   
            var obj = objs.rows;  
          //  alert(objs.rows[0].newsId);  
            var table = $("#table");  
            table.empty();  
            table.append('<tr><th>编号</th><th>文章标题</th><th>所属类别</th><th>发表时间</th><th>操作</th></tr>');  
              
            if(obj==null || obj==""){  
                table.append('<tr><td colspan="5" style="text-align: center; color:red">暂无数据!</td></tr>');  
                //$("#page").hide();   
                return false;  
            }  
              //alert(obj.length);
              for(i in obj){  
                 table.append('<tr><td>'+obj[i].newsId+'</td>'+'<td>'+obj[i].newsTitle+'</td>'+'<td>'+(obj[i].newsType=="1"?"图片新闻":"文字新闻")+'</td>'+'<td>'+obj[i].newsDate+'</td><td>'+'<a href="ShowOneNewsAction?newsId='+obj[i].newsId+'">编辑</a>'+'</td></tr>');       
              }   
            
        }  
    });  
 
</script> 
  </head>  
  <body>
    <div id="list">
    <form name="action" method="post">
    <table width="100%" border="0" cellpadding="8" cellspacing="0" class="tableBasic" id="table">
     <tbody><tr>
      
      <th width="40" align="center">编号</th>
      <th align="left">文章标题</th>
      <th width="150" align="center">所属类别</th>
      <th width="80" align="center">发表时间</th>
      <th width="80" align="center">操作</th>
     </tr>
         </tbody></table>
    </form>
    </div>           
  </body>
</html>