SpringMVC,MyBatis商品的增删改查

时间:2023-03-08 17:43:38
SpringMVC,MyBatis商品的增删改查

一、需求

商品的增删改查

二、工程结构

SpringMVC,MyBatis商品的增删改查

三、代码

1.Mapper层

(1)

ItemsMapperCustom.java

 package com.tony.ssm.mapper;

 import java.util.List;

 import com.tony.ssm.po.ItemsCustom;
import com.tony.ssm.po.ItemsQueryVo; public interface ItemsMapperCustom {
//商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}

ItemsMapperCustom.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.tony.ssm.mapper.ItemsMapperCustom" > <!-- 定义商品查询的sql片段,就是商品查询条件 -->
<sql id="query_items_where">
<!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
<!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if> </sql> <!-- 商品列表查询 -->
<!-- parameterType传入包装对象(包装了查询条件)
resultType建议使用扩展对象
-->
<select id="findItemsList" parameterType="com.tony.ssm.po.ItemsQueryVo"
resultType="com.tony.ssm.po.ItemsCustom">
SELECT items.* FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select> </mapper>

(2)

ItemsMapper.java

 package com.tony.ssm.mapper;

 import com.tony.ssm.po.Items;
import com.tony.ssm.po.ItemsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param; 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);
}

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.tony.ssm.mapper.ItemsMapper" >
<resultMap id="BaseResultMap" type="com.tony.ssm.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.tony.ssm.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.tony.ssm.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.tony.ssm.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.tony.ssm.po.ItemsExample" >
delete from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.tony.ssm.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.tony.ssm.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.tony.ssm.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}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.tony.ssm.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.tony.ssm.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.tony.ssm.po.Items" >
update items
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL},
pic = #{pic,jdbcType=VARCHAR},
createtime = #{createtime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

2.Service层

(1)

ItemsService.java

 package com.tony.ssm.service;

 import java.util.List;

 import com.tony.ssm.po.ItemsCustom;
import com.tony.ssm.po.ItemsQueryVo; /**
*
* <p>Title: ItemsService</p>
* <p>Description:商品管理service </p>
*/
public interface ItemsService { //商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; //根据id查询商品信息
/**
*
* <p>Title: findItemsById</p>
* <p>Description: </p>
* @param id 查询商品的id
* @return
* @throws Exception
*/
public ItemsCustom findItemsById(Integer id) throws Exception; //修改商品信息
/**
*
* <p>Title: updateItems</p>
* <p>Description: </p>
* @param id 修改商品的id
* @param itemsCustom 修改的商品信息
* @throws Exception
*/
public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception; }

ItemsServiceImpl.java

 package com.tony.ssm.service.impl;

 import java.util.List;

 import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import com.tony.ssm.exception.CustomException;
import com.tony.ssm.mapper.ItemsMapper;
import com.tony.ssm.mapper.ItemsMapperCustom;
import com.tony.ssm.po.Items;
import com.tony.ssm.po.ItemsCustom;
import com.tony.ssm.po.ItemsQueryVo;
import com.tony.ssm.service.ItemsService; /**
*
* <p>Title: ItemsServiceImpl</p>
* <p>Description: 商品管理</p>
*/
public class ItemsServiceImpl implements ItemsService{ @Autowired
private ItemsMapperCustom itemsMapperCustom; @Autowired
private ItemsMapper itemsMapper; @Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
throws Exception {
//通过ItemsMapperCustom查询数据库
return itemsMapperCustom.findItemsList(itemsQueryVo);
} @Override
public ItemsCustom findItemsById(Integer id) throws Exception { Items items = itemsMapper.selectByPrimaryKey(id);
if(items==null){
throw new CustomException("修改的商品信息不存在!");
}
//中间对商品信息进行业务处理
//....
//返回ItemsCustom
ItemsCustom itemsCustom = null;
//将items的属性值拷贝到itemsCustom
if(items!=null){
itemsCustom = new ItemsCustom();
BeanUtils.copyProperties(items, itemsCustom);
} return itemsCustom; } @Override
public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
//添加业务校验,通常在service接口对关键参数进行校验
//校验 id是否为空,如果为空抛出异常 //更新商品信息使用updateByPrimaryKeyWithBLOBs根据id更新items表中所有字段,包括 大文本类型字段
//updateByPrimaryKeyWithBLOBs要求必须转入id
itemsCustom.setId(id);
itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
} }

3.Controller层

