Spring+MyBatis+SpringMVC
使用jar包 在WEB-INF下导入
配置文件
数据连接配置
uname=root
password=root
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8
app.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描 cn.bcsp.service包下的类,如果类上面有@servcie注解,Spring框架 帮助我们创建类的对象,并且将对象保存到spring容器中-->
<context:component-scan base-package="cn.bcsp.service"/>
<!--读取 db.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!--数据源: 管理数据库链接 dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="username" value="${uname}"/>
<property name="password" value="${password}"/>
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
</bean>
<!--sqlSessionFactory能够创建sqlSession,sqlSession是MyBatis的数据库链接 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations">
<list>
<value>classpath:cn/bcsp/mapper/*Mapper.xml</value>
</list>
</property>
</bean>
<!--
扫描cn.cn.bcsp.mapper包下的接口, 创建接口对应的MapperFactoryBean(MapperFactoryBean)
MapperFactoryBean 创建cn.cn.bcsp.mapper包下的接口对应的实现类
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.bcsp.mapper"/>
</bean>
<!--事务管理器: 管理事务-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--方法对应的事务策略-->
<tx:advice id="txadivce" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="set*" read-only="true" propagation="NEVER" timeout="-1"/>
<tx:method name="query*" read-only="true" propagation="NEVER" timeout="2"/>
<tx:method name="select*" read-only="true" propagation="NEVER" timeout="2"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!--使用aop的方式 配置事务-->
<aop:config>
<!--切点: 找到事务需要管理的方法 -->
<aop:pointcut id="pointcut1" expression="execution(* cn.bcsp.service..*.*(..))"/>
<!--织入操作: 方法 和 方法的事务策略 织入-->
<aop:advisor advice-ref="txadivce" pointcut-ref="pointcut1"/>
</aop:config>
</beans>
mybatis-config配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--自动映射级别:FULL -->
<settings>
<setting name="autoMappingBehavior" value="FULL"/>
</settings>
<!--cn.bcsp.pojo包下的类的别名是 类名(不包含包名)-->
<typeAliases>
<package name="cn.bcsp.pojo"/>
</typeAliases>
</configuration>
springmvc-配置
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!--开启 基于注解的方式 将请求映射到控制类中的方法上-->
<mvc:annotation-driven />
<!--如果用户的请求中包含 /statics/.... 请求映射到 /statics/文件夹中 -->
<!--
http://localhost:8080/statics/css/style.css
/statcis/css/style.css
-->
<mvc:resources mapping="/statics/**" location="/statics/"/>
<!--
扫描 cn.bcsp.controller包下的类,如果这些类上有@Controller注解,创建类的对象
将其保存到Spring容器中。如果一个类上加了@Controller注解,这个类就是控制器,此
类就可以处理用户的请求
-->
<context:component-scan base-package="cn.bcsp.controller"/>
<!--视图解析器: 逻辑视图 解析成 物理视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
</bean>
<!--全局异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="cn.bcsp.exception.LoginException">sysError</prop>
</props>
</property>
</bean>
</beans>
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">
<!--监听器:项目的启动 读取配置文件 app.xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app.xml</param-value>
</context-param>
<!--前端控制器-->
<servlet>
<servlet-name>dispatcherServelt</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServelt</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--过滤器-->
<filter>
<filter-name>characterEncoding</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>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
java类
没有数据表 按照属性名创建一个数据表 相信你自己一定可以的
package cn.bcsp.pojo;
import java.util.Date;
/**
* @Description: TODO
* @author: wangyue
* @date: 2021年07月16日 16:58
*/
public class Supplier {
private Long id;
private String supCode;
private String supName;
private String supDesc;
private String supContact;
private String supPhone;
private String supAddress;
private String supFax;
private Long createdUserId;
private Date createdTime;
private Date updatedTime;
private Long updatedUserId;
public Supplier(Long id, String supCode, String supName, String supDesc, String supContact, String supPhone, String supAddress, String supFax, Long createdUserId, Date createdTime, Date updatedTime, Long updatedUserId) {
this.id = id;
this.supCode = supCode;
this.supName = supName;
this.supDesc = supDesc;
this.supContact = supContact;
this.supPhone = supPhone;
this.supAddress = supAddress;
this.supFax = supFax;
this.createdUserId = createdUserId;
this.createdTime = createdTime;
this.updatedTime = updatedTime;
this.updatedUserId = updatedUserId;
}
public Supplier() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSupCode() {
return supCode;
}
public void setSupCode(String supCode) {
this.supCode = supCode;
}
public String getSupName() {
return supName;
}
public void setSupName(String supName) {
this.supName = supName;
}
public String getSupDesc() {
return supDesc;
}
public void setSupDesc(String supDesc) {
this.supDesc = supDesc;
}
public String getSupContact() {
return supContact;
}
public void setSupContact(String supContact) {
this.supContact = supContact;
}
public String getSupPhone() {
return supPhone;
}
public void setSupPhone(String supPhone) {
this.supPhone = supPhone;
}
public String getSupAddress() {
return supAddress;
}
public void setSupAddress(String supAddress) {
this.supAddress = supAddress;
}
public String getSupFax() {
return supFax;
}
public void setSupFax(String supFax) {
this.supFax = supFax;
}
public Long getCreatedUserId() {
return createdUserId;
}
public void setCreatedUserId(Long createdUserId) {
this.createdUserId = createdUserId;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public Long getUpdatedUserId() {
return updatedUserId;
}
public void setUpdatedUserId(Long updatedUserId) {
this.updatedUserId = updatedUserId;
}
}
mapper文件
package cn.bcsp.mapper;
import cn.bcsp.pojo.Supplier;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SupplierMapper {
//分页查询供货商信息
List<Supplier> selectSupplier(
@Param("supCode") String supCode,
@Param("supName") String supName,
@Param("startRow") int startRow,
@Param("pageSize") int pageSize);
//按条件查询供货商的总记录数
int count(@Param("supCode") String supCode,
@Param("supName") String supName);
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 配置命名空间,区别名称 -->
<mapper namespace="cn.bcsp.mapper.SupplierMapper">
<select id="count" resultType="int">
select count(1) FROM t_supplier
<trim prefix="where" prefixOverrides="and|or">
<if test="supName!=null and supName!=''">
and supName like concat('%', #{supName},'%')
</if>
<if test="supCode!=null and supCode!=''">
and supCode like concat('%', #{supCode},'%')
</if>
</trim>
</select>
<select id="selectSupplier" resultType="Supplier">
SELECT supCode,supName,supContact,supPhone,supFax FROM t_supplier
<trim prefix="where" prefixOverrides="and|or">
<if test="supName!=null and supName!=''">
and supName like concat('%', #{supName},'%')
</if>
<if test="supCode!=null and supCode!=''">
and supCode like concat('%', #{supCode},'%')
</if>
</trim>
limit #{startRow},#{pageSize}
</select>
</mapper>
这里引用了一个分页工具类
package cn.bcsp.util;
import java.util.ArrayList;
import java.util.List;
public class PageUtil<T> {
private int currentPage;
private int pageSize;
private int startRow;
private int totalCount;
private int totalPage;
private List<T> lists = new ArrayList<T>();
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
if (currentPage <= 0) {
currentPage = 1;
} else if (currentPage > this.getTotalPage()) {
if (this.getTotalPage() == 0) {
currentPage = 1;
} else {
currentPage = this.getTotalPage();
}
}
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if (pageSize <= 0) {
pageSize = 5;
}
this.pageSize = pageSize;
}
public int getStartRow() {
return (this.getCurrentPage() - 1) * this.getPageSize();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
if (this.getTotalCount() % this.getPageSize() == 0) {
return this.getTotalCount() / this.getPageSize();
} else {
return this.getTotalCount() / this.getPageSize() + 1;
}
}
public List<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
}
service
package cn.bcsp.service;
import cn.bcsp.pojo.Supplier;
import cn.bcsp.util.PageUtil;
public interface SupplierService {
PageUtil<Supplier> querySupplier(String supCode, String supName, int currentPage);
}
serviceImpl
package cn.bcsp.service;
import cn.bcsp.mapper.SupplierMapper;
import cn.bcsp.pojo.Supplier;
import cn.bcsp.util.PageUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Description: TODO
* @author: wangyue
* @date: 2021年07月16日 17:27
*/
@Service("supplierService")
public class SupplierServiceImpl implements SupplierService {
@Resource
private SupplierMapper supplierMapper;
@Override
public PageUtil<Supplier> querySupplier(String supCode, String supName, int currentPage) {
PageUtil<Supplier> pageUtil=new PageUtil<>(); //当前页的数数据
//总记录数
int totalCount=supplierMapper.count(supCode,supName);
pageUtil.setTotalCount(totalCount);
//每页显示的条数
pageUtil.setPageSize(5);
//当前页数
pageUtil.setCurrentPage(currentPage);
//每页开始条数
int startRow=pageUtil.getStartRow();
//当前页的数据
List<Supplier> list=
supplierMapper.selectSupplier(supCode,supName,startRow,pageUtil.getPageSize());
pageUtil.setLists(list);
return pageUtil;
}
}
controller调用
package cn.bcsp.controller;
import cn.bcsp.pojo.Supplier;
import cn.bcsp.service.SupplierService;
import cn.bcsp.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
/**
* @Description: TODO
* @author: wangyue
* @date: 2021年07月16日 17:33
*/
@Controller
@RequestMapping("/sys/supplier")
public class SupplierController {
@Resource
private SupplierService supplierService;
@RequestMapping("/list")
public String list(@RequestParam(name="querySupCode",defaultValue = "") String querySupCode,
@RequestParam(name="querySupName",defaultValue = "") String querySupName,
@RequestParam(name = "currentPage",defaultValue = "1") int currentPage,
Model model){
//分页以后的供货信息
PageUtil<Supplier> pageUtil=
supplierService.querySupplier(querySupCode,querySupName,currentPage);
model.addAttribute("pageUtil",pageUtil);
//保存查询的条件
model.addAttribute("querySupCode",querySupCode);
model.addAttribute("querySupName",querySupName);
return "supplier/list";
}
}
最终前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/head.jsp"%>
<div class="right">
<div class="location">
<strong>当前位置:</strong>
<span>供货商管理页面</span>
</div>
<div class="search">
<form method="get" action="${pageContext.request.contextPath }/sys/supplier/list">
<span>供货商编码:</span>
<input name="querySupCode" type="text" value="${querySupCode }">
<span>供货商名称:</span>
<input name="querySupName" type="text" value="${querySupName }">
<input type="hidden" name="currentPage" id="currentPage"/>
<input value="查 询" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath }/sys/supplier/toAdd">添加</a>
</form>
</div>
<!--供货商操作表格-->
<table class="supplierTable" cellpadding="0" cellspacing="0">
<tr class="firstTr">
<th width="10%">供货商编码</th>
<th width="20%">供货商名称</th>
<th width="10%">联系人</th>
<th width="10%">联系电话</th>
<th width="10%">传真</th>
<th width="10%">创建时间</th>
<th width="30%">操作</th>
</tr>
<c:forEach var="supplier" items="${pageUtil.lists }" varStatus="status">
<tr>
<td>
<span>${supplier.supCode }</span>
</td>
<td>
<span>${supplier.supName }</span>
</td>
<td>
<span>${supplier.supContact}</span>
</td>
<td>
<span>${supplier.supPhone}</span>
</td>
<td>
<span>${supplier.supFax}</span>
</td>
<td>
<span>
<fmt:formatDate value="${supplier.createdTime}" pattern="yyyy-MM-dd"/>
</span>
</td>
<td>
<span><a class="viewSupplier" href="javascript:;" supId=${supplier.id } supName=${supplier.supName }><img src="${pageContext.request.contextPath }/statics/images/view.png" alt="查看" title="查看"/></a></span>
<span><a class="modifySupplier" href="javascript:;" supId=${supplier.id } supName=${supplier.supName }><img src="${pageContext.request.contextPath }/statics/images/upd.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteSupplier" href="javascript:;" supId=${supplier.id } supName=${supplier.supName }><img src="${pageContext.request.contextPath }/statics/images/del.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="7" align="right">
${pageUtil.currentPage}/${pageUtil.totalPage} 页
<c:if test="${pageUtil.currentPage!=1}">
<a href="javascript:jump('1')">首页</a>
<a href="javascript:jump('${pageUtil.currentPage-1}')">上一页</a>
</c:if>
<c:if test="${pageUtil.currentPage!=pageUtil.totalPage}">
<a href="javascript:jump('${pageUtil.currentPage+1}')">下一页</a>
<a href="javascript:jump('${pageUtil.totalPage}')">尾页</a>
</c:if>
</td>
<script>
function jump(page){
document.getElementById("currentPage").value=page;
document.forms[0].submit();
}
</script>
</tr>
</table>
<input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
</div>
</section>
<!--点击删除按钮后弹出的页面-->
<div class="zhezhao"></div>
<div class="remove" id="removeProv">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain" >
<p>确定删除该供货商吗?</p>
<a href="#" id="yes">是</a>
<a href="#" id="no">否</a>
</div>
</div>
</div>
<%@include file="/WEB-INF/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/js/supplier/list.js"></script>