Spring MVC实例(增删改查)

数据库配置文件application-context-jdbc.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:jdbc="http://www.springframework.org/schema/jdbc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
    ">

        <!--配置mysql数据库-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName">
                <value>com.mysql.jdbc.Driver</value>
            </property>
            <property name="url">
                <value>jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=UTF-8</value>
            </property>
            <property name="username">
                <value>root</value>
            </property>
            <property name="password">
                <value>root</value>
            </property>
        </bean>

        <!--jdbcTemplate和数据库关联-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name = "dataSource" ref="dataSource"/>
        </bean>
    </beans>

表teacher的结构(tid自增,tno工号,tname姓名,dno部门号)

tid int auto_increment primary key,tno varchar(20),tname varchar(20),dno varchar(10)

分页类PageResult

package com.zyz.dao.base;

/**
 * Created by zyz on 2016-8-11.
 */
import java.io.Serializable;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

public class PageResult<T> implements Serializable {
    public static final int NUMBERS_PER_PAGE = 10;//默认每页10条记录
    //每页显示的记录数
    private int numPerPage;
    //记录总数
    private int totalRows;
    //总页数
    private int totalPages;
    //当前页码
    private int currentPage;
    //起始行数
    private int startIndex;
    //结束行数
    private int lastIndex;
    //结果集存放List
    private List<T> resultList;
    //JdbcTemplate jTemplate
    private JdbcTemplate jdbcTemplate;

    /**
     * 每页显示10条记录的构造函数,使用该函数必须先给Pagination设置currentPage,jTemplate初值
     * @param sql oracle语句
     */
    public PageResult(String sql){
        if(jdbcTemplate == null){
            throw new IllegalArgumentException("com.itbegin.dao.base.PageResult.jTemplate is null,please initial it first. ");
        }else if(sql.equals("")){
            throw new IllegalArgumentException("com.itbegin.dao.base.PageResult.sql is empty,please initial it first. ");
        }
        new PageResult<T>(sql,currentPage,NUMBERS_PER_PAGE,jdbcTemplate);
    }

    /**分页构造函数
     * @param sql 根据传入的sql语句得到一些基本分页信息
     * @param currentPage 当前页
     * @param numPerPage 每页记录数
     * @param jTemplate JdbcTemplate实例
     */
    public PageResult(String sql,int currentPage,int numPerPage,JdbcTemplate jTemplate){
        if(jTemplate == null){
            throw new IllegalArgumentException("com.deity.ranking.util.Pagination.jTemplate is null,please initial it first. ");
        }else if(sql == null || sql.equals("")){
            throw new IllegalArgumentException("com.deity.ranking.util.Pagination.sql is empty,please initial it first. ");
        }
        //设置每页显示记录数
        setNumPerPage(numPerPage);
        //设置要显示的页数
        setCurrentPage(currentPage);
        //计算总记录数
        StringBuffer totalSQL = new StringBuffer(" SELECT count(*) FROM ( ");
        totalSQL.append(sql);
        totalSQL.append(" ) totalTable ");
        //给JdbcTemplate赋值
        this.jdbcTemplate = jTemplate;
        //总记录数
        setTotalRows(getJdbcTemplate().queryForObject(totalSQL.toString(),Integer.class));
        //计算总页数
        setTotalPages();
        //计算起始行数
        setStartIndex();
        //计算结束行数
        setLastIndex();

        //装入结果集
        setResultList(getJdbcTemplate().queryForList(getMySQLPageSQL(sql,startIndex,numPerPage)));
    }



