SSM整合
- jar包整合
Mybatis所需要的jar有(我这里使用的是Mybatis3.27)
首先是Mybatis的核心jar包:mybatis.jar。
然后是Mybatis的一些依赖包:这些包主要都是一些日志包
MySQL的驱动包:mysql-connection-java.jar
数据库连接池包:这里采用C3p0连接池com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
MyBatis整合Spring的jar包:mybatis-spring-1.2.2.jar
Spring所需要的jar包
Spring和SpringMVC所需要的核心包:
aop联盟的jar包:com.springsource.org.aopalliance-1.0.0.jar
切面编程的jar包:com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
在前端页面需要使用c标签所需要的jstl的包:jstl-1.2.jar
需求分析
从数据库中查询商品信息,并在首页显示所有的商品;首页提供对商品的删除、批量删除、修改商品等功能的实现。
数据准备:
创建工程并导入jar包:
通过MyBatis的逆向工程生成Java代码:
生成的JavaBean:Items
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
}
生成的ItemsExample类:
public class ItemsExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ItemsExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andPriceIsNull() {
addCriterion("price is null");
return (Criteria) this;
}
public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return (Criteria) this;
}
public Criteria andPriceEqualTo(Float value) {
addCriterion("price =", value, "price");
return (Criteria) this;
}
public Criteria andPriceNotEqualTo(Float value) {
addCriterion("price <>", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThan(Float value) {
addCriterion("price >", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThanOrEqualTo(Float value) {
addCriterion("price >=", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThan(Float value) {
addCriterion("price <", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThanOrEqualTo(Float value) {
addCriterion("price <=", value, "price");
return (Criteria) this;
}
public Criteria andPriceIn(List<Float> values) {
addCriterion("price in", values, "price");
return (Criteria) this;
}
public Criteria andPriceNotIn(List<Float> values) {
addCriterion("price not in", values, "price");
return (Criteria) this;
}
public Criteria andPriceBetween(Float value1, Float value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPriceNotBetween(Float value1, Float value2) {
addCriterion("price not between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPicIsNull() {
addCriterion("pic is null");
return (Criteria) this;
}
public Criteria andPicIsNotNull() {
addCriterion("pic is not null");
return (Criteria) this;
}
public Criteria andPicEqualTo(String value) {
addCriterion("pic =", value, "pic");
return (Criteria) this;
}
public Criteria andPicNotEqualTo(String value) {
addCriterion("pic <>", value, "pic");
return (Criteria) this;
}
public Criteria andPicGreaterThan(String value) {
addCriterion("pic >", value, "pic");
return (Criteria) this;
}
public Criteria andPicGreaterThanOrEqualTo(String value) {
addCriterion("pic >=", value, "pic");
return (Criteria) this;
}
public Criteria andPicLessThan(String value) {
addCriterion("pic <", value, "pic");
return (Criteria) this;
}
public Criteria andPicLessThanOrEqualTo(String value) {
addCriterion("pic <=", value, "pic");
return (Criteria) this;
}
public Criteria andPicLike(String value) {
addCriterion("pic like", value, "pic");
return (Criteria) this;
}
public Criteria andPicNotLike(String value) {
addCriterion("pic not like", value, "pic");
return (Criteria) this;
}
public Criteria andPicIn(List<String> values) {
addCriterion("pic in", values, "pic");
return (Criteria) this;
}
public Criteria andPicNotIn(List<String> values) {
addCriterion("pic not in", values, "pic");
return (Criteria) this;
}
public Criteria andPicBetween(String value1, String value2) {
addCriterion("pic between", value1, value2, "pic");
return (Criteria) this;
}
public Criteria andPicNotBetween(String value1, String value2) {
addCriterion("pic not between", value1, value2, "pic");
return (Criteria) this;
}
public Criteria andCreatetimeIsNull() {
addCriterion("createtime is null");
return (Criteria) this;
}
public Criteria andCreatetimeIsNotNull() {
addCriterion("createtime is not null");
return (Criteria) this;
}
public Criteria andCreatetimeEqualTo(Date value) {
addCriterion("createtime =", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotEqualTo(Date value) {
addCriterion("createtime <>", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThan(Date value) {
addCriterion("createtime >", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) {
addCriterion("createtime >=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThan(Date value) {
addCriterion("createtime <", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeLessThanOrEqualTo(Date value) {
addCriterion("createtime <=", value, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeIn(List<Date> values) {
addCriterion("createtime in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotIn(List<Date> values) {
addCriterion("createtime not in", values, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeBetween(Date value1, Date value2) {
addCriterion("createtime between", value1, value2, "createtime");
return (Criteria) this;
}
public Criteria andCreatetimeNotBetween(Date value1, Date value2) {
addCriterion("createtime not between", value1, value2, "createtime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
生成的Mapper接口类:ItemsMapper
public interface ItemsMapper {
int countByExample(ItemsExample example);
int deleteByExample(ItemsExample example);
int deleteByPrimaryKey(Integer id);
int insert(Items record);
int insertSelective(Items record);
List<Items> selectByExampleWithBLOBs(ItemsExample example);
List<Items> selectByExample(ItemsExample example);
Items selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByPrimaryKeySelective(Items record);
int updateByPrimaryKeyWithBLOBs(Items record);
int updateByPrimaryKey(Items record);
}
生成的Mapper接口的映射文件:ItemsMapper.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="com.lc.dao.ItemsMapper" >
<resultMap id="BaseResultMap" type="com.lc.po.Items" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="REAL" />
<result column="pic" property="pic" jdbcType="VARCHAR" />
<result column="createtime" property="createtime" jdbcType="TIMESTAMP" />
</resultMap>
<resultMap id="ResultMapWithBLOBs" type="com.lc.po.Items" extends="BaseResultMap" >
<result column="detail" property="detail" jdbcType="LONGVARCHAR" />
</resultMap>
<sql id="Example_Where_Clause" >
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause" >
<where >
<foreach collection="example.oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List" >
id, name, price, pic, createtime
</sql>
<sql id="Blob_Column_List" >
detail
</sql>
<select id="selectByExampleWithBLOBs" resultMap="ResultMapWithBLOBs" parameterType="com.lc.po.ItemsExample" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.lc.po.ItemsExample" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from items
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from items
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.lc.po.ItemsExample" >
delete from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.lc.po.Items" >
insert into items (id, name, price,
pic, createtime, detail
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=REAL},
#{pic,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{detail,jdbcType=LONGVARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.lc.po.Items" >
insert into items
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="price != null" >
price,
</if>
<if test="pic != null" >
pic,
</if>
<if test="createtime != null" >
createtime,
</if>
<if test="detail != null" >
detail,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="price != null" >
#{price,jdbcType=REAL},
</if>
<if test="pic != null" >
#{pic,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
#{createtime,jdbcType=TIMESTAMP},
</if>
<if test="detail != null" >
#{detail,jdbcType=LONGVARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.lc.po.ItemsExample" resultType="java.lang.Integer" >
select count(*) from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map" >
update items
<set >
<if test="record.id != null" >
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name != null" >
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.price != null" >
price = #{record.price,jdbcType=REAL},
</if>
<if test="record.pic != null" >
pic = #{record.pic,jdbcType=VARCHAR},
</if>
<if test="record.createtime != null" >
createtime = #{record.createtime,jdbcType=TIMESTAMP},
</if>
<if test="record.detail != null" >
detail = #{record.detail,jdbcType=LONGVARCHAR},
</if>
</set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExampleWithBLOBs" parameterType="map" >
update items
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
price = #{record.price,jdbcType=REAL},
pic = #{record.pic,jdbcType=VARCHAR},
createtime = #{record.createtime,jdbcType=TIMESTAMP},
detail = #{record.detail,jdbcType=LONGVARCHAR}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map" >
update items
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
price = #{record.price,jdbcType=REAL},
pic = #{record.pic,jdbcType=VARCHAR},
createtime = #{record.createtime,jdbcType=TIMESTAMP},
detail = #{detail}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.lc.po.Items" >
update items
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="price != null" >
price = #{price,jdbcType=REAL},
</if>
<if test="pic != null" >
pic = #{pic,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
createtime = #{createtime,jdbcType=TIMESTAMP},
</if>
<if test="detail != null" >
detail = #{detail,jdbcType=LONGVARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKeyWithBLOBs" parameterType="com.lc.po.Items" >
update items
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL},
pic = #{pic,jdbcType=VARCHAR},
createtime = #{createtime,jdbcType=TIMESTAMP},
detail = #{detail,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.lc.po.Items" >
update items
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL},
pic = #{pic,jdbcType=VARCHAR},
detail = #{detail},
createtime = #{createtime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
编写web.xml配置文件:
在web.xml配置文件中配置Spring的监听器和SpringMVC的控制器和解决POST乱码的过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>springmvc_demo03_ssm</display-name>
<!-- 添加编码过滤器,该编码过滤器主要功能是解决POST请求的编码风格 -->
<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>
<!-- 配置springmvc控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 默认加载方式 默认加载必须规范: * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
* 路径规范:必须在WEB-INF目录下面 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- 添加Spring配置文件位置和spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置spring配置文件applicationContext.xml
在spring配置文件中配置的主要有:开启注解扫描、数据源、配置SqlSessionFactory、配置MyBatis接口代理、配置事务管理。
<?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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.lc"></context:component-scan>
<!-- 第一步:配置数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db.driver}"></property>
<property name="jdbcUrl" value="${db.url}"></property>
<property name="user" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<!-- 第二步:配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!-- 配置Mybatis接口代理 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lc.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 第三步:配置事务管理 -->
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- aop编程 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lc.service.*.*(..))"/>
</aop:config>
</beans>
配置springmvc配置文件springmvc.xml:
springmvc配置文件需要开启注解扫描、开启springmvc注解、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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="com.lc"></context:component-scan>
<!-- 开启springmvc注解 -->
<mvc:annotation-driven>
</mvc:annotation-driven>
<!-- 配置sprigmvc视图解析器:解析逻辑试图 后台返回逻辑试图:index -->
<!--视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
创建Service层,并对商品的查询、修改等方法实现
service接口:ItemsService
public interface ItemsService {
//查询所有商品
List<Items> findAllItems();
//根据id查找商品
Items findItemById(Integer id);
//修改商品
void updateItems(Items items);
//删除商品
void deleteItem(Integer id);
}
service接口实现类:ItemsServiceImpl
@Service
public class ItemsServiceImpl implements ItemsService{
//注入dao层的mapper接口
@Resource
private ItemsMapper itemsMapper;
@Override
public List<Items> findAllItems() {
return itemsMapper.findAll();
}
@Override
public Items findItemById(Integer id) {
return itemsMapper.selectByPrimaryKey(id);
}
@Override
public void updateItems(Items items) {
itemsMapper.updateByPrimaryKey(items);
}
@Override
public void deleteItem(Integer id) {
itemsMapper.deleteByPrimaryKey(id);
}
}
在Service层中查询所有,该方法在MyBatis逆向工程中没有生成,因此,我们去添加:
//查询所有商品信息
List<Items> findAll();
在ItemsMapper.xml添加该sql:
<!-- 查询所有 -->
<select id="findAll" resultMap="BaseResultMap">
SELECT * FROM ITEMS
</select>
创建控制器类Controller并实现其方法:ItemsController
修改商品信息我采用的是REST风格
@Controller
@RequestMapping("/items")
public class ItemsController {
//注入Service层
@Resource
private ItemsService itmesService;
//查询所有商品
@RequestMapping("findAll")
public String findAllItems(Model model){
List<Items> itemsList = itmesService.findAllItems();
model.addAttribute("itemsList", itemsList);
return "itemsList";
}
//获取需要修改的商品并跳转到修改界面回显修改的类容
@RequestMapping("/editItem/{id}")
public String editItem(@PathVariable Integer id,Model model){
Items item = itmesService.findItemById(id);
model.addAttribute("item", item);
return "editItem";
}
//修改商品
@RequestMapping("updateItem")
public String updateItem(Items items){
itmesService.updateItems(items);
return "redirect:/items/findAll.do";//重定向到list.do
}
//删除商品
@RequestMapping("/deleteItem/{id}")
public String deleteItem(@PathVariable Integer id){
itmesService.deleteItem(id);
return "redirect:/items/findAll.do";
}
//批量删除商品
@RequestMapping("deleteItems")
public String deleteItems(Integer[] ids){
for(Integer id:ids){
itmesService.deleteItem(id);
}
return "redirect:/items/findAll.do";
}
}
编写前端页面:
前端商品展示页面:itemsList.jsp
这里没有对图片进行展示,因为在后面会等springmvc对文件上传另做笔记。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<c:set var="basePath" value="http://127.0.0.1:8080/ssmImageServer/uploadImage/"></c:set>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/items/deleteItems.do" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/>
<input type="submit" value="批量删除商品"/>
</td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>ID</td>
<td>商品名称</td>
<td>商品图片</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td><input type="checkbox" name="ids" value="${item.id}"/></td>
<td>${item.name }</td>
<td>
<img alt="商品图片" src="${basePath }${item.pic}" width="400px" height="300px">
</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/rest/items/editItem/${item.id}">修改</a>
<a href="${pageContext.request.contextPath }/rest/items/deleteItem/${item.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
前端商品修改页面:editItem.jsp
此处修改没有提供对图片的展示和上传等操作,后面会进行文件片上传另做笔记。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<c:set var="basePath" value="http://127.0.0.1:8080/ssmImageServer/uploadImage/"></c:set>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/items/deleteItems.do" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/>
<input type="submit" value="批量删除商品"/>
</td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>ID</td>
<td>商品名称</td>
<td>商品图片</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td><input type="checkbox" name="ids" value="${item.id}"/></td>
<td>${item.name }</td>
<td>
<img alt="商品图片" src="${basePath }${item.pic}" width="400px" height="300px">
</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/rest/items/editItem/${item.id}">修改</a>
<a href="${pageContext.request.contextPath }/rest/items/deleteItem/${item.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
启动Tomcat并查看效果:
商品展示:
商品修改: