1. 程式人生 > >springMvc+AJAX+JSON的增刪改查

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做的一個簡單增刪改查