springmvc增删改查案例,实例分享

很多人都想要了解一下springmvc增删改查,下面的文章内容要给大家分享的是一个springmvc增删改查的实例,一起来了解一下吧。

MVC布局格式-1.MVC包的创建格式

MVC布局格式

2.创建实体类

package cn.ps.entity;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class MySqlUser
{
    private int id;
    @NotBlank(message = "学生姓名不能为空")
    private String name;
    @DecimalMin(value = "1", message = "年龄不能小于1岁")
    @DecimalMax(value = "130", message = "年龄最大为130岁")
    private String age;
    private String sex;
    @Pattern(regexp = ".+@.+\\..+", message = "邮箱格式错误")
    private String eamil;
    @Size(max = 11, min = 11, message = "手机号码必须为11位数")
    private String phone;
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getSex()
    {
        return sex;
    }
    public void setSex(String sex)
    {
        this.sex = sex;
    }
    public String getAge()
    {
        return age;
    }
    public void setAge(String age)
    {
        this.age = age;
    }
    public String getEamil()
    {
        return eamil;
    }
    public void setEamil(String eamil)
    {
        this.eamil = eamil;
    }
    public String getPhone()
    {
        return phone;
    }
    public void setPhone(String phone)
    {
        this.phone = phone;
    }
}

3.配置XML文件和资源文件

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--关联一个空的jsp-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 过滤springmvc的请求  将请求字符集修改为UTF-8-->
    <filter>
        <filter-name>fgf</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!-- 设置请求头-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--设置请求体-->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>fgf</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--
            springmvc 支持 rest风格
        -->
    <filter>
        <filter-name>httpFile</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>httpFile</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--
            中央处理器
        -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springweb.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
springweb.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: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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <context:component-scan base-package="cn"></context:component-scan>
    <context:property-placeholder location="classpath:/jdbc.properties"/>
    <!--启用验证-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbcDriver}"></property>
        <property name="url" value="${jdbcUrl}"></property>
        <property name="username" value="${jdbcUsername}"></property>
        <property name="password" value="${jdbcPassword}"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>
pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.ps</groupId>
    <artifactId>SpringMVCRest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.19.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.6.Final</version>
        </dependency>
    </dependencies>
    <!-- 设定tomcat一些参数  字符集 端口-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

4.数据的提取和业务的逻辑控制

