xdxxdx
www.xdxxdxxdx.com

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

 

posted on 2017-06-15 11:17  xdxxdx  阅读(3098)  评论(0编辑  收藏  举报