(1)ItemsController.java

 package com.tony.ssm.controller;

 import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; import com.tony.ssm.controller.validation.ValidateGroup1;
import com.tony.ssm.po.ItemsCustom;
import com.tony.ssm.po.ItemsQueryVo;
import com.tony.ssm.service.ItemsService; /**
*
* <p>Title: ItemsController1</p>
* <p>Description:实现controller接口的 处理器 </p>
*/
@Controller
@RequestMapping("/items")
public class ItemsController { @Autowired
private ItemsService itemsService; @RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request,
ItemsQueryVo itemsQueryVo) throws Exception { // 测试forward后request是否可以共享
System.out.println(request.getParameter("id")); //调用service查找 数据库,查询商品列表
List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); //返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList); //指定视图
modelAndView.setViewName("items/itemsList"); return modelAndView;
} //@RequestMapping("/editItems")
// @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
// public ModelAndView editItems() throws Exception {
// //调用service根据商品id查询商品信息
// ItemsCustom itemsCustom = itemsService.findItemsById(1);
//
// // 返回ModelAndView
// ModelAndView modelAndView = new ModelAndView();
//
// //将商品信息放到model
// modelAndView.addObject("itemsCustom", itemsCustom);
//
// //商品修改页面1
// modelAndView.setViewName("items/editItems");
//
// return modelAndView;
// } //controller可能返回ModelAndView、String、void
// @RequestParam里边指定request传入参数名称和形参进行绑定。
// 通过required属性指定参数是否必须要传入
// 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
public String editItems(Model model,@RequestParam(value="id") Integer items_id) throws Exception {
//调用service根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(items_id); // if(itemsCustom == null){
// throw new CustomException("商品不存在");
// } // 通过形参中的model将model数据传到页面
// 相当于modelAndView.addObject方法
model.addAttribute("items", itemsCustom);
return "items/editItems";
} @RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,
HttpServletRequest request,
Integer id,
@ModelAttribute("items") @Validated(value={ValidateGroup1.class}) ItemsCustom itemsCustom,
BindingResult bindingResult,
MultipartFile itemsPic) throws Exception {
// 获取校验错误信息
if(bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
for(ObjectError error : allErrors){
System.out.println(error.getDefaultMessage());
} // 将错误信息传到页面
model.addAttribute("allErrors", allErrors); //如果不用@ModelAttribute也可以使用model.addAttribute("items", itemsCustom)完成数据回显。
//model.addAttribute("items", itemsCustom); // 出错重新到商品修改页面
return "items/editItems";
} //上传图片
if(itemsPic != null){
//原始名称
String originalFilename = itemsPic.getOriginalFilename(); //存储图片的物理路径
String picPath = "D:\\Workspaces\\eclipseJ2EE\\springmvc_mybatis\\WebRoot\\pic\\"; //新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新图片
File newFile = new File(picPath + newFileName); //将内存中的数据写入磁盘
itemsPic.transferTo(newFile); //将新图片名称写到itemsCustom中,写到数据库表中
itemsCustom.setPic(newFileName); }
//调用service更新商品信息
itemsService.updateItems(id, itemsCustom);
// 重定向到商品查询列表
//return "redirect:queryItems.action"; // 页面转发
//return "forward:queryItems.action"; return "success";
} @RequestMapping("deleteItems")
public String deleteItems(Integer[] items_ids) throws Exception {
//调用service批量删除 return "success";
} //绑定集合类型list
// 批量修改商品页面,将商品信息查询出来,在页面中可以编辑商品信息
@RequestMapping("editItemsQuery")
public String editItemsQuery(Model model) throws Exception {
List<ItemsCustom> itemsList = itemsService.findItemsList(null);
model.addAttribute("itemsList", itemsList);
return "items/editItemsQuery";
} // 批量修改商品提交
// 通过ItemsQueryVo接收批量提交的商品信息,将商品信息存储到itemsQueryVo中itemsList属性中。
@RequestMapping("editItemsAllSubmit")
public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo) throws Exception {
return "success";
} @ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){
Map<String, String> itemTypes = new HashMap<String, String>();
itemTypes.put("101", "数码");
itemTypes.put("102", "图书");
return itemTypes;
} //RESTful查询商品信息,输出json
///itemsView/{id}里边的{id}表示占位符,通过@PathVariable获取占位符中的参数,
//如果占位符中的名称和形参名一致,在@PathVariable可以不指定名称
@RequestMapping("/itemsView/{id}")
public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception {
ItemsCustom itemsCustom = itemsService.findItemsById(id);
return itemsCustom;
}
}

