springMvc+AJAX+JSON的增删改查

controller 层

package cn.et.springmvc.day6.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.et.springmvc.day5.dao.MoneyDaoImp;
import cn.et.springmvc.day6.dao.MyFoodDaoImpl;

@Controller
public class MyFoodController {
	
	@Autowired
	MyFoodDaoImpl mfdi;
	
	/**
	 * 查看菜品
	 * @param foodname
	 * @param os
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/queryFood",method={RequestMethod.GET})
	public String queryFood(String foodname,OutputStream os) throws Exception{
		List<Map<String, Object>> queryAllFood =mfdi.queryAllFood(foodname);
		JSONArray arry =JSONArray.fromObject(queryAllFood);
		String jsonStr =arry.toString();
		os.write(jsonStr.getBytes("UTF-8"));
		return null;
	}
	
	/**
	 * 删除菜品
	 * @param foodId
	 * @param os
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/food/{foodId}",method={RequestMethod.DELETE})
	public String deleteFood(@PathVariable String foodId,OutputStream os) throws Exception{
		try {
			mfdi.deleteFood(foodId);
			os.write("1".getBytes("UTF-8"));
		} catch (Exception e) {
			os.write("2".getBytes("UTF-8"));
		}
		return null;
	}
	
	/**
	 * 修改菜品
	 * @param foodId
	 * @param foodname
	 * @param price
	 * @param os
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/food/{foodId}",method={RequestMethod.PUT})
	public String updateFood(@PathVariable String foodId,String foodName,String price,OutputStream os) throws Exception{
		try {
			mfdi.updateFood(foodId, foodName, price);
			os.write("1".getBytes("UTF-8"));
		} catch (Exception e) {
			os.write("2".getBytes("UTF-8"));
		}
		return null;
	}
	
	
	/**
	 * 添加菜品
	 * @param foodname
	 * @param price
	 * @param os
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/food",method={RequestMethod.POST})
	public String saveFood(String foodName,String price,OutputStream os) throws Exception{
		try {
			mfdi.saveFood(foodName, price);
			os.write("1".getBytes("UTF-8"));
		} catch (Exception e) {
			os.write("2".getBytes("UTF-8"));
		}
		return null;
	}
}	

dao层

package cn.et.springmvc.day6.dao;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MyFoodDaoImpl {
	
	@Autowired
	JdbcTemplate jdbc;
	
	public void saveFood(String foodName,String price){
		String sql ="insert into food(foodname,price) values('"+foodName+"','"+price+"')";
		jdbc.execute(sql);
	}
	
	public void deleteFood(String foodId){
		String sql ="delete from food where foodId="+foodId;
		jdbc.execute(sql);
	}
	
	public void updateFood(String foodId,String foodName,String price){
		String sql ="update food set foodname='"+foodName+"',price='"+price+"' where foodid="+foodId;
		jdbc.execute(sql);
	}
	
	public  List<Map<String, Object>> queryAllFood(String foodname){
		String sql ="select * from food where foodname like '%"+foodname+"%'";
		return jdbc.queryForList(sql);
	}	
}


spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
	">
	<!-- 扫描文件 -->
	<context:component-scan base-package="cn.et.springmvc.day6"></context:component-scan>

	<!-- pringmvc 配置拦截 / 所有资源都被拦截 图片无法展示 将除控制层以外的资源交给servlet处理 -->
	<mvc:default-servlet-handler />

	<!-- 将springmvc注解的action交给springmvc处理 -->
	<mvc:annotation-driven />
	
	<!-- 将springmvc注解的action交给springmvc处理 -->
	<mvc:annotation-driven validator="localValidatorFactoryBean">
		<mvc:message-converters>
			<!-- 配置返回解析成json的消息转换器 -->
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html</value>
						<value>application/x-www-form-urlencoded</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	
	<!-- 扫描jdbc.properties -->
	<context:property-placeholder location="classpath:jdbc.properties" /> 
	
	<!-- 创建一个连接数据库的工具 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="${url}"></property>  <!-- 添加里面的属性 -->
		<property name="username" value="${userid}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClassName" value="${driverClass}"></property>
	</bean>

	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

</beans>


html页面

<%@ 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 'list.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">
		<script type="text/javascript">
/*
 封装的发送ajax的函数 
 *url 发送请求的地址
 *方法类型  get或者post
 *参数  通过 键=值&键=值 方式
 *回调函数 当结果返回后 自动调用的函数 第一个参数就是返回的结果
  function(responseText){
     	具体的逻辑(页面渲染)
  }
 */
function sendAjax(url, methodType, param, retnFunction) {
	//无刷新调用 http://localhost:8080/s/queryFood 获取到数据 数据通过dom方式添加到 table中
	//ajax(异步的ajax)+json
	var xmlhttp = null;
	//兼容所有的瀏覽器創建這個對象 XHR對象
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	//回調函數 當請求發送后 收到結果自動調用該方法
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			retnFunction(xmlhttp.responseText)
		}
	}
	if (methodType == "get" || methodType == "GET") {
		xmlhttp.open("GET", url + "?" + param, true);
		xmlhttp.send();
	} else {
		xmlhttp.open("POST", url, true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
		xmlhttp.send(param);
	}
}
/*
使用ajax
尽量使用 true 异步模式  (防假死)
尽量将获取数据之后的逻辑处理(页面渲染)放在回调函数中
 */

function query() {
	var foodname = document.getElementsByName("foodName")[0].value;
	sendAjax("${pageContext.request.contextPath}/queryFood","GET","foodname="+foodname,function(responseText){
            //返回的是字符串的json
			var resutlJson = responseText;
			//轉換為js對象
			var resultObj=JSON.parse(resutlJson);
			//获取表格对象
			var table=document.getElementById("myTable");
			//将所有名字为 dataTr的tr全部删除  [a,b,c]
			var allDataTr=document.getElementsByName("dataTr");
			var length=allDataTr.length;
			for(var i=0;i<length;i++){
			  table.removeChild(allDataTr[0]);
			}
			
			//根据json的行数追加多个tr
			for(var i=0;i<resultObj.length;i++){
				//查询
			   var obj=resultObj[i];
			   var td=document.createElement("td");
			   td.innerText=obj.foodname;
			   var td1=document.createElement("td");
			   td1.innerText=obj.price;
			   
			   
			   var td2=document.createElement("td");
			   //删除按钮
			   var ib=document.createElement("button");
			   ib.innerText="删除";
			   var ib1=document.createElement("button");
			   ib1.innerText="修改";
			   td2.appendChild(ib);
			   td2.appendChild(ib1);
			   var tr=document.createElement("tr");
			   //将当前行的json对象绑定到当前按钮上
			   ib.foodObj=obj;
			   //将当前行的tr绑定到当前按钮上
			   ib.myLineTr=tr;
			   
			   //删除按钮事件
			   ib.addEventListener("click",function(){
			      //获取当前按钮
			      var eventSrc=event.srcElement;
			      //删除当前行  + 发送ajax请求到后台 删除数据库
			      table.removeChild(eventSrc.myLineTr);
			      sendAjax("${pageContext.request.contextPath}/food/"+ib.foodObj.foodid,"POST","_method=delete",function(responseText){
			         if(responseText==1)
			            alert("删除成功");
			         else{
			            alert("删除失败");
			         }
			      });
			   });
			   
			   
			   ib1.foodObj=obj;
			   ib1.addEventListener("click",function(){
			       var eventSrc=event.srcElement;
			       document.getElementById('updateDiv').style.display='block';
			       document.getElementsByName("umyFoodName")[0].value=eventSrc.foodObj.foodname;
			       document.getElementsByName("umyFoodPrice")[0].value=eventSrc.foodObj.price;
			       document.getElementsByName("umyFoodId")[0].value=eventSrc.foodObj.foodid;
			       
			   })
			   
			   tr.setAttribute("name","dataTr");
			   tr.appendChild(td);
			   tr.appendChild(td1);
			   tr.appendChild(td2);
			   table.appendChild(tr);
			}
     })
}

/**
  新增的方法
**/
function saveFood(){
	//获取名称
   var myFoodName=document.getElementsByName("myFoodName")[0].value;
   //获取价格
   var myFoodPrice=document.getElementsByName("myFoodPrice")[0].value;
   //跳转
   sendAjax("${pageContext.request.contextPath}/food","POST","foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
         if(responseText==1){
            document.getElementById('addDiv').style.display='none';
            query();
            alert("新增成功");
         }else{
            alert("新增失败");
         }
	});
}

/**
  修改的方法
**/
function updateFood(){
	//获取名称
   var myFoodName=document.getElementsByName("umyFoodName")[0].value;
   //获取价格
   var myFoodPrice=document.getElementsByName("umyFoodPrice")[0].value;
   //获取id
   var myFoodId=document.getElementsByName("umyFoodId")[0].value;
   
   //跳转
   sendAjax("${pageContext.request.contextPath}/food/"+myFoodId,"POST","_method=put&foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
         if(responseText==1){
            document.getElementById('updateDiv').style.display='none';
            query();
            alert("修改成功");
            
         }else{
            alert("修改失败");
         }
	});
}
</script>
	</head>
	<body>
		<input type='text' name="foodName" />
		<input type='button' value="查询" onclick="query()">
		<input type='button' value="新增" onclick="document.getElementById('addDiv').style.display='block';">
		<table id="myTable">
			<tr>
				<th>
					菜品名
				</th>
				<th>
					菜品价格
				</th>
				<th>
					操作
				</th>
			</tr>
		</table>
	</body>

	<div id="addDiv"
		style="display: none; position: absolute; left: 40%; top: 40%; z-index: 100; border: 1px solid black; width: 250px; height: 100px">

		菜品名:
		<input type="text" name="myFoodName">
		<br />
		价   格:
		<input type="text" name="myFoodPrice">
		<br />
		<input type="button" value="保存" onclick="saveFood()">
		   
		<input type="button" value="关闭"
			onclick="document.getElementById('addDiv').style.display='none';">
		<br />
	</div>

	<div id="updateDiv"
		style="display: none; position: absolute; left: 40%; top: 40%; z-index: 100; border: 1px solid black; width: 250px; height: 100px">
		<input type="hidden" name="umyFoodId">
		菜品名:
		<input type="text" name="umyFoodName">
		<br />
		价   格:
		<input type="text" name="umyFoodPrice">
		<br />
		<input type="button" value="修改" onclick="updateFood()">
		   
		<input type="button" value="关闭"
			onclick="document.getElementById('updateDiv').style.display='none';">
		<br />
	</div>

以上就是用ajax加springmvc做的一个简单增删改查


猜你喜欢

转载自blog.csdn.net/Yang_Hui_Liang/article/details/79167438