上一篇文章简要介绍了将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>&nbsp;&nbsp;<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一些新的功能点。

ssm学习(四)--完整的增删改查demo的更多相关文章

  1. EF学习笔记-1 EF增删改查

    首次接触Entity FrameWork,就感觉非常棒.它节省了我们以前写SQL语句的过程,同时也让我们更加的理解面向对象的编程思想.最近学习了EF的增删改查的过程,下面给大家分享使用EF对增删改查时 ...

  2. python学习之-成员信息增删改查

    python学习之-成员信息增删改查 主要实现了成员信息的增加,修改,查询,和删除功能,写着玩玩,在写的过程中,遇到的问题,旧新成员信息数据的合并,手机号和邮箱的验证,#!/usr/bin/env p ...

  3. SSH登录与增删改查demo详解+源代码

    点击下载,测试绝对可用SSH整合框架登录加增删改查demo 下载地址:http://download.csdn.net/detail/qq_33599520/9784679   一.框架概述 spri ...

  4. 【讲义提纲】以一个实战新闻cms增删改查demo为例,给学院国创队伍培训php

    PHP实战基础——以一个新闻cms的增删改查为例 一.        环境配置 二.        数据库创建 三.        增删改查demo 连接数据库 <?php $link=mysq ...

  5. mvc模式jsp+servel+dbutils oracle基本增删改查demo

    mvc模式jsp+servel+dbutils oracle基本增删改查demo 下载地址

  6. mvc模式jsp+servel+jdbc oracle基本增删改查demo

    mvc模式jsp+servel+jdbc oracle基本增删改查demo 下载地址

  7. ztree--插件实现增删改查demo(完整版)

    ztree--插件实现增删改查demo(完整版) var setting = {                 async: {                     enable: true,  ...

  8. SQL Server学习之路(四):“增删改查”之“删”

    0.目录 1.前言 2.通过SSMS删除 3.通过SQL语句删除 3.1 删除单行数据 3.2 删除所有行数据 3.3 删除表和数据库 1.前言 增删改查都是对数据的操作,其中"删" ...

  9. IDEA+Maven 整合SSM框架实现简单的增删改查(新手入门,傻瓜操作)

    原博客地址:https://blog.csdn.net/khxu666/article/details/79851070 选用SSM框架的原因在目前的企业级Java应用中,Spring框架是必须的.S ...

随机推荐

  1. JVM命令

    jstack--jstack用于打印出给定的java进程ID或core file或远程调试服务的Java堆栈信息: jinfo--jinfo可以输出并修改运行时的java 进程的opts.用处比较简单 ...

  2. JavaWeb面试(七)

    61,JDBC访问数据库的基本步骤是什么?1,加载驱动2,通过DriverManager对象获取连接对象Connection3,通过连接对象获取会话4,通过会话进行数据的增删改查,封装对象5,关闭资源 ...

  3. better-scroll 实现tab栏目滑动当前高亮始终在可视区

    https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/#better-scroll better-scroll文档地址 如图 ,是我们要实现的 ...

  4. Java 读取 .properties 配置文件的几种方式

    Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配 ...

  5. win10环境下tensorflow-gpu安装

    踩了很多坑,浪费了一下午时间,在此记录一下. pip install tensorflow-gpu 然后下载安装cuda8.0 https://developer.nvidia.com/cuda-do ...

  6. sockt初级了解 感悟 一起打怪升级偶

    刚接触来谈谈对sockt基础的一点理解,多线性下次再发.也逛了逛博客,有一篇基础讲的停息在这推荐下sockt套接字编程全绍辉 首先贴下代码#服务器 import socket skt=socket.s ...

  7. 爬起点小说 day01

    先介绍下我自己爬起点小说的思路: 1.爬取所有的类型列表 a.链接存redis中 类型表:novel_list 具体每一种类型:bnovel_all_list(把novel_list和bnovel_l ...

  8. 《Flask Web开发——基于Python的Web应用开发实践》一字一句上机实践(上)

    目录 前言 第1章 安装 第2章 程序的基本结构 第3章 模板 第4章 Web表单 第5章 数据库 第6章 电子邮件 第7章 大型程序的结构   前言 学习Python也有一个半月时间了,学到现在感觉 ...

  9. ChatterBot之快速入门01

    本人运行环境为Python 3.5.2; 首先你需要导入chatterbot 的包,如果没有你先需要下载 使用命令 pip install chatterbot 1 # -*- coding: utf ...

  10. 《Linux命令行与shell脚本编程大全》第二十二章 gawk进阶

    gawk是一门功能丰富的编程语言,你可以通过它所提供的各种特性来编写好几程序处理数据. 22.1 使用变量 gawk编程语言支持两种不同类型的变量: 内建变量和自定义变量 22.1.1 内建变量 ga ...