    /**
     * 构造MySQL数据分页SQL
     * @param queryString
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMySQLPageSQL(String queryString, Integer startIndex, Integer pageSize)
    {
        String result = "";
        if (null != startIndex && null != pageSize)
        {
            result = queryString + " limit " + startIndex + "," + pageSize;
        } else if (null != startIndex && null == pageSize)
        {
            result = queryString + " limit " + startIndex;
        } else
        {
            result = queryString;
        }
        return result;
    }



    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getNumPerPage() {
        return numPerPage;
    }

    public void setNumPerPage(int numPerPage) {
        this.numPerPage = numPerPage;
    }

    public List<T> getResultList() {
        return resultList;
    }

    public void setResultList(List resultList) {
        this.resultList = resultList;
    }

    public int getTotalPages() {
        return totalPages;
    }
    //计算总页数
    public void setTotalPages() {
        if(totalRows % numPerPage == 0){
            this.totalPages = totalRows / numPerPage;
        }else{
            this.totalPages = (totalRows / numPerPage) + 1;
        }
    }

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex() {
        this.startIndex = (currentPage - 1) * numPerPage;
    }

    public int getLastIndex() {
        return lastIndex;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //计算结束时候的索引
    public void setLastIndex() {
        //System.out.println("totalRows="+totalRows);///////////
        //System.out.println("numPerPage="+numPerPage);///////////
        if( totalRows < numPerPage){
            this.lastIndex = totalRows;
        }else if((totalRows % numPerPage == 0) || (totalRows % numPerPage != 0 && currentPage < totalPages)){
            this.lastIndex = currentPage * numPerPage;
        }else if(totalRows % numPerPage != 0 && currentPage == totalPages){//最后一页
            this.lastIndex = totalRows ;
        }
    }

    @Override
    public String toString() {
        return "totalRows:"+totalRows+" totalPages:"+totalPages+" currentPage:"+currentPage+resultList;
    }



}

 

实体类Model

package com.zyz.model;

/**
 * Created by zyz on 2016-8-3.
 */
public class Teacher {
    private int tid;
    private String tno;
    private String tname;
    private String dno;

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getTno() {
        return tno;
    }

    public void setTno(String tno) {
        this.tno = tno;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    public String getDno() {
        return dno;
    }

    public void setDno(String dno) {
        this.dno = dno;
    }
}

数据访问层DAO-TeacherDao

package com.zyz.dao;

import com.zyz.dao.base.PageResult;
import com.zyz.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zyz on 2016-8-3.
 */
@Repository
public class TeacherDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public PageResult<Teacher> queryPage(Integer currentPage,Integer numPerPage,Teacher teacher){
        StringBuffer sql=new StringBuffer();
        sql.append("select tid, tno,tname,dno from teacher where 1=1 ");
        if(teacher!=null){
            if(teacher.getTname()!=null && !teacher.getTname().equals("")){
                sql.append(" and tname like '");
                sql.append(teacher.getTname());
                sql.append("%' ");
            }
            if(teacher.getDno()!=null && !teacher.getDno().equals("")){
                sql.append(" and dno like '");
                sql.append(teacher.getDno());
                sql.append("%' ");
            }
        }
        sql.append(" order by tno asc");
        PageResult<Teacher> page=new PageResult<Teacher>(sql.toString(),currentPage,numPerPage,this.jdbcTemplate);
        return page;
    }
    public List<Teacher> getTeachers(){
        List<Teacher> teachers=new ArrayList<Teacher>();
        String sql="select tid, tno,tname,dno from teacher";
        teachers=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Teacher>(Teacher.class));
        return teachers;
    }
    public void addTeacher(Teacher teacher){
        String sql="insert into teacher(tno,tname,dno) values(?,?,?)";
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,teacher.getTno());
                ps.setString(2,teacher.getTname());
                ps.setString(3,teacher.getDno());
            }
        });
    }

    public Teacher getTeacher(int tid){
        String sql="select tid,tno,tname,dno from teacher where tid=?";
        Teacher teacher=jdbcTemplate.queryForObject(sql,new Object[]{tid},new BeanPropertyRowMapper<Teacher>(Teacher.class));
        return teacher;
    }

    public void update(Teacher teacher){
        String sql="update teacher set tno=?,tname=?,dno=? where tid=?";
        jdbcTemplate.update(sql,new Object[]{teacher.getTno(),teacher.getTname(),teacher.getDno(),teacher.getTid()});
    }

    public void delete(int tid){
        String sql="delete from teacher where tid=?";
        jdbcTemplate.update(sql,new Object[]{tid});
    }
}

业务逻辑层Service-TeacherService

package com.zyz.service;

import com.zyz.dao.TeacherDao;
import com.zyz.dao.base.PageResult;
import com.zyz.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by zyz on 2016-8-3.
 */
@Service
public class TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    public PageResult<Teacher> queryPageBusiness(Integer currentPage,Integer numPerPage,Teacher teacher){
        return teacherDao.queryPage(currentPage,numPerPage,teacher);
    }
    public List<Teacher> getTeachers(){
        return teacherDao.getTeachers();
    }
    public void addTeacher(Teacher teacher){
        teacherDao.addTeacher(teacher);
    }
    public Teacher getTeacher(int tid){ return teacherDao.getTeacher(tid);}
    public void update(Teacher teacher){teacherDao.update(teacher);}
    public void delete(int tid){teacherDao.delete(tid);}
}

控制层Controller-TeacherController

package com.zyz.action;