(2)LoginController.java

 package com.tony.ssm.controller;

 import javax.servlet.http.HttpSession;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class LoginController { //登录
@RequestMapping("/login")
public String login(HttpSession session, String username, String password) throws Exception{ //向session记录用户身份信息
session.setAttribute("username", username);
return "redirect:items/queryItems.action";
} //退出
@RequestMapping("/logout")
public String logout(HttpSession session) throws Exception{ //session过期
session.invalidate();
return "redirect:items/queryItems.action";
}
}

4.po类

(1)Items.java

 package com.tony.ssm.po;

 import java.util.Date;

 import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import com.tony.ssm.controller.validation.ValidateGroup1; public class Items {
private Integer id; //这里指定分组ValidGroup1,此@Size校验只适用ValidGroup1校验
//校验名称在1到30字符中间
//message是提示校验出错显示的信息
//groups:此校验属于哪个分组,groups可以定义多个分组
@Size(min=1,max=30,message="{items.name.length.error}",groups={ValidateGroup1.class})
private String name; private Float price; private String pic; @NotNull(message="{items.createtime.isNUll}")
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();
}
}

(2)ItemsCustom.java

 package com.tony.ssm.po;

 /**
*
* <p>Title: ItemsCustom</p>
* <p>Description: 商品信息的扩展类</p>
*/
public class ItemsCustom extends Items { //添加商品信息的扩展属性 }

(3)ItemsQueryVo.java

 package com.tony.ssm.po;

 import java.util.List;

 /**
*
* <p>Title: ItemsQueryVo</p>
* <p>Description:商品包装对象 </p>
*/
public class ItemsQueryVo { //商品信息
private Items items; //为了系统 可扩展性,对原始生成的po进行扩展
private ItemsCustom itemsCustom; //批量商品信息
private List<ItemsCustom> itemsList; //用户信息
//private UserCustom userCustom; public Items getItems() {
return items;
} public void setItems(Items items) {
this.items = items;
} public ItemsCustom getItemsCustom() {
return itemsCustom;
} public void setItemsCustom(ItemsCustom itemsCustom) {
this.itemsCustom = itemsCustom;
} public List<ItemsCustom> getItemsList() {
return itemsList;
} public void setItemsList(List<ItemsCustom> itemsList) {
this.itemsList = itemsList;
} }

5.convertor

(1)CustomDateConverter.java

 package com.tony.ssm.controller.converter;

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.core.convert.converter.Converter; /**
*
* <p>Title: CustomDateConverter</p>
* <p>Description:日期转换器 </p>
*/
public class CustomDateConverter implements Converter<String,Date>{ @Override
public Date convert(String source) { //实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss) SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try {
//转成直接返回
return simpleDateFormat.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果参数绑定失败返回null
return null;
} }

6.validation

(1)ValidateGroup1.java

 package com.tony.ssm.controller.validation;

 public interface ValidateGroup1 {

 }

(2)ValidateGroup2.java

 package com.tony.ssm.controller.validation;

 public interface ValidateGroup2 {

 }

7.exception

(1)CustomException.java

 package com.tony.ssm.exception;

 public class CustomException extends Exception {

     private String message;

     public CustomException(String message) {
super();
this.message = message;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} }

(2)CustomExceptionResolver.java

 package com.tony.ssm.exception;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; public class CustomExceptionResolver implements HandlerExceptionResolver{ @Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
CustomException ce = null;
//如果抛出的是系统自定义异常则直接转换
if(ex instanceof CustomException){
ce = (CustomException)ex;
}else{
//如果抛出的不是系统自定义异常则重新构造一个未知错误异常。
ce = new CustomException("未知异常");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", ce.getMessage());
modelAndView.setViewName("error");
return modelAndView;
} }

8.interceptor

(1)LoginInterceptor.java

 package com.tony.ssm.interceptor;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; public class LoginInterceptor implements HandlerInterceptor{ /**
* controller执行前调用此方法
* 返回true表示继续执行,返回false中止执行
* 这里可以加入登录校验、权限拦截等
*/ @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//如果是登录页面则放行,开发中放行的路径写在配置文件中
if(request.getRequestURI().indexOf("login.action")>=0){
return true;
}
//如果用户已登录也放行
HttpSession session = request.getSession();
if(session.getAttribute("username") != null){
return true;
}
//用户没有登录挑战到登录页面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
} /**
* controller执行后但未返回视图前调用此方法
* 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("LoginInterceptor .......postHandle"); } /**
* controller执行后且视图返回后调用此方法
* 这里可得到执行controller时的异常信息
* 这里可记录操作日志,资源清理等
*/ @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("LoginInterceptor .......afterCompletion"); } }

9.view层

(1)itemsList.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"%>
<!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>
<script>
function deleteItems(){
document.itemsForm.action = "${pageContext.request.contextPath }/items/deleteItems.action";
document.itemsForm.submit();
}
</script>
</head>
<body>
<c:if test="${username != null }">
当前用户:${username }
<a href="${pageContext.request.contextPath }/logout.action">退出</a>
</c:if>
<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>名称:<input name="itemsCustom.name"/></td>
<td>
商品类型:
<select name="itemtypes">
<c:forEach items="${itemtypes }" var="itemtype">
<option value="${itemtype.key }">${itemtype.value }</option>
</c:forEach>
</select>
</td>
<td><input type="submit" value="查询"/></td>
<td><input type="button" value="批量删除" onclick="deleteItems()"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>选择</td>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList}" var="item">
<tr>
<td><input type="checkbox" value="${item.id}" name="items_ids" /></td>
<td>${item.name }</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 }/items/editItems.action?id=${item.id}">修改</a></td> </tr>
</c:forEach> </table>
</form>
</body> </html>

(2)editItems.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"%>
<!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>
<c:if test="${allErrors != null}">
<c:forEach items="${allErrors }" var="error">
${error.defaultMessage }<br/>
</c:forEach>
</c:if>
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${items.id }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${items.name }"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${items.price }"/></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<c:if test="${items.pic !=null}">
<img src="../pic/${items.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="itemsPic"/>
</td>
</tr>
<tr>
<td>商品简介</td>
<td>
<textarea rows="3" cols="30" name="detail">${items.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table> </form>
</body> </html>

(3)editItemsQuery.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"%>
<!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>
<script type="text/javascript">
function editItemsAllSubmit(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath }/items/editItemsAllSubmit.action";
document.itemsForm.submit();
}
function queryItems(){
//提交form
document.itemsForm.action="${pageContext.request.contextPath }/items/queryItems.action";
document.itemsForm.submit();
}
</script>
</head>
<body>
<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>
商品名称:<input name="itemsCustom.name" />
</td>
<td><input type="button" value="查询" onclick="queryItems()"/>
<input type="button" value="批量修改提交" onclick="editItemsAllSubmit()"/>
</td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item" varStatus="status">
<tr> <td><input name="itemsList[${status.index }].name" value="${item.name }"/></td>
<td><input name="itemsList[${status.index }].price" value="${item.price }"/></td>
<td><input name="itemsList[${status.index }].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
<td><input name="itemsList[${status.index }].detail" value="${item.detail }"/></td> </tr>
</c:forEach> </table>
</form>
</body> </html>

(4)error.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
${message }
</body>
</html>

(5)success.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
操作成功!
</body>
</html>

(6)login.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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 }/login.action" method="post">
用户账号:<input type="text" name="username" /><br/>
用户密码 :<input type="password" name="password" /><br/>
<input type="submit" value="登陆"/>
</form>
</body>
</html>

(7)jsonTest.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>json交互测试</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
//请求json,输出是json
function requestJson(){ $.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json;charset=utf-8',
//数据格式是json串,商品信息
data:'{"name":"手机","price":999}',
success:function(data){//返回json结果
console.log(data);
} }); }
//请求key/value,输出是json
function responseJson(){ $.ajax({
type:'post',
url:'${pageContext.request.contextPath }/responseJson.action',
//请求是key/value这里不需要指定contentType,因为默认就 是key/value类型
//contentType:'application/json;charset=utf-8',
//数据格式是json串,商品信息
data:'name=手机&price=999',
success:function(data){//返回json结果
alert(data.name);
} }); }
</script>
</head>
<body>
<input type="button" onclick="requestJson()" value="请求json,输出是json"/>
<input type="button" onclick="responseJson()" value="请求key/value,输出是json"/>
</body>
</html>

10.MyBatis配置文件

(1)sqlMapConfig.xml

 <?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> <!-- 全局setting配置,根据需要添加 --> <!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="com.tony.ssm.po"/>
