上一篇文章簡要介紹了將sping mvc加入整個框架,算是完成了ssm的集成。本節繼續前面的內容,結合spring mvc做一個簡單的增刪改查demo.
1.首先,重寫一下GeckoList.jsp頁面,稍微整了一下樣式,代碼如下所示。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath(); String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>geckoList</title>
<!-- css文件 -->
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap-theme.min.css">
<!-- js文件 -->
<script type="text/javascript" src="./static/js/jquery-1.11.0.js"></script>
<script type="text/javascript">
function MemAdd() { h = "geckoAdd"; location.href = h; } function deleteGecko(geckoId){ if (confirm('確定刪除?')){ $.ajax({ type : 'post', url : 'geckoDelete?geckoId='+geckoId, async : false, dataType : 'html', success : function(data) { if (data > 0) { alert("成功"); } else { alert("失敗") } location.href = "geckoList"; } }) } } </script>
</head>
<body>
<form>
<div class="row" style="text-align: center">
<div class="col-lg-5" style="font-size: 18px">
<strong>hello,welcome to gecko's world</strong>
</div>
<div class="col-lg-3 col-xs-offset-1">
<button type="button" class="btn btn-sm" onclick="MemAdd()">新增</button>
</div>
</div>
<div class="row">
<div class="col-lg-8 col-xs-offset-1">
<table class="table">
<tr>
<th>編號</th>
<th>名稱</th>
<th>創建時間</th>
<th>操作</th>
</tr>
<c:choose>
<c:when test="${not empty geckoList }">
<c:forEach items="${geckoList }" var="gecko" varStatus="vs">
<tr>
<td>${gecko.geckoId}</td>
<td>${gecko.geckoName}</td>
<td><fmt:formatDate type="both" dateStyle="medium" timeStyle="medium" value="${gecko.createTime}" /></td>
<td><a href="geckoEdit?geckoId=${gecko.geckoId}">編輯</a> <a href='javascript:void(0)' onclick="deleteGecko(${gecko.geckoId})">刪除</a></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise> 沒有相關數據 </c:otherwise>
</c:choose>
</table>
</div>
</div>
</form>
</body>
</html>
主要是加了新增,編輯和刪除按鈕,用於跳到相關的頁面。
訪問geckoList,顯示效果如下。
2.編寫前往新增頁面的controllers方法。前往新增頁面不用攜帶任何數據,直接跳轉即可。
@RequestMapping("geckoAdd") public ModelAndView geckoAdd() { return new ModelAndView("gecko/GeckoAdd"); }
繼續編寫頁面,新建一個GeckoAdd.jsp頁面,代碼如下。此處需要注意的是表單項的名字需與實體中元素的名字相對應。且用了hidden的標簽來傳遞參數。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath(); String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>geckoAdd</title>
<!-- css文件 -->
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap-theme.min.css">
<!-- js文件 -->
<script type="text/javascript" src="./static/js/jquery-1.11.0.js"></script>
<style type="text/css">
</style>
</head>
<body>
<h3>please add a gecko</h3>
<form id="thisForm" action="">
<input type="hidden" name="type" value="1" /> <input type="hidden" name="geckoType" value="1" />
<div class="row">
<span>geckoName:</span><input type="text" name="geckoName" />
</div>
<div class="row">
<button id="submit1" type="button" class="btn">提交</button>
<button id="submit2" type="button" class="btn">提交2</button>
</div>
</form>
</body>
<script type="text/javascript"> $("#submit1").click(function() { $.ajax({ type : 'post', url : 'geckoSave', data : $('#thisForm').serialize(), dataType : 'html', success : function(data) { if (data > 0) { alert("成功"); } else { alert("失敗") } location.href = "geckoList"; } }) }) $("#submit2").click(function() { $.ajax({ type : 'post', url : 'jsonDemo', data : $('#thisForm').serialize(), dataType : 'json', success : function(data) { alert(data.name); alert(data.age); } }) }) </script>
</html>
點擊新增按鈕,跳到如下頁面。
3.編寫保存的代碼,代碼如下。
@ResponseBody @RequestMapping("geckoSave") public String geckoSave(TGecko gecko, int type) { Integer result; if (type == 1) { result = geckoService.addGecko(gecko); } else { result = geckoService.updateGecko(gecko); } return result.toString(); }
這邊重點注意的是,我傳的參數是TGecko類型的,所以在頁面端的表單項必須是TGecko類型的成員屬性。
提交表單這邊采用了ajax模擬表單提交的方法,這樣存儲完數據以后我們可以根據自己的需要跳轉到不同的頁面。具體的js代碼就在jsp頁面中了。
4.編輯,要跳轉到編輯頁面的時候,必須將需要編輯的信息帶到頁面去,代碼如下。
@RequestMapping("geckoEdit") public ModelAndView geckoEdit(int geckoId) { TGecko gecko = geckoService.getGeckoById(geckoId); ModelAndView mv = new ModelAndView("gecko/GeckoEdit"); mv.getModel().put("gecko", gecko); return mv; }
頁面代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath(); String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>geckoAdd</title>
<!-- css文件 -->
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap-theme.min.css">
<!-- js文件 -->
<script type="text/javascript" src="./static/js/jquery-1.11.0.js"></script>
<style type="text/css">
</style>
</head>
<body>
<h3>please add a gecko</h3>
<form id="thisForm" action="">
<input type="hidden" name="type" value="2" /> <input type="hidden" name="geckoId" value="${gecko.geckoId}" />
<div class="row">
<span>geckoName:</span><input type="text" name="geckoName" value="${gecko.geckoName}" />
</div>
<div class="row">
<button id="submit1" type="button" class="btn">提交</button>
</div>
</form>
</body>
<script type="text/javascript"> $("#submit1").click(function() { $.ajax({ type : 'post', url : 'geckoSave', data : $('#thisForm').serialize(), dataType : 'html', success : function(data) { if (data > 0) { alert("成功"); } else { alert("失敗") } location.href = "geckoList"; } }) }) </script>
</html>
5.刪除
刪除較為簡單,同樣采用ajax的方式,返回刪除成功或者失敗,代碼如下。
@ResponseBody
@RequestMapping("geckoDelete")
public String geckoDelete(TGecko gecko) {
Integer result = geckoService.deleteGecko(gecko);
return result.toString();
}
至此,增刪改查都已經完了。下面貼出controllers和Service的完整代碼。
GeckoController.java
package com.m_gecko.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.m_gecko.entity.TGecko; import com.m_gecko.service.GeckoService; @Controller public class GeckoController { @Resource(name = "geckoService") private GeckoService geckoService; @RequestMapping("/getReq") public ModelAndView getReq(HttpServletRequest req) { String gecko = req.getParameter("gecko"); System.out.println(gecko); return null; } @RequestMapping("/setRes") public ModelAndView setRes(HttpServletResponse res) { String str = "這是一個響應,我要將它打印在瀏覽器上"; PrintWriter writer = null; res.setHeader("Content-type", "text/html;charset=UTF-8"); try { writer = res.getWriter(); writer.print(str); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); } finally { if (writer != null) writer.close(); } return null; } @RequestMapping("/goPage") public ModelAndView goPage(String geckoName) { ModelAndView mv = new ModelAndView(); mv.getModel().put("geckoName", geckoName); mv.setViewName("gecko/GoPage"); return mv; } @RequestMapping("geckoList") public ModelAndView geckoList() throws Exception { ModelAndView mv = new ModelAndView(); List<TGecko> geckoList = geckoService.getGeckoList(); mv.getModel().put("geckoList", geckoList); mv.setViewName("gecko/GeckoList"); return mv; } @RequestMapping("geckoAdd") public ModelAndView geckoAdd() { return new ModelAndView("gecko/GeckoAdd"); } @RequestMapping("geckoEdit") public ModelAndView geckoEdit(int geckoId) { TGecko gecko = geckoService.getGeckoById(geckoId); ModelAndView mv = new ModelAndView("gecko/GeckoEdit"); mv.getModel().put("gecko", gecko); return mv; } @ResponseBody @RequestMapping("geckoSave") public String geckoSave(TGecko gecko, int type) { Integer result; if (type == 1) { result = geckoService.addGecko(gecko); } else { result = geckoService.updateGecko(gecko); } return result.toString(); } @ResponseBody @RequestMapping("geckoDelete") public String geckoDelete(TGecko gecko) { Integer result = geckoService.deleteGecko(gecko); return result.toString(); } @ResponseBody @RequestMapping("jsonDemo") public String jsonDemo() { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "xdx"); jsonObject.put("age", "28"); return jsonObject.toString(); } }
GeckoService.java
package com.m_gecko.service; import java.util.List; import javax.annotation.Resource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Service; import com.m_gecko.dao.BaseDao; import com.m_gecko.entity.TGecko; import com.m_gecko.util.ParamModel; @Service("geckoService") public class GeckoService { @Resource(name="baseDao") private BaseDao<TGecko,Integer> baseDao; public TGecko getGeckoById(int geckoId){ return baseDao.getT("TGeckoMapper.selectByPrimaryKey", geckoId); } public int addGecko(TGecko gecko){ return baseDao.addT("TGeckoMapper.insertSelective", gecko); } public int deleteGecko(TGecko gecko){ return baseDao.deleteT("TGeckoMapper.deleteByPrimaryKey",gecko.getGeckoId()); } public int updateGecko(TGecko gecko){ return baseDao.updateT("TGeckoMapper.updateByPrimaryKeySelective", gecko); } public List<TGecko>getGeckoList() throws Exception{ return baseDao.findTList("TGeckoMapper.listGecko"); } public List<TGecko>getGeckoListByPm(ParamModel pm) throws Exception{ return baseDao.findTListByParam("TGeckoMapper.listGeckoByPm", pm); } public List<TGecko>getGeckoListByPm2(ParamModel pm) throws Exception{ return baseDao.findTListByParam("TGeckoMapper.listGeckoByPm2", pm); } public static void main(String args[]) throws Exception{ ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml"); GeckoService geckoService=(GeckoService) context.getBean("geckoService"); List<TGecko> geckoList=geckoService.getGeckoList(); for(TGecko gecko:geckoList){ System.out.println("查詢結果,geckoId:"+gecko.getGeckoId()+",geckoName:"+gecko.getGeckoName()+",geckoType:"+gecko.getGeckoType()); } // ParamModel pm=new ParamModel(); // pm.setType(1); // pm.setIsDel(0); // List<TGecko>geckoList=geckoService.getGeckoListByPm(pm); // for(int i=0;i<geckoList.size();i++){ // System.out.println(geckoList.get(i).getGeckoId()+","+geckoList.get(i).getGeckoName()); // } // List<TGecko>geckoList2=geckoService.getGeckoListByPm2(pm); // for(int i=0;i<geckoList2.size();i++){ // System.out.println(geckoList2.get(i).getGeckoId()+","+geckoList2.get(i).getGeckoName()+","+geckoList2.get(i).getCreateTime()); // }
} }
下一節我們學習一下spring mvc一些新的功能點。