import com.zyz.api.Msg;
import com.zyz.dao.base.PageResult;
import com.zyz.model.Teacher;
import com.zyz.service.TeacherService;
import com.zyz.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by zyz on 2016-8-3.
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    private static final int PAGE_LIMIT=3;

    @RequestMapping(value = "/list",method =RequestMethod.GET)
    public String teacherInfo(String page,Model model){
        Integer currPage=1;
        if(page!=null && !page.equals("")){
            currPage=new Integer(page);
        }
        PageResult<Teacher> pageResult=teacherService.queryPageBusiness(currPage,new Integer(PAGE_LIMIT),new Teacher());
        model.addAttribute("pageUrl","/teacher/list?1=1");
        model.addAttribute("teachers",pageResult);
        return "/teacher/list";
    }
    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public String teacherFind(String tname,String dno,String page,Model model){
        Integer currPage = 1;
        if(page!=null && !page.equals("")){
            currPage = new Integer(page);
        }
        Teacher teacher=new Teacher();
        teacher.setTname(tname);
        teacher.setDno(dno);
        PageResult<Teacher> pageResult = teacherService.queryPageBusiness(currPage,
                new Integer(PAGE_LIMIT),teacher );
        model.addAttribute("pageUrl", "/teacher/find?1=1&tname="+tname+"&dno="+dno);
        model.addAttribute("teachers", pageResult);
        model.addAttribute("findTeacher", teacher);
        return "/teacher/list";
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String addTeacher(){
        return "/teacher/add";
    }

    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable String id,Model model){
        try {
            int tid=Integer.valueOf(id);
            Teacher teacher=teacherService.getTeacher(tid);
            model.addAttribute("teacher",teacher);
            return "/teacher/edit";
        }catch (NumberFormatException ex){
            return "/teacher/list";
        }
    }

    @RequestMapping(value = "/edit/save",method = RequestMethod.POST)
    public String update(@ModelAttribute("teacher") Teacher teacher, Model model){
        Map<String,Msg> msgs=new HashMap<>();
        if(StrUtil.isEmpty(teacher.getTno())){
            msgs.put("tno",new Msg("tno","工号不能为空."));
        }
        if(StrUtil.isEmpty(teacher.getTname())){
            msgs.put("tname",new Msg("tname","姓名不能为空."));
        }
        if(StrUtil.isEmpty(teacher.getDno())){
            msgs.put("dno",new Msg("dno","部门不能为空."));
        }
        try {
            if(msgs.isEmpty()){
                teacherService.update(teacher);
                model.addAttribute("success",new Msg("","更新成功."));
            }
        }catch (Exception ex){
            model.addAttribute("error",new Msg("","更新失败."));
        }
        model.addAttribute("msgs",msgs);
        model.addAttribute("teacher",teacher);
        return "/teacher/edit";
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public String delete(@PathVariable String id,Model model){
        try {
        int tid=Integer.valueOf(id);
            teacherService.delete(tid);
            model.addAttribute("success",new Msg("","删除成功."));
        }catch (Exception ex){
            model.addAttribute("error",new Msg("","删除失败:"+ex.getMessage()));
        }
        return teacherInfo("",model);
    }
}

数据检验-TeacherApi

package com.zyz.api;

import com.zyz.model.Teacher;
import com.zyz.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zyz on 2016-8-4.
 */
@RestController
@RequestMapping("/teacher")
public class TeacherApi {
    @Autowired
    private TeacherService teacherService;
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResponseData add(@RequestBody Teacher teacher){
        List<Msg> msgs=new ArrayList<Msg>();
        if(teacher.getTno()==null || teacher.getTno().equals("")){
            msgs.add(new Msg("tnoMsg","工号不能为空."));
        }
        if(teacher.getTname()==null || teacher.getTname().equals("")){
            msgs.add(new Msg("tnameMsg","姓名不能为空."));
        }
        if(teacher.getDno()==null || teacher.getDno().equals("")){
            msgs.add(new Msg("dnoMsg","部门号不能为空."));
        }
        if(msgs.size()==0){
            teacherService.addTeacher(teacher);
            return new ResponseData(true,"添加成功.");
        }else {
            return new ResponseData(false,"添加失败.",msgs);
        }
    }
}

分页定自义标签-pager.ftl