控制层
package cn.ps.coutroller;
import cn.ps.entity.MySqlUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import cn.ps.service.EmpService;
import cn.ps.utils.PagerBean;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
@Controller
public class DataCoutroller
{
    @Autowired
    private EmpService service;
    /**
     * 多条件搜索
     *  传参   /emps?stu=1&curPage=2&pageNum=3
     * @param stu
     * @param curPage
     * @param pageNum
     * @param map
     * @return
     */
    @RequestMapping(value = "/emps", method = RequestMethod.GET)
    public String listEmp(String stu, String curPage, String pageNum, ModelMap map)
    {
        try
        {
            PagerBean < MySqlUser > pb = service.queryClass(stu, curPage, pageNum);
            map.put("pb", pb);
            return "/showemp.jsp";
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    public String addEmp(@Valid MySqlUser emp, Errors er, ModelMap map)
    {
        if (er.hasErrors())
        {
            return "/add.jsp";
        }
        service.addEmp(emp);
        return listEmp(null, null, null, map);
    }
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)
    public String updateEmp(@PathVariable String id, @Valid MySqlUser emp, Errors er, ModelMap map)
    {
        emp.setId(Integer.parseInt(id));
        if (er.hasErrors())
        {
            map.addAttribute("id", id);
            return "/update.jsp";
        }
        service.updateEmp(emp);
        return listEmp(null, null, null, map);
    }
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
    public String deleteEmp(@PathVariable String id, ModelMap map)
    {
        service.deleteEmp(id);
        return listEmp(null, null, null, map);
    }
}
dao层( 数据层)
package cn.ps.dao.impl;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.mysql.jdbc.StringUtils;
import cn.ps.dao.EmpDao;
import cn.ps.entity.MySqlUser;
@Repository
public class EmpDaoImpl implements EmpDao
{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public int countEmp(String name) throws SQLException
    {
        String sql = "SELECT count(*) as myCount FROM stu1";
        if (!StringUtils.isNullOrEmpty(name))
        {
            sql += " where name like '%" + name + "%'";
        }
        Map map = jdbcTemplate.queryForMap(sql);
        return Integer.parseInt(map.get("myCount")
            .toString());
    }
    public List < MySqlUser > queryClass(String name, int startIndex, int pageNum) throws Exception
    {
        String sql = "SELECT * FROM stu1";
        if (!StringUtils.isNullOrEmpty(name))
        {
            sql += " where name like '%" + name + "%'";
        }
        sql += " limit " + startIndex + "," + pageNum;
        List < MySqlUser > list = jdbcTemplate.query(sql, new BeanPropertyRowMapper < MySqlUser > (MySqlUser.class));
        return list;
    }
    public void addEmp(MySqlUser emp)
    {
        String sql = "insert into stu1(name,age,eamil,sex,phone) values(?,?,?,?,?)";
        jdbcTemplate.update(sql, emp.getName(), emp.getAge(), emp.getEamil(), emp.getSex(), emp.getPhone());
    }
    public void deleteEmp(String id)
    {
        String sql = "delete from stu1 where id=?";
        jdbcTemplate.update(sql, id);
    }
    public void updateEmp(MySqlUser emp)
    {
        String sql = "update stu1 set name=?,age=?,eamil=?,sex=?,phone=? where id=?";
        jdbcTemplate.update(sql, emp.getName(), emp.getAge(), emp.getEamil(), emp.getSex(), emp.getPhone(), emp.getId());
    }
}
Service层( 服务层)
package cn.ps.service.impl;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.ps.dao.EmpDao;
import cn.ps.entity.MySqlUser;
import cn.ps.service.EmpService;
import cn.ps.utils.PagerBean;
@Service
public class EmpServiceImpl implements EmpService
{
    @Autowired
    private EmpDao dao;
    public PagerBean < MySqlUser > queryClass(String name, String curPage, String pageNum) throws Exception
    {
        //第一次访问 没有当前页
        if (StringUtils.isEmpty(curPage))
        {
            curPage = "1";
        }
        if (StringUtils.isEmpty(pageNum))
        {
            pageNum = "10";
        }
        //转换成int类型
        int curPageIn = Integer.parseInt(curPage);
        int pageNumIn = Integer.parseInt(pageNum);
        int total = dao.countEmp(name);
        PagerBean < MySqlUser > pd = new PagerBean < MySqlUser > (curPageIn, pageNumIn, total);
        List < MySqlUser > queryClass = dao.queryClass(name, pd.getStartIndex(), pd.getPageNum());
        pd.setData(queryClass);
        return pd;
    }
    public void addEmp(MySqlUser emp)
    {
        dao.addEmp(emp);
    }
    public void deleteEmp(String id)
    {
        dao.deleteEmp(id);
    }
    public void updateEmp(MySqlUser emp)
    {
        dao.updateEmp(emp);
    }
}
``
`java
查询 jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
	table{
		border-collapse: collapse;
	}
	th{
		border: 1px solid #ccc;
	
	}
	td{
		border: 1px solid #ccc;
	}

</style>
</head>
<body>
	<form action="${pageContext.request.contextPath}/emps">
		学生姓名:<input type="text" name='stu'><input type="submit" value="查询">
        <input type="button" value="新增" onclick="window.location='${pageContext.request.contextPath}/add.jsp'">
	</form>
	<table style="width:80%">
		<tr>
			<td>id</td>
			<td>学生姓名</td>
			<td>年龄</td>
            <td>邮箱</td>
			<td>性别</td>
            <td>手机号码</td>
			<td>操作</td>
		</tr>
	<c:forEach  var="tt" items="${requestScope.pb.data}">
		<tr>
			<td>${tt.id}</td>
			<td>${tt.name}</td>
			<td>${tt.age}</td>
            <td>${tt.eamil}</td>
            <td>${tt.sex}</td>
            <td>${tt.phone}</td>
			<td><form action="${pageContext.request.contextPath}/emp/${tt.id}" method="post">
				<input type="hidden" name="_method" value="delete"/>
				<input type="submit" value="删除"/>&nbsp;
				<input type="button" value="修改"onclick="window.location='${pageContext.request.contextPath}/update.jsp?id=${tt.id}&name=${tt.name}&age=${tt.age}&eamil=${tt.eamil}&sex=${tt.sex}&phone=${tt.phone}'"/>

			</form>
			</td>
		</tr>
	</c:forEach> 
	</table>
	<a href="${pageContext.request.contextPath}/emps?curPage=${requestScope.pb.prePage}&stu=${param.stu}">上一页</a>
	<c:forEach var="i" begin="1" end="${requestScope.pb.totalPage}" step="1">
		<a href="emps?curPage=${i}">${i}</a>
	</c:forEach>
	当前页是:${requestScope.pb.curPage}  总页数是:${requestScope.pb.totalPage}  总条数是:${requestScope.pb.total}
	<a href="${pageContext.request.contextPath}/emps?curPage=${requestScope.pb.nextPage}&stu=${param.stu}">下一页</a>
</body>
</html>
新增(add.jsp) <
    % --
Created by IntelliJ IDEA.
User: Administrator
Date: 2018 - 11 - 07
Time: 上午 10: 47
To change this template use File | Settings | File Templates.
    -- % >
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/emp">
        <h1>新增学生</h1>
        <hr>
        学生姓名:<input type="text" name="name"><font color="red"><s:errors path="mySqlUser.name"></s:errors> </font><br/>
        年龄:<input type="text" name="age"><font color="red"><s:errors path="mySqlUser.age"></s:errors></font><br/>
        邮箱:<input type="text" name="eamil"><font color="red"><s:errors path="mySqlUser.eamil"></s:errors></font><br/>
        性别:<input type="text" name="sex"><br/>
        手机号码:<input type="text" name="phone"><font color="red"><s:errors path="mySqlUser.phone"></s:errors></font><br/>
        <input type="submit" value="提交">
        <input type="button" value="返回"onclick="window.location='${pageContext.request.contextPath}/emps'">
        <hr>
        
    </form>
</body>
</html>
修改(update.jsp) <
    % --
Created by IntelliJ IDEA.
User: Administrator
Date: 2018 - 11 - 07
Time: 上午 10: 47
To change this template use File | Settings | File Templates.
    -- % >
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/emp/${param.id==null?requestScope.id:param.id}">
        <input type="hidden" value="put" name="_method">
        <h1>修改学生</h1>
        <hr>
        学生姓名:<input type="text" name="name" value="${param.name}"><font color="red"><s:errors path="mySqlUser.name"></s:errors> </font><br/>
        年龄:<input type="text" name="age" value="${param.age}"><font color="red"><s:errors path="mySqlUser.age"></s:errors></font><br/>
        邮箱:<input type="text" name="eamil" value="${param.eamil}"><font color="red"><s:errors path="mySqlUser.eamil"></s:errors></font><br/>
        性别:<input type="text" name="sex" value="${param.sex}"><br/>
        手机号码:<input type="text" name="phone" value="${param.phone}"><font color="red"><s:errors path="mySqlUser.phone"></s:errors></font><br/>
        <input type="submit" value="提交">
        <input type="button" value="返回"onclick="window.location='${pageContext.request.contextPath}/emps'">
        <hr>
    </form>
</body>
</html>

更多的实例,请继续关注奇Q工具网的java实例栏目来进行了解吧。

推荐阅读:

java jdbc实现增删改查实例,如何实现?

hibernate增删改查语句该怎么实现?代码示例

springmvc单例bean线程安全怎么解决?解决方法分享