【javaweb】从数据库读取多条数据并求和 将结果送到前端html

sevlet代码实现

package com.zzxtit.system.servlet;

import java.io.IOException;
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;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zzxtit.util.DBUtil;

@WebServlet("/getTotalIncome.action")
public class getTotalIncome extends HttpServlet{
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		String idCard = request.getParameter("idCard");
		
		//System.out.println("进入servlet");
		String sql = "select sum(consume_money) as sum_consume_money from  t_order";
		
		QueryRunner qr = new QueryRunner(DBUtil.getDS());
		
		try {
			
			Object obj = qr.query(sql, new ScalarHandler()); 
			String totalMoney = String.valueOf(obj);
			//System.out.println(totalMoney);
			response.getWriter().write(totalMoney);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
}

注 :

(1) sql求和语句 select sum(consume_money) as sum_consume_money from  t_order

(2)注意ScalarHandler的使用

(3)前台 使用的ajax进入的servlet 所出使用response.getWriter().write(totalMoney);返回数据

(4)读取出来的数据是BigDecimal的格式,无法转为int格式的数据, 我们先将其转为String格式的数据,直接通过String类型的数据进行传递,直接将String类型的数据放到html的代码中。

 

前台ajax代码实现 :

$(function(){
		var sumMoney = 0;
		$.ajax({
			url : "${ctxpath}/getTotalIncome.action",
			type : "post",
			//dataType : "String",
			success : function(data){
				//alert("测试成功");
				//alert(data);
				//sumMoney = Number(data);
				//alert(sumMoney);
				//alert(data);
				document.getElementById("ordersum").innerHTML = data;
			},
			error : function(data){
				parseInt(data);
				alert(data);
			}
		})
	});

 

 

 

 

 

 

 

 

你可能感兴趣的:(【javaweb】从数据库读取多条数据并求和 将结果送到前端html)