<#macro pager url totalPage curPage=1 showPageNum=4>
    <#if (totalPage?number > 1)>
    <div class="holder">
        <nav class="center">

            <ul class="pagination" pages="${totalPage}" id="ul">

                <li id="Previous" <#if curPage?number == 1>class="disabled"</#if>>
                    <a href="${url}?page=1" aria-label="Previous"> <span
                            aria-hidden="true">&laquo;</span>
                    </a>
                </li>

                <@pagercount url=url totalPage=totalPage curPage=curPage showPageNum=showPageNum/>

                <li id="Next" <#if curPage?number==totalPage?number>class="disabled"</#if>><a href="${url}?page=${totalPage}" aria-label="Next"> <span
                        aria-hidden="true">&raquo;</span>
                </a></li>
            </ul>
        </nav>
    </div>
    </#if>
</#macro>

<#macro pagercount url totalPage curPage showPageNum>


    <#local halfPage =(showPageNum/2)?int/>
    <#local curPage = curPage?number/>



    <#if (halfPage>=curPage)>
        <@showPage start=1 end=curPage curPage=curPage url=url />
        <#if (showPageNum > (totalPage?number))>
            <@showPage start=curPage+1 end=(totalPage?number) curPage=curPage url=url/>
        <#else>
            <@showPage start=curPage+1 end=showPageNum curPage=curPage url=url/>
        </#if>
    <#else>

        <#local startPage1 = (curPage-halfPage) />
        <#local startPage2 = curPage+1 />

        <#if ((curPage+halfPage)>(totalPage?number))>

            <#local endPage = (totalPage?number)/>

            <#if (showPageNum > (endPage-startPage1)+1)>
                <#local startPage1 = (curPage-halfPage)-1 />
                <#if startPage1 <= 0>
                    <#local startPage1 = (curPage-halfPage) />
                </#if>
            </#if>

        <#else>

            <#local endPage = curPage + halfPage/>

            <#if ((endPage-startPage1) >= showPageNum)>

                <#local startPage1 = startPage1+1 />

            </#if>
        </#if>

        <@showPage start=startPage1 end=curPage curPage=curPage url=url />
        <@showPage start=startPage2 end=endPage url=url curPage=curPage/>

    </#if>

</#macro>


<#macro showPage start end curPage url>

    <#if (end >= start) >

        <#list start..end as page>

        <li id="${(page)}" <#if curPage==page>class="active"</#if> >
            <a href="${url}&page=${page}" class="btn btn-default" role="button"><span>${(page)}
                <#if curPage==page> <span class="sr-only">(current)</span></span> </#if>
            </a>


        </li>

        </#list>
    </#if>
</#macro>

查-list.ftl

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>教师列表</title>
    <link rel="stylesheet" href="/css/common/bootstrap.min.css">
    <script src="/js/common/jquery.min.js"></script>
    <script src="/js/common/bootstrap.min.js"></script>
    <style>
        .msg{
            color: #f00;
        }
    </style>
</head>
<body>
<#include "../common/pager.ftl">
<h3 class="msg">
    <#if success?exists>${success.msg!}</#if>
    <#if error?exists>${error.msg!}</#if>
</h3>
<div>
    姓名:<input type="text" id="tname" name="tname" value="<#if (findTeacher.tname)??>${findTeacher.tname!}</#if>" >&nbsp;&nbsp;
    部门号:<input type="text" id="dno" name="dno"  value="<#if (findTeacher.dno)??>${findTeacher.dno!}</#if>">&nbsp;&nbsp;
    <input type="button" id="btnFind" value="查找" class="btn btn-primary">

    <input type="button" id="btnAdd" value="新增" class="btn btn-primary" onclick="window.location.href='/teacher/add'">
    <input type="button" id="btnModify" value="修改" class="btn btn-primary">
    <input type="button" id="btnDelete" value="删除" class="btn btn-primary">

</div>
<table class="table table-bordered table-hover">
    <tr>
        <th>#</th>
        <th>工号</th>
        <th>姓名</th>
        <th>部门号</th>
    </tr>
    <#list teachers.resultList as teacher>
        <tr>
            <td><input type="radio" name="teacher" value="${teacher.tid!}"></td>
            <td>${teacher.tno!}</td>
            <td>${teacher.tname!}</td>
            <td>${teacher.dno!}</td>
        </tr>
    </#list>
</table>
<nav>
    <!-- 显示分页 -->
<#if teachers?exists>
    <@pager url='${pageUrl}' totalPage='${teachers.getTotalPages()}' curPage='${teachers.getCurrentPage()}'/>
</#if>
</nav>
<script src="/js/teacher/list.js"></script>
</body>
</html>

查-list.js

/**
 * Created by zyz on 2016-8-11.
 */
