首先要有控制器,对url请求进行处理。
package cn.itcast.ssm.controller;
import java.io.File;
import java.util.ArrayList;
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.RequestBody;
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.sun.xml.internal.ws.developer.MemberSubmissionAddressing.Validation;
import cn.itcast.ssm.controller.validation.ValidGroup1;
import cn.itcast.ssm.exception.CustomException;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsQueryVo;
import cn.itcast.ssm.service.ItemsService;
//为了对url进行分类管理,可以在这里定义路径,最终访问url是根路径+子路径
//比如:商品列表:/items/queryItems.action
@Controller
@RequestMapping("/items")
public class ItemsController {
@Autowired
private ItemsService itemsService;
//商品分类
//itemtypes表示将方法返回值放在request中的key
@ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){
Map<String, String> itemTypes = new HashMap<String,String>();
itemTypes.put("101", "数码");
itemTypes.put("102", "母婴");
return itemTypes;
}
//商品查询
//商品查询列表
@RequestMapping("/queryItems.action")
public ModelAndView queryItems(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception{
System.out.println(request.getParameter("id"));
//调用service查找数据,查询商品列表,这里使用静态数据模拟
List<ItemsCustom> itemsList = itemsService.findItemdsList(itemsQueryVo);
//创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
//填充数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
//下边的路径,如果在视图解析器中配置jsp前缀和后缀,
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上边的路径可以不在程序中指定jsp路径的前缀和后缀,修改为
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
//商品信息修改页面显示
//@RequestMapping("/editItems")
//限制http请求方法
/* @RequestMapping(value="/editItems",method= {RequestMethod.GET,RequestMethod.POST})
public ModelAndView editItems()throws Exception{
//调用service根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(1);
ModelAndView modelAndView = new ModelAndView();
//将商品信息添加至model
modelAndView.addObject("itemsCustom",itemsCustom);
modelAndView.setViewName("items/editItems");
return modelAndView;
}*/
//通过required参数指定 参数是否必须要传入,
//通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
@RequestMapping(value="/editItems",method= {RequestMethod.GET,RequestMethod.POST})
public String editItems(Model model,
@RequestParam(value="id",required = true,defaultValue="")Integer items_id)throws Exception{
//调用service根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
//可以注释掉
/* if(itemsCustom == null){
throw new CustomException("商品信息不存11在!");
}*/
//通过形参中的model将model数据传到视图
model.addAttribute("itemsCustom", itemsCustom);
//可以直接使用model将提交pojo回显到页面
//model.addAttribute("items", itemsCustom);
return "items/editItems";
}
//商品信息修改
//在需要校验的pojo前边添加@Validated,在需要校验的pojo的后边添加BindingResult bingdingResult接收输出错误信息
//注意:@Validated和BindingResult bingdingResult是配对出现的,并且形参顺序是固定的
//value= {ValidGroup1.class}指定使用这个分组的校验
//@ModelAttribute("items")可以指定pojo回显到页面在request中的key
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Model model,HttpServletRequest request,Integer id,
@ModelAttribute("items")@Validated(value= {ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult,MultipartFile pictureFile)throws Exception{
if(bindingResult.hasErrors()) {
//输出错误信息
List<ObjectError> allErrors = bindingResult.getAllErrors();
for(ObjectError objectError:allErrors) {
//输出错误信息
System.out.println(objectError.getDefaultMessage());
}
//将错误信息传到页面
model.addAttribute("allErrors", allErrors);
//出错重新到商品修改页面
return "items/editItems";
}
//原始文件名称
String pictureFile_name = pictureFile.getOriginalFilename();
if(pictureFile != null && pictureFile_name != null && pictureFile_name.length() > 0) {
//新文件名称
String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
//上传图片
File uploadPic = new java.io.File("E:/storage/develop/upload/temp/"+newFileName);
if(!uploadPic.exists()){//E:\\storage\\develop\\upload\\temp\\
uploadPic.mkdirs();
}
//向磁盘写文件
pictureFile.transferTo(uploadPic);
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_id)throws Exception{
//调用service批量删除商品
System.out.print("yes");
return "success";
}
//批量修改商品页面,将商品信息查询出来,在页面中可以编辑商品信息
@RequestMapping("/editItemsQuery")
public ModelAndView editItemsQuery(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception{
//调用service查找数据,查询商品列表,这里使用静态数据模拟
List<ItemsCustom> itemsList = itemsService.findItemdsList(itemsQueryVo);
//创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
//填充数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
//下边的路径,如果在视图解析器中配置jsp前缀和后缀,
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上边的路径可以不在程序中指定jsp路径的前缀和后缀,修改为
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
//批量修改商品提交
//通过ItemsQueryVo接收批量商品信息,将商品信息存储到itemsQueryVo中itemsList属性中。
@RequestMapping("/editItemsALlSubmit")
public String editItemsALlSubmit(ItemsQueryVo itemsQueryVo)throws Exception{
return "success";
}
}
接着,调用某个服务,服务包含对应的接口和实现。
items服务的接口
package cn.itcast.ssm.service;
import java.util.List;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsQueryVo;
public interface ItemsService {
//商品管理service
//商品查询列表
public List<ItemsCustom> findItemdsList(ItemsQueryVo itemdsQueryVo)throws Exception;
//根据id查询商品信息
public ItemsCustom findItemsById(int id)throws Exception;
//修改商品信息
public void updateItems(Integer id,ItemsCustom itemsCustom)throws Exception;
}
以下为items的服务实现。
package cn.itcast.ssm.impl;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import cn.itcast.ssm.exception.CustomException;
import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.mapper.ItemsMapperCustom;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsCustom;
import cn.itcast.ssm.po.ItemsQueryVo;
import cn.itcast.ssm.service.ItemsService;
//商品管理
public class ItemsServiceImpl implements ItemsService{
@Autowired
private ItemsMapperCustom itemsMapperCustom;
@Autowired
private ItemsMapper itemsMapper;
@Override
public List<ItemsCustom> findItemdsList(ItemsQueryVo itemsQueryVo) throws Exception {
//通过ItemsMapperCustom查询数据库
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
@Override
public ItemsCustom findItemsById(int id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
if(items == null) {
throw new CustomException("商品信息不存在!");
}
//中间商品信息进行业务处理,
ItemsCustom itemsCustom = null;
if(items != null) {
//最终返回itemsCustom
itemsCustom = new ItemsCustom();
BeanUtils.copyProperties(items, itemsCustom);
}
return itemsCustom;
}
@Override
public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
//添加业务校验,通常在service接口关键参数进行校验
//校验id是否为空,如果为空,输出异常
//更新商品信息,使用updateByPrimaryKeyWithBLOBs,根据id更新updateByPrimaryKeyWithBLOBsitems表中所有字段,包括大文本类型。
//updateByPrimaryKeyWithBLOBs要求必须传入id
itemsCustom.setId(id);
// itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
itemsMapper.updateByPrimaryKeySelective(itemsCustom);
}
}
服务调用对应Mapper的方法,方法内有四类语句,分别为增删查改。这里列出itemsMapper对应的语句,另外itemsMapper需要有对应的接口(比如itemsMaper.xml对应的itemsMapper.java接口)。
<?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.itcast.ssm.mapper.ItemsMapper" >
<resultMap id="BaseResultMap" type="cn.itcast.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="cn.itcast.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="cn.itcast.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="cn.itcast.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="cn.itcast.ssm.po.ItemsExample" >
delete from items
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="cn.itcast.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="cn.itcast.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="cn.itcast.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="cn.itcast.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="cn.itcast.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="cn.itcast.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>
方便查看使用。
对应的mapper接口,要声明方法名称。
package cn.itcast.ssm.mapper;
import cn.itcast.ssm.po.Items;
import cn.itcast.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);
}