自学jsp+servlet+ajax的一些知识的总结

1、Servlet+JSP+EL 表达式语言;
服务端 返回list 
客服端 接收list
request.setAttribute("lists", list);
<td>${requestScope.lists}</td>
<td>${requestScope.lists[0]}</td>//但是显示的是一个数组,是否需要for循环取出数组中的没一个值呢? 再用JSTL标签C forecho 遍历


服务端 返回Json 数据的list 
客服端 接收Json 数据的list   //需要引入JAR 包 引入commons-beanutils.jar、commons-collections.jar、ezmorph-1.0.6.jar、json-lib-2.3-jdk15.jar、commons-lang.jar、commons-logging-1.1.1.jar包
request.setAttribute("lists", list);
<td>${requestScope.lists}</td>
<td>${requestScope.lists[0]}</td>//但是显示的是一个数组,是否需要for循环取出数组中的没一个值呢? 再用JSTL标签C forecho 遍历

Json 数据转换为xml格式数据
JSONArray jobj = JSONArray.fromObject(json);
String xml =  new XMLSerializer().write(jobj);
System.out.println(xml);
//需要引入JAR 包 引入xom-1.1.jar包

*服务端 返回Session 数据的list【未完成】
*客服端 接收Session 数据的list【未完成】




2、Servlet+JSP+JSTL标签库   服务端遍历list
ResultSet rs = stat.executeQuery(sql);
//List<String> list= new ArrayList<String>();
ResultSetMetaData rm = rs.getMetaData();//获取数据库中字段的名称、字段的值和属性
   List<Address> list = new ArrayList<Address>();//存放数据库中的数据
   while (rs.next()) {//一个遍历数据中的数据,直到字段对应的值为null为止
       //Map<String, Object> m = new HashMap<String, Object>();//使用Map的键值对,来对数据库中的字段和字段对应的值进行存储
       Address  add = new Address();
       add.setIDS(rs.getObject(1).toString());
       add.setUsername(rs.getObject(2).toString());
list.add(add);//把Map集合的键值存放到List集合中
   }
   rs.close();//对用的完的资源进行关闭
   stat.close();
   db.getConn().close();
  request.setAttribute("lists", list);//把List集合中数据放到request的域中
  request.getRequestDispatcher("index.jsp").forward(request, response);
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

//-------------------**************  ---JSP页面
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
//导入包 C标签需要的2个包
<table width="600px" height="100px" border="1px">
        <c:forEach items="${lists}" var="add" >
<tr height="10px">
<td>${add.IDS}</td>
<td>${add.username}</td>
<td>${add.sex}</td>
<td>${add.company}</td>
<td>${add.department}</td>
<td>${add.telphone}</td>
<td>${add.e_mail}</td>
<td>${add.qq}</td>
</tr>
</c:forEach>
</table>

3、Servlet+JSP+JSP小程序片段<%>、<%=%>、<%!声明%>
//-----------JSP 页面---********************
<%@ page language="java" import="java.util.*" import ="bean.BaseInformation"%>
<% ArrayList list=(ArrayList)request.getAttribute("lists");%>
<table width="100%" border="1" 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>
<% for(int i=0;i<list.size();i++){
BaseInformation aa = (BaseInformation)list.get(i);%>
<tr>
     <td><%=aa.getIds()%></td>
     <td><%=aa.getUserName()%></td>
     <td><%=aa.getAge()%></td>
     <td><%=aa.getBortAddress()%></td>
     <td><%=aa.getBorthDay()%></td>
     </tr>
    <%}%>
     </tbody>
     </table>
 
 
//------------------------- ajax 按钮绑定事件 请求查询 
<script type="text/javascript">
$(function () {
$("#sub").click(function () {
$.ajax({
                //cache: false,
                type: "post",
                url:"http://localhost:8080/jquerydemo/ismy.do?"+Math.random(),
                //dataType:"json",
                //data:$('#form1').serialize(),// 你的formid
                async: true,
                success: function(data) {
                    $("#commonLayout").html(data);
                }, error: function() {
                alert("未获取到数据!");
                }
            })
    })
})


</script>



4、Servlet+JSP+JQurey Ajax 异步请求获取数据 --默认展示数据--------  I N G
//--------------------Servlet 代码
public void doPost(HttpServletRequest request, HttpServletResponse response) { 
response.setContentType("text/html;charset=utf-8");
try { 
    String userStr = readJSONString(request);//得到requestContext 
    JSONObject jsonObj = JSONObject.fromObject(userStr);//转换成JSONObject 
    System.out.println(jsonObj.getInt("userId"));//得到JSONObject的userId值 
    System.out.println(jsonObj.getString("name")); 
    jsonObj.put("sex", "男");//用put方法给json0bj添加元素
    System.out.println(jsonObj);
    JSONObject resultJSON = new JSONObject();//构建一个JSONObject 
    resultJSON.accumulate("errNum", "传给客服端的信息"); //累积到对象中
    resultJSON.accumulate("errInfo", "输出成功"); 
    response.setContentType("application/x-json");//需要设置ContentType 为"application/x-json" 
    PrintWriter out = response.getWriter(); 
    System.out.println(resultJSON);
    out.print(jsonObj.toString());
    //out.println(resultJSON.toString());//向客户端输出JSONObject字符串 
    out.flush(); 
    out.close(); 
   } catch (Exception e) { 
    e.printStackTrace(); 
   } 



/** 
* Initialization of the servlet. <br> 

* @throws ServletException 
*             if an error occure 
*/ 
public void init() throws ServletException { 
   // Put your code here 

public String readJSONString(HttpServletRequest request){ 
   StringBuffer json = new StringBuffer(); 
   String line = null; 
   try { 
   BufferedReader reader = request.getReader(); 
   while((line = reader.readLine()) != null) { 
   json.append(line); 
   } 
   } 
   catch(Exception e) { 
   System.out.println(e.toString()); 
   } 
   return json.toString(); 
   } 


}    


//传值 默认展示数据--------
<script type="text/javascript">   
function User(userId, name) {  
   this.userId = userId;  
   this.name = name;  
}  
function requestServlet() { 
   var urlStr = "http://localhost:8080/jquerydemo/ismy.do";  
   var user = JSON.stringify(new User(101, "阿猫"));  
   //调用JQuery提供的Ajax方法   
   $.ajax( {  
       type : "POST",  
       url : urlStr,  
       data : user,  
       dataType : "json",
       success : function(data,status){  
           //$("#commonLayout").html(data.errNum+"\t"+data.errInfo);
           $("#form1").html(data.userId+"\t"+data.name+"\t"+data.sex);
           console.log('添加成功');
       }, error: function() {
        $("#form1").html("调用错误,未获取到数据data");
        console.log('不正确');
            }
   });//回调函数   
}  
 
requestServlet(); 
</script>   
//----------------------  不传值  默认展示数据-------- 异步请求获取数据
<script type="text/javascript">   
/* function User(userId, name) {  
   this.userId = userId;  
   this.name = name;  
}   */
function requestServlet() { 
   var urlStr = "http://localhost:8080/jquerydemo/ismy.do";  
   //var user = JSON.stringify(new User(101, "阿猫"));  
   //调用JQuery提供的Ajax方法   
   $.ajax( {  
       type : "POST",  
       url : urlStr,  
      // data : user,  
       dataType : "json",
       success : function(data,status){ 
        //$("#form1").html(data);
           $("#commonLayout").html(data.errNum+"\t"+data.errInfo);
           //$("#form1").html(data.userId+"\t"+data.name+"\t"+data.sex);
           console.log('添加成功');
       }, error: function() {
        $("#form1").html("调用错误,未获取到数据data");
        console.log('不正确');
            }
   });//回调函数   
}  
 
requestServlet(); 
</script>   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值