$(function () {
    $("#btnFind").on("click",function () {
        var url="/teacher/find?tname="+$("#tname").val()+"&dno="+$("#dno").val();
        window.location.href=url;
    });
    $("#btnModify").on("click",function () {
        var id=$("input[name='teacher']:checked").val();
        if(id){
            window.location.href="/teacher/edit/"+id;
        }
    });
    $("#btnDelete").on("click",function () {
        var id=$("input[name='teacher']:checked").val();
        if(id){
            window.location.href="/teacher/delete/"+id;
        }
    });
})

增-add.ftl

<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>添加教师</title>
    <style>
        .msg{
            color:red;
        }
    </style>
</head>
<body>
    工号:<input type="text" id="tno"><span id="tnoMsg" class="msg"></span><br>
    姓名:<input type="text" id="tname"><span id="tnameMsg" class="msg"></span><br>
    部门号:<input type="text" id="dno"><span id="dnoMsg" class="msg"></span><br>
    <input type="button" id="add" value="添加">
    <script src="/js/common/jquery.min.js"></script>
    <script src="/js/teacher/add.js"></script>
</body>
</html>

增-add.js(Ajax提交)

/**
 * Created by zyz on 2016-8-2.
 */
$(function () {
    // 将所有class为msg的元素内容清空,这些元素通常提示错误信息的,每次提交前都要清除,以显示本次的信息
    function clearMsg() {
        $(".msg").html('');
    }
    //获取表单数据,返回一个json对象,准备提交给服务器,注意此处json对象的属性必须和对应model对象Person的属性名保持一致
    function formData() {
        return {
            tno:$("#tno").val(),
            tname:$("#tname").val(),
            dno:$("#dno").val()
        };
    }
    function add() {
        var url="/teacher/add";//通过该url找到对应api类的某个方法来接收ajax请求并作出响应(返回一个json对象)
        var data=formData();//此处的data是一个json对象
        clearMsg();
        $.ajax({
            type:'POST',//处理异步请求数据的api类@RequestMapping(value="/add",method=RequestMethod.POST)
            url: url,
            dataType:'json',
            contentType: 'application/json',
            data:JSON.stringify(data),
            //将一个json对象转换成json对象字符串,因为在api中参数@RequestBody接受的是一个json对象字符串,而不是一个json对象
            success:function (responseData) {//此处success是表示响应成功,即状态码为200,responseData参数表示返回的数据
                if(responseData.success==true){
                    //ResponseData是一个json对象,是由后台类(ResponseData(success,desc,msgs)类)的对象返回到前台形成的一个json对象,
                    // 此处的success仅表示该json对象的一个属性,
                    alert(responseData.desc);
                    window.location.href="/teacher/list";
                }else {//如果验证失败,则 显示错误信息
                    var msgs=responseData.msgs;
                    for(var i=0;i<msgs.length;i++){
                        $('#'+msgs[i].id).html(msgs[i].msg);
                    }
                }
            }
        });
    }
    // 定义一个初始化的方法
    function init() {
        $("#add").on("click",function () {//给添加按纽绑定事件
            add();
        });
    }
    init();//调用初始化事件
})

 改-edit.ftl

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>修改</title>
    <link rel="stylesheet" href="/css/common/bootstrap.min.css">
    <script src="/js/common/jquery.min.js"></script>
    <script src="/js/common/bootstrap.min.js"></script>
    <style>
        .msg{
            color: #f00;
        }
    </style>
</head>
<body>
<form action="/teacher/edit/save" method="post">
    <input type="hidden" name="tid" value="${teacher.tid!}">
    <#if success?exists >
        <h3 class="msg">${success.msg!}</h3>
    </#if>
    <#if error?exists >
        <h3 class="msg">${error.msg!}</h3>
    </#if>
    工号:<input type="text" name="tno" value="${teacher.tno!}">
    <#if msgs?exists>
        <#if msgs["tno"]?exists>
            <span class="msg">${msgs["tno"].msg!}</span>
        </#if>
    </#if>
    <br>
    姓名:<input type="text" name="tname" value="${teacher.tname!}">
    <#if msgs?exists>
        <#if msgs["tname"]?exists>
            <span class="msg">${msgs["tname"].msg!}</span>
        </#if>
    </#if>
    <br>
    部门:<input type="text" name="dno" value="${teacher.dno!}">
    <#if msgs?exists>
        <#if msgs["dno"]?exists>
            <span class="msg">${msgs["dno"].msg!}</span>
        </#if>
    </#if>
    <br>
    <input type="submit" value="保存" class="btn btn-primary">
    <input type="button" value="返回" class="btn btn-primary" onclick="window.location.href='/teacher/list'">
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/beast-king/p/5786752.html