</typeAliases> <!-- 配置mapper
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
必须遵循:mapper.xml和mapper.java文件同名且在一个目录
--> <!-- <mappers> </mappers> -->
</configuration>

(2)generatorConfig.xml(反向工程配置文件)

 <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 "> <!-- 事务管理器
对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源
dataSource在applicationContext-dao.xml中配置了
-->
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tony.ssm.service.impl.*.*(..))"/>
</aop:config> </beans>

11.Spring配置文件

(1)springmvc.xml

 <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 "> <!-- 配置Handler
<bean id="itemsController1" name="/queryItems1.action" class="com.tony.ssm.controller.ItemsController1" />
-->
<!-- 对于注解的Handler可以单个配置
实际开发中建议使用组件扫描 <bean class="com.tony.ssm.controller.ItemsController" /> -->
<!--
可以扫描controller、service、...
这里让扫描controller,指定controller的包 -->
<!-- -->
<context:component-scan base-package="com.tony.ssm.controller"/> <!-- 静态资源解析包括 :js、css、img、.. -->
<mvc:resources location="/js/" mapping="/js/**"/>
<!--<mvc:resources location="/img/" mapping="/img/**"/>--> <!-- 视图解析器 解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean> <!--
使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven -->
<mvc:annotation-driven conversion-service="conversionService" validator="validator"></mvc:annotation-driven>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="com.tony.ssm.controller.converter.CustomDateConverter"/>
</list>
</property>
</bean> <!-- 校验器 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- hibernate校验器-->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件名-->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean> <!-- 全局异常处理器
只要实现HandlerExceptionResolver接口就是全局异常处理器,若写多个也只有一个才有效
-->
<bean class="com.tony.ssm.exception.CustomExceptionResolver"></bean> <!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean> <!--拦截器 -->
<mvc:interceptors>
<!--多个拦截器,顺序执行 -->
<!-- 登陆认证拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.tony.ssm.interceptor.LoginInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!-- /**表示所有url包括子url路径 -->
<mvc:mapping path="/**"/>
<bean class="com.tony.ssm.interceptor.HandlerInterceptor1"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.tony.ssm.interceptor.HandlerInterceptor2"/>
</mvc:interceptor>
</mvc:interceptors> </beans>

(2)applicationContext-dao.xml

 <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 "> <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 ,dbcp --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
</bean> <!--
<bean id="itmesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.tony.ssm.mapper.ItemsMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<bean id="itmesMapperCustom" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.tony.ssm.mapper.ItemsMapperCustom"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
-->
<!-- mapper扫描器 ,cmlgb,一用扫描器就报错-->
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tony.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean> </beans>

(3)applicationContext-service.xml

 <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 ">
<!-- 商品管理的service -->
<bean id="itemsService" class="com.tony.ssm.service.impl.ItemsServiceImpl"/>
</beans>

(4)applicationContext-transaction.xml

 <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 "> <!-- 事务管理器
对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源
dataSource在applicationContext-dao.xml中配置了
-->
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tony.ssm.service.impl.*.*(..))"/>
</aop:config> </beans>

12.资源文件

(1)log4j.properties

 # Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

(2)db.properties

 jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=xxx

(3)CustomValidationMessages.properties

 #\u6dfb\u52a0\u6821\u9a8c\u9519\u8bef\u63d0\u4ea4\u4fe1\u606f
items.name.length.error=\u8bf7\u8f93\u51651\u523030\u4e2a\u5b57\u7b26\u7684\u5546\u54c1\u540d\u79f0
items.createtime.isNUll=\u8bf7\u8f93\u5165 \u5546\u54c1\u7684\u751f\u4ea7\u65e5\u671f

13.server配置文件web.xml

(1)web.xml

 <?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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_mybatis</display-name> <!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析
第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
使用此种方式可以实现 RESTful风格的url
第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 -->
<url-pattern>*.action</url-pattern>
</servlet-mapping> <!-- springmvc前端控制器,rest配置 -->
<servlet>
<servlet-name>springmvc_rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>springmvc_rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- post乱码过虑器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <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>

14.反向工程文件GeneratorSqlmap.java

 import java.io.File;
import java.util.ArrayList;
import java.util.List; import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback; public class GeneratorSqlmap { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("D:\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null); }
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
} } }

网盘资料

http://pan.baidu.com/s/1i3ShQ1B

http://pan.baidu.com/s/1dEuGpOl