一、需求
商品的增删改查
二、工程结构
三、代码
1.Mapper层
(1)
ItemsMapperCustom.java
1 package com.tony.ssm.mapper;
2
3 import java.util.List;
4
5 import com.tony.ssm.po.ItemsCustom;
6 import com.tony.ssm.po.ItemsQueryVo;
7
8 public interface ItemsMapperCustom {
9 //商品查询列表
10 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
11 }
ItemsMapperCustom.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 <mapper namespace="com.tony.ssm.mapper.ItemsMapperCustom" >
4
5 <!-- 定义商品查询的sql片段,就是商品查询条件 -->
6 <sql id="query_items_where">
7 <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
8 <!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
9 <if test="itemsCustom!=null">
10 <if test="itemsCustom.name!=null and itemsCustom.name!=''">
11 items.name LIKE '%${itemsCustom.name}%'
12 </if>
13 </if>
14
15 </sql>
16
17 <!-- 商品列表查询 -->
18 <!-- parameterType传入包装对象(包装了查询条件)
19 resultType建议使用扩展对象
20 -->
21 <select id="findItemsList" parameterType="com.tony.ssm.po.ItemsQueryVo"
22 resultType="com.tony.ssm.po.ItemsCustom">
23 SELECT items.* FROM items
24 <where>
25 <include refid="query_items_where"></include>
26 </where>
27 </select>
28
29 </mapper>
(2)
ItemsMapper.java
1 package com.tony.ssm.mapper;
2
3 import com.tony.ssm.po.Items;
4 import com.tony.ssm.po.ItemsExample;
5 import java.util.List;
6 import org.apache.ibatis.annotations.Param;
7
8 public interface ItemsMapper {
9 int countByExample(ItemsExample example);
10
11 int deleteByExample(ItemsExample example);
12
13 int deleteByPrimaryKey(Integer id);
14
15 int insert(Items record);
16
17 int insertSelective(Items record);
18
19 List<Items> selectByExampleWithBLOBs(ItemsExample example);
20
21 List<Items> selectByExample(ItemsExample example);
22
23 Items selectByPrimaryKey(Integer id);
24
25 int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
26
27 int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
28
29 int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
30
31 int updateByPrimaryKeySelective(Items record);
32
33 int updateByPrimaryKeyWithBLOBs(Items record);
34
35 int updateByPrimaryKey(Items record);
36 }
ItemsMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 <mapper namespace="com.tony.ssm.mapper.ItemsMapper" >
4 <resultMap id="BaseResultMap" type="com.tony.ssm.po.Items" >
5 <id column="id" property="id" jdbcType="INTEGER" />
6 <result column="name" property="name" jdbcType="VARCHAR" />
7 <result column="price" property="price" jdbcType="REAL" />
8 <result column="pic" property="pic" jdbcType="VARCHAR" />
9 <result column="createtime" property="createtime" jdbcType="TIMESTAMP" />
10 </resultMap>
11 <resultMap id="ResultMapWithBLOBs" type="com.tony.ssm.po.Items" extends="BaseResultMap" >
12 <result column="detail" property="detail" jdbcType="LONGVARCHAR" />
13 </resultMap>
14 <sql id="Example_Where_Clause" >
15 <where >
16 <foreach collection="oredCriteria" item="criteria" separator="or" >
17 <if test="criteria.valid" >
18 <trim prefix="(" suffix=")" prefixOverrides="and" >
19 <foreach collection="criteria.criteria" item="criterion" >
20 <choose >
21 <when test="criterion.noValue" >
22 and ${criterion.condition}
23 </when>
24 <when test="criterion.singleValue" >
25 and ${criterion.condition} #{criterion.value}
26 </when>
27 <when test="criterion.betweenValue" >
28 and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
29 </when>
30 <when test="criterion.listValue" >
31 and ${criterion.condition}
32 <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
33 #{listItem}
34 </foreach>
35 </when>
36 </choose>
37 </foreach>
38 </trim>
39 </if>
40 </foreach>
41 </where>
42 </sql>
43 <sql id="Update_By_Example_Where_Clause" >
44 <where >
45 <foreach collection="example.oredCriteria" item="criteria" separator="or" >
46 <if test="criteria.valid" >
47 <trim prefix="(" suffix=")" prefixOverrides="and" >
48 <foreach collection="criteria.criteria" item="criterion" >
49 <choose >
50 <when test="criterion.noValue" >
51 and ${criterion.condition}
52 </when>
53 <when test="criterion.singleValue" >
54 and ${criterion.condition} #{criterion.value}
55 </when>
56 <when test="criterion.betweenValue" >
57 and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
58 </when>
59 <when test="criterion.listValue" >
60 and ${criterion.condition}
61 <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
62 #{listItem}
63 </foreach>
64 </when>
65 </choose>
66 </foreach>
67 </trim>
68 </if>
69 </foreach>
70 </where>
71 </sql>
72 <sql id="Base_Column_List" >
73 id, name, price, pic, createtime
74 </sql>
75 <sql id="Blob_Column_List" >
76 detail
77 </sql>
78 <select id="selectByExampleWithBLOBs" resultMap="ResultMapWithBLOBs" parameterType="com.tony.ssm.po.ItemsExample" >
79 select
80 <if test="distinct" >
81 distinct
82 </if>
83 <include refid="Base_Column_List" />
84 ,
85 <include refid="Blob_Column_List" />
86 from items
87 <if test="_parameter != null" >
88 <include refid="Example_Where_Clause" />
89 </if>
90 <if test="orderByClause != null" >
91 order by ${orderByClause}
92 </if>
93 </select>
94 <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.tony.ssm.po.ItemsExample" >
95 select
96 <if test="distinct" >
97 distinct
98 </if>
99 <include refid="Base_Column_List" />
100 from items
101 <if test="_parameter != null" >
102 <include refid="Example_Where_Clause" />
103 </if>
104 <if test="orderByClause != null" >
105 order by ${orderByClause}
106 </if>
107 </select>
108 <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
109 select
110 <include refid="Base_Column_List" />
111 ,
112 <include refid="Blob_Column_List" />
113 from items
114 where id = #{id,jdbcType=INTEGER}
115 </select>
116 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
117 delete from items
118 where id = #{id,jdbcType=INTEGER}
119 </delete>
120 <delete id="deleteByExample" parameterType="com.tony.ssm.po.ItemsExample" >
121 delete from items
122 <if test="_parameter != null" >
123 <include refid="Example_Where_Clause" />
124 </if>
125 </delete>
126 <insert id="insert" parameterType="com.tony.ssm.po.Items" >
127 insert into items (id, name, price,
128 pic, createtime, detail
129 )
130 values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=REAL},
131 #{pic,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{detail,jdbcType=LONGVARCHAR}
132 )
133 </insert>
134 <insert id="insertSelective" parameterType="com.tony.ssm.po.Items" >
135 insert into items
136 <trim prefix="(" suffix=")" suffixOverrides="," >
137 <if test="id != null" >
138 id,
139 </if>
140 <if test="name != null" >
141 name,
142 </if>
143 <if test="price != null" >
144 price,
145 </if>
146 <if test="pic != null" >
147 pic,
148 </if>
149 <if test="createtime != null" >
150 createtime,
151 </if>
152 <if test="detail != null" >
153 detail,
154 </if>
155 </trim>
156 <trim prefix="values (" suffix=")" suffixOverrides="," >
157 <if test="id != null" >
158 #{id,jdbcType=INTEGER},
159 </if>
160 <if test="name != null" >
161 #{name,jdbcType=VARCHAR},
162 </if>
163 <if test="price != null" >
164 #{price,jdbcType=REAL},
165 </if>
166 <if test="pic != null" >
167 #{pic,jdbcType=VARCHAR},
168 </if>
169 <if test="createtime != null" >
170 #{createtime,jdbcType=TIMESTAMP},
171 </if>
172 <if test="detail != null" >
173 #{detail,jdbcType=LONGVARCHAR},
174 </if>
175 </trim>
176 </insert>
177 <select id="countByExample" parameterType="com.tony.ssm.po.ItemsExample" resultType="java.lang.Integer" >
178 select count(*) from items
179 <if test="_parameter != null" >
180 <include refid="Example_Where_Clause" />
181 </if>
182 </select>
183 <update id="updateByExampleSelective" parameterType="map" >
184 update items
185 <set >
186 <if test="record.id != null" >
187 id = #{record.id,jdbcType=INTEGER},
188 </if>
189 <if test="record.name != null" >
190 name = #{record.name,jdbcType=VARCHAR},
191 </if>
192 <if test="record.price != null" >
193 price = #{record.price,jdbcType=REAL},
194 </if>
195 <if test="record.pic != null" >
196 pic = #{record.pic,jdbcType=VARCHAR},
197 </if>
198 <if test="record.createtime != null" >
199 createtime = #{record.createtime,jdbcType=TIMESTAMP},
200 </if>
201 <if test="record.detail != null" >
202 detail = #{record.detail,jdbcType=LONGVARCHAR},
203 </if>
204 </set>
205 <if test="_parameter != null" >
206 <include refid="Update_By_Example_Where_Clause" />
207 </if>
208 </update>
209 <update id="updateByExampleWithBLOBs" parameterType="map" >
210 update items
211 set id = #{record.id,jdbcType=INTEGER},
212 name = #{record.name,jdbcType=VARCHAR},
213 price = #{record.price,jdbcType=REAL},
214 pic = #{record.pic,jdbcType=VARCHAR},
215 createtime = #{record.createtime,jdbcType=TIMESTAMP},
216 detail = #{record.detail,jdbcType=LONGVARCHAR}
217 <if test="_parameter != null" >
218 <include refid="Update_By_Example_Where_Clause" />
219 </if>
220 </update>
221 <update id="updateByExample" parameterType="map" >
222 update items
223 set id = #{record.id,jdbcType=INTEGER},
224 name = #{record.name,jdbcType=VARCHAR},
225 price = #{record.price,jdbcType=REAL},
226 pic = #{record.pic,jdbcType=VARCHAR},
227 createtime = #{record.createtime,jdbcType=TIMESTAMP}
228 <if test="_parameter != null" >
229 <include refid="Update_By_Example_Where_Clause" />
230 </if>
231 </update>
232 <update id="updateByPrimaryKeySelective" parameterType="com.tony.ssm.po.Items" >
233 update items
234 <set >
235 <if test="name != null" >
236 name = #{name,jdbcType=VARCHAR},
237 </if>
238 <if test="price != null" >
239 price = #{price,jdbcType=REAL},
240 </if>
241 <if test="pic != null" >
242 pic = #{pic,jdbcType=VARCHAR},
243 </if>
244 <if test="createtime != null" >
245 createtime = #{createtime,jdbcType=TIMESTAMP},
246 </if>
247 <if test="detail != null" >
248 detail = #{detail,jdbcType=LONGVARCHAR},
249 </if>
250 </set>
251 where id = #{id,jdbcType=INTEGER}
252 </update>
253 <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.tony.ssm.po.Items" >
254 update items
255 set name = #{name,jdbcType=VARCHAR},
256 price = #{price,jdbcType=REAL},
257 pic = #{pic,jdbcType=VARCHAR},
258 createtime = #{createtime,jdbcType=TIMESTAMP},
259 detail = #{detail,jdbcType=LONGVARCHAR}
260 where id = #{id,jdbcType=INTEGER}
261 </update>
262 <update id="updateByPrimaryKey" parameterType="com.tony.ssm.po.Items" >
263 update items
264 set name = #{name,jdbcType=VARCHAR},
265 price = #{price,jdbcType=REAL},
266 pic = #{pic,jdbcType=VARCHAR},
267 createtime = #{createtime,jdbcType=TIMESTAMP}
268 where id = #{id,jdbcType=INTEGER}
269 </update>
270 </mapper>
2.Service层
(1)
ItemsService.java
1 package com.tony.ssm.service;
2
3 import java.util.List;
4
5 import com.tony.ssm.po.ItemsCustom;
6 import com.tony.ssm.po.ItemsQueryVo;
7
8 /**
9 *
10 * <p>Title: ItemsService</p>
11 * <p>Description:商品管理service </p>
12 */
13 public interface ItemsService {
14
15 //商品查询列表
16 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
17
18 //根据id查询商品信息
19 /**
20 *
21 * <p>Title: findItemsById</p>
22 * <p>Description: </p>
23 * @param id 查询商品的id
24 * @return
25 * @throws Exception
26 */
27 public ItemsCustom findItemsById(Integer id) throws Exception;
28
29 //修改商品信息
30 /**
31 *
32 * <p>Title: updateItems</p>
33 * <p>Description: </p>
34 * @param id 修改商品的id
35 * @param itemsCustom 修改的商品信息
36 * @throws Exception
37 */
38 public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
39
40
41 }
ItemsServiceImpl.java
1 package com.tony.ssm.service.impl;
2
3 import java.util.List;
4
5 import org.springframework.beans.BeanUtils;
6 import org.springframework.beans.factory.annotation.Autowired;
7
8 import com.tony.ssm.exception.CustomException;
9 import com.tony.ssm.mapper.ItemsMapper;
10 import com.tony.ssm.mapper.ItemsMapperCustom;
11 import com.tony.ssm.po.Items;
12 import com.tony.ssm.po.ItemsCustom;
13 import com.tony.ssm.po.ItemsQueryVo;
14 import com.tony.ssm.service.ItemsService;
15
16 /**
17 *
18 * <p>Title: ItemsServiceImpl</p>
19 * <p>Description: 商品管理</p>
20 */
21 public class ItemsServiceImpl implements ItemsService{
22
23 @Autowired
24 private ItemsMapperCustom itemsMapperCustom;
25
26 @Autowired
27 private ItemsMapper itemsMapper;
28
29 @Override
30 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
31 throws Exception {
32 //通过ItemsMapperCustom查询数据库
33 return itemsMapperCustom.findItemsList(itemsQueryVo);
34 }
35
36 @Override
37 public ItemsCustom findItemsById(Integer id) throws Exception {
38
39 Items items = itemsMapper.selectByPrimaryKey(id);
40 if(items==null){
41 throw new CustomException("修改的商品信息不存在!");
42 }
43 //中间对商品信息进行业务处理
44 //....
45 //返回ItemsCustom
46 ItemsCustom itemsCustom = null;
47 //将items的属性值拷贝到itemsCustom
48 if(items!=null){
49 itemsCustom = new ItemsCustom();
50 BeanUtils.copyProperties(items, itemsCustom);
51 }
52
53
54 return itemsCustom;
55
56 }
57
58 @Override
59 public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
60 //添加业务校验,通常在service接口对关键参数进行校验
61 //校验 id是否为空,如果为空抛出异常
62
63 //更新商品信息使用updateByPrimaryKeyWithBLOBs根据id更新items表中所有字段,包括 大文本类型字段
64 //updateByPrimaryKeyWithBLOBs要求必须转入id
65 itemsCustom.setId(id);
66 itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
67 }
68
69 }
3.Controller层
(1)ItemsController.java
1 package com.tony.ssm.controller;
2
3 import java.io.File;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.UUID;
8
9 import javax.servlet.http.HttpServletRequest;
10
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Controller;
13 import org.springframework.ui.Model;
14 import org.springframework.validation.BindingResult;
15 import org.springframework.validation.ObjectError;
16 import org.springframework.validation.annotation.Validated;
17 import org.springframework.web.bind.annotation.ModelAttribute;
18 import org.springframework.web.bind.annotation.PathVariable;
19 import org.springframework.web.bind.annotation.RequestMapping;
20 import org.springframework.web.bind.annotation.RequestMethod;
21 import org.springframework.web.bind.annotation.RequestParam;
22 import org.springframework.web.bind.annotation.ResponseBody;
23 import org.springframework.web.multipart.MultipartFile;
24 import org.springframework.web.servlet.ModelAndView;
25
26 import com.tony.ssm.controller.validation.ValidateGroup1;
27 import com.tony.ssm.po.ItemsCustom;
28 import com.tony.ssm.po.ItemsQueryVo;
29 import com.tony.ssm.service.ItemsService;
30
31 /**
32 *
33 * <p>Title: ItemsController1</p>
34 * <p>Description:实现controller接口的 处理器 </p>
35 */
36 @Controller
37 @RequestMapping("/items")
38 public class ItemsController {
39
40 @Autowired
41 private ItemsService itemsService;
42
43 @RequestMapping("/queryItems")
44 public ModelAndView queryItems(HttpServletRequest request,
45 ItemsQueryVo itemsQueryVo) throws Exception {
46
47 // 测试forward后request是否可以共享
48 System.out.println(request.getParameter("id"));
49
50 //调用service查找 数据库,查询商品列表
51 List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);
52
53 //返回ModelAndView
54 ModelAndView modelAndView = new ModelAndView();
55 //相当 于request的setAttribut,在jsp页面中通过itemsList取数据
56 modelAndView.addObject("itemsList", itemsList);
57
58 //指定视图
59 modelAndView.setViewName("items/itemsList");
60
61 return modelAndView;
62 }
63
64 //@RequestMapping("/editItems")
65 // @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
66 // public ModelAndView editItems() throws Exception {
67 // //调用service根据商品id查询商品信息
68 // ItemsCustom itemsCustom = itemsService.findItemsById(1);
69 //
70 // // 返回ModelAndView
71 // ModelAndView modelAndView = new ModelAndView();
72 //
73 // //将商品信息放到model
74 // modelAndView.addObject("itemsCustom", itemsCustom);
75 //
76 // //商品修改页面1
77 // modelAndView.setViewName("items/editItems");
78 //
79 // return modelAndView;
80 // }
81
82 //controller可能返回ModelAndView、String、void
83 // @RequestParam里边指定request传入参数名称和形参进行绑定。
84 // 通过required属性指定参数是否必须要传入
85 // 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
86 @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
87 public String editItems(Model model,@RequestParam(value="id") Integer items_id) throws Exception {
88 //调用service根据商品id查询商品信息
89 ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
90
91 // if(itemsCustom == null){
92 // throw new CustomException("商品不存在");
93 // }
94
95 // 通过形参中的model将model数据传到页面
96 // 相当于modelAndView.addObject方法
97 model.addAttribute("items", itemsCustom);
98 return "items/editItems";
99 }
100
101 @RequestMapping("/editItemsSubmit")
102 public String editItemsSubmit(Model model,
103 HttpServletRequest request,
104 Integer id,
105 @ModelAttribute("items") @Validated(value={ValidateGroup1.class}) ItemsCustom itemsCustom,
106 BindingResult bindingResult,
107 MultipartFile itemsPic) throws Exception {
108 // 获取校验错误信息
109 if(bindingResult.hasErrors()){
110 List<ObjectError> allErrors = bindingResult.getAllErrors();
111 for(ObjectError error : allErrors){
112 System.out.println(error.getDefaultMessage());
113 }
114
115 // 将错误信息传到页面
116 model.addAttribute("allErrors", allErrors);
117
118 //如果不用@ModelAttribute也可以使用model.addAttribute("items", itemsCustom)完成数据回显。
119 //model.addAttribute("items", itemsCustom);
120
121 // 出错重新到商品修改页面
122 return "items/editItems";
123 }
124
125 //上传图片
126 if(itemsPic != null){
127 //原始名称
128 String originalFilename = itemsPic.getOriginalFilename();
129
130 //存储图片的物理路径
131 String picPath = "D:\\Workspaces\\eclipseJ2EE\\springmvc_mybatis\\WebRoot\\pic\\";
132
133 //新的图片名称
134 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
135
136 //新图片
137 File newFile = new File(picPath + newFileName);
138
139 //将内存中的数据写入磁盘
140 itemsPic.transferTo(newFile);
141
142 //将新图片名称写到itemsCustom中,写到数据库表中
143 itemsCustom.setPic(newFileName);
144
145 }
146 //调用service更新商品信息
147 itemsService.updateItems(id, itemsCustom);
148 // 重定向到商品查询列表
149 //return "redirect:queryItems.action";
150
151 // 页面转发
152 //return "forward:queryItems.action";
153
154 return "success";
155 }
156
157 @RequestMapping("deleteItems")
158 public String deleteItems(Integer[] items_ids) throws Exception {
159 //调用service批量删除
160
161 return "success";
162 }
163
164 //绑定集合类型list
165 // 批量修改商品页面,将商品信息查询出来,在页面中可以编辑商品信息
166 @RequestMapping("editItemsQuery")
167 public String editItemsQuery(Model model) throws Exception {
168 List<ItemsCustom> itemsList = itemsService.findItemsList(null);
169 model.addAttribute("itemsList", itemsList);
170 return "items/editItemsQuery";
171 }
172
173 // 批量修改商品提交
174 // 通过ItemsQueryVo接收批量提交的商品信息,将商品信息存储到itemsQueryVo中itemsList属性中。
175 @RequestMapping("editItemsAllSubmit")
176 public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo) throws Exception {
177 return "success";
178 }
179
180 @ModelAttribute("itemtypes")
181 public Map<String, String> getItemTypes(){
182 Map<String, String> itemTypes = new HashMap<String, String>();
183 itemTypes.put("101", "数码");
184 itemTypes.put("102", "图书");
185 return itemTypes;
186 }
187
188 //RESTful查询商品信息,输出json
189 ///itemsView/{id}里边的{id}表示占位符,通过@PathVariable获取占位符中的参数,
190 //如果占位符中的名称和形参名一致,在@PathVariable可以不指定名称
191 @RequestMapping("/itemsView/{id}")
192 public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception {
193 ItemsCustom itemsCustom = itemsService.findItemsById(id);
194 return itemsCustom;
195 }
196 }
(2)LoginController.java
1 package com.tony.ssm.controller;
2
3 import javax.servlet.http.HttpSession;
4
5 import org.springframework.stereotype.Controller;
6 import org.springframework.web.bind.annotation.RequestMapping;
7
8 @Controller
9 public class LoginController {
10
11 //登录
12 @RequestMapping("/login")
13 public String login(HttpSession session, String username, String password) throws Exception{
14
15 //向session记录用户身份信息
16 session.setAttribute("username", username);
17 return "redirect:items/queryItems.action";
18 }
19
20 //退出
21 @RequestMapping("/logout")
22 public String logout(HttpSession session) throws Exception{
23
24 //session过期
25 session.invalidate();
26 return "redirect:items/queryItems.action";
27 }
28 }
4.po类
(1)Items.java
1 package com.tony.ssm.po;
2
3 import java.util.Date;
4
5 import javax.validation.constraints.NotNull;
6 import javax.validation.constraints.Size;
7
8 import com.tony.ssm.controller.validation.ValidateGroup1;
9
10 public class Items {
11 private Integer id;
12
13 //这里指定分组ValidGroup1,此@Size校验只适用ValidGroup1校验
14 //校验名称在1到30字符中间
15 //message是提示校验出错显示的信息
16 //groups:此校验属于哪个分组,groups可以定义多个分组
17 @Size(min=1,max=30,message="{items.name.length.error}",groups={ValidateGroup1.class})
18 private String name;
19
20 private Float price;
21
22 private String pic;
23
24 @NotNull(message="{items.createtime.isNUll}")
25 private Date createtime;
26
27 private String detail;
28
29 public Integer getId() {
30 return id;
31 }
32
33 public void setId(Integer id) {
34 this.id = id;
35 }
36
37 public String getName() {
38 return name;
39 }
40
41 public void setName(String name) {
42 this.name = name == null ? null : name.trim();
43 }
44
45 public Float getPrice() {
46 return price;
47 }
48
49 public void setPrice(Float price) {
50 this.price = price;
51 }
52
53 public String getPic() {
54 return pic;
55 }
56
57 public void setPic(String pic) {
58 this.pic = pic == null ? null : pic.trim();
59 }
60
61 public Date getCreatetime() {
62 return createtime;
63 }
64
65 public void setCreatetime(Date createtime) {
66 this.createtime = createtime;
67 }
68
69 public String getDetail() {
70 return detail;
71 }
72
73 public void setDetail(String detail) {
74 this.detail = detail == null ? null : detail.trim();
75 }
76 }
(2)ItemsCustom.java
1 package com.tony.ssm.po;
2
3 /**
4 *
5 * <p>Title: ItemsCustom</p>
6 * <p>Description: 商品信息的扩展类</p>
7 */
8 public class ItemsCustom extends Items {
9
10 //添加商品信息的扩展属性
11
12 }
(3)ItemsQueryVo.java
1 package com.tony.ssm.po;
2
3 import java.util.List;
4
5 /**
6 *
7 * <p>Title: ItemsQueryVo</p>
8 * <p>Description:商品包装对象 </p>
9 */
10 public class ItemsQueryVo {
11
12 //商品信息
13 private Items items;
14
15 //为了系统 可扩展性,对原始生成的po进行扩展
16 private ItemsCustom itemsCustom;
17
18 //批量商品信息
19 private List<ItemsCustom> itemsList;
20
21 //用户信息
22 //private UserCustom userCustom;
23
24 public Items getItems() {
25 return items;
26 }
27
28 public void setItems(Items items) {
29 this.items = items;
30 }
31
32 public ItemsCustom getItemsCustom() {
33 return itemsCustom;
34 }
35
36 public void setItemsCustom(ItemsCustom itemsCustom) {
37 this.itemsCustom = itemsCustom;
38 }
39
40 public List<ItemsCustom> getItemsList() {
41 return itemsList;
42 }
43
44 public void setItemsList(List<ItemsCustom> itemsList) {
45 this.itemsList = itemsList;
46 }
47
48
49
50 }
5.convertor
(1)CustomDateConverter.java
1 package com.tony.ssm.controller.converter;
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 import org.springframework.core.convert.converter.Converter;
8
9 /**
10 *
11 * <p>Title: CustomDateConverter</p>
12 * <p>Description:日期转换器 </p>
13 */
14 public class CustomDateConverter implements Converter<String,Date>{
15
16 @Override
17 public Date convert(String source) {
18
19 //实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
20
21 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
22
23 try {
24 //转成直接返回
25 return simpleDateFormat.parse(source);
26 } catch (ParseException e) {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 }
30 //如果参数绑定失败返回null
31 return null;
32 }
33
34 }
6.validation
(1)ValidateGroup1.java
1 package com.tony.ssm.controller.validation;
2
3 public interface ValidateGroup1 {
4
5 }
(2)ValidateGroup2.java
1 package com.tony.ssm.controller.validation;
2
3 public interface ValidateGroup2 {
4
5 }
7.exception
(1)CustomException.java
1 package com.tony.ssm.exception;
2
3 public class CustomException extends Exception {
4
5 private String message;
6
7 public CustomException(String message) {
8 super();
9 this.message = message;
10 }
11
12 public String getMessage() {
13 return message;
14 }
15
16 public void setMessage(String message) {
17 this.message = message;
18 }
19
20 }
(2)CustomExceptionResolver.java
1 package com.tony.ssm.exception;
2
3 import javax.servlet.http.HttpServletRequest;
4 import javax.servlet.http.HttpServletResponse;
5
6 import org.springframework.web.servlet.HandlerExceptionResolver;
7 import org.springframework.web.servlet.ModelAndView;
8
9 public class CustomExceptionResolver implements HandlerExceptionResolver{
10
11 @Override
12 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
13 Exception ex) {
14 CustomException ce = null;
15 //如果抛出的是系统自定义异常则直接转换
16 if(ex instanceof CustomException){
17 ce = (CustomException)ex;
18 }else{
19 //如果抛出的不是系统自定义异常则重新构造一个未知错误异常。
20 ce = new CustomException("未知异常");
21 }
22 ModelAndView modelAndView = new ModelAndView();
23 modelAndView.addObject("message", ce.getMessage());
24 modelAndView.setViewName("error");
25 return modelAndView;
26 }
27
28 }
8.interceptor
(1)LoginInterceptor.java
1 package com.tony.ssm.interceptor;
2
3 import javax.servlet.http.HttpServletRequest;
4 import javax.servlet.http.HttpServletResponse;
5 import javax.servlet.http.HttpSession;
6
7 import org.springframework.web.servlet.HandlerInterceptor;
8 import org.springframework.web.servlet.ModelAndView;
9
10 public class LoginInterceptor implements HandlerInterceptor{
11
12 /**
13 * controller执行前调用此方法
14 * 返回true表示继续执行,返回false中止执行
15 * 这里可以加入登录校验、权限拦截等
16 */
17
18 @Override
19 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
20 throws Exception {
21 //如果是登录页面则放行,开发中放行的路径写在配置文件中
22 if(request.getRequestURI().indexOf("login.action")>=0){
23 return true;
24 }
25 //如果用户已登录也放行
26 HttpSession session = request.getSession();
27 if(session.getAttribute("username") != null){
28 return true;
29 }
30 //用户没有登录挑战到登录页面
31 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
32 return false;
33 }
34
35 /**
36 * controller执行后但未返回视图前调用此方法
37 * 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
38 */
39 @Override
40 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
41 ModelAndView modelAndView) throws Exception {
42 System.out.println("LoginInterceptor .......postHandle");
43
44 }
45
46 /**
47 * controller执行后且视图返回后调用此方法
48 * 这里可得到执行controller时的异常信息
49 * 这里可记录操作日志,资源清理等
50 */
51
52 @Override
53 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
54 throws Exception {
55 System.out.println("LoginInterceptor .......afterCompletion");
56
57 }
58
59 }
9.view层
(1)itemsList.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6 <html>
7 <head>
8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
9 <title>查询商品列表</title>
10 <script>
11 function deleteItems(){
12 document.itemsForm.action = "${pageContext.request.contextPath }/items/deleteItems.action";
13 document.itemsForm.submit();
14 }
15 </script>
16 </head>
17 <body>
18 <c:if test="${username != null }">
19 当前用户:${username }
20 <a href="${pageContext.request.contextPath }/logout.action">退出</a>
21 </c:if>
22 <form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
23 查询条件:
24 <table width="100%" border=1>
25 <tr>
26 <td>名称:<input name="itemsCustom.name"/></td>
27 <td>
28 商品类型:
29 <select name="itemtypes">
30 <c:forEach items="${itemtypes }" var="itemtype">
31 <option value="${itemtype.key }">${itemtype.value }</option>
32 </c:forEach>
33 </select>
34 </td>
35 <td><input type="submit" value="查询"/></td>
36 <td><input type="button" value="批量删除" onclick="deleteItems()"/></td>
37 </tr>
38 </table>
39 商品列表:
40 <table width="100%" border=1>
41 <tr>
42 <td>选择</td>
43 <td>商品名称</td>
44 <td>商品价格</td>
45 <td>生产日期</td>
46 <td>商品描述</td>
47 <td>操作</td>
48 </tr>
49 <c:forEach items="${itemsList}" var="item">
50 <tr>
51 <td><input type="checkbox" value="${item.id}" name="items_ids" /></td>
52 <td>${item.name }</td>
53 <td>${item.price }</td>
54 <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
55 <td>${item.detail }</td>
56
57 <td><a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id}">修改</a></td>
58
59 </tr>
60 </c:forEach>
61
62 </table>
63 </form>
64 </body>
65
66 </html>
(2)editItems.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6 <html>
7 <head>
8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
9 <title>修改商品信息</title>
10
11 </head>
12 <body>
13 <c:if test="${allErrors != null}">
14 <c:forEach items="${allErrors }" var="error">
15 ${error.defaultMessage }<br/>
16 </c:forEach>
17 </c:if>
18 <form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
19 <input type="hidden" name="id" value="${items.id }"/>
20 修改商品信息:
21 <table width="100%" border=1>
22 <tr>
23 <td>商品名称</td>
24 <td><input type="text" name="name" value="${items.name }"/></td>
25 </tr>
26 <tr>
27 <td>商品价格</td>
28 <td><input type="text" name="price" value="${items.price }"/></td>
29 </tr>
30 <tr>
31 <td>商品生产日期</td>
32 <td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
33 </tr>
34 <tr>
35 <td>商品图片</td>
36 <td>
37 <c:if test="${items.pic !=null}">
38 <img src="../pic/${items.pic}" width=100 height=100/>
39 <br/>
40 </c:if>
41 <input type="file" name="itemsPic"/>
42 </td>
43 </tr>
44 <tr>
45 <td>商品简介</td>
46 <td>
47 <textarea rows="3" cols="30" name="detail">${items.detail }</textarea>
48 </td>
49 </tr>
50 <tr>
51 <td colspan="2" align="center"><input type="submit" value="提交"/>
52 </td>
53 </tr>
54 </table>
55
56 </form>
57 </body>
58
59 </html>
(3)editItemsQuery.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6 <html>
7 <head>
8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
9 <title>查询商品列表</title>
10 <script type="text/javascript">
11 function editItemsAllSubmit(){
12 //提交form
13 document.itemsForm.action="${pageContext.request.contextPath }/items/editItemsAllSubmit.action";
14 document.itemsForm.submit();
15 }
16 function queryItems(){
17 //提交form
18 document.itemsForm.action="${pageContext.request.contextPath }/items/queryItems.action";
19 document.itemsForm.submit();
20 }
21 </script>
22 </head>
23 <body>
24 <form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
25 查询条件:
26 <table width="100%" border=1>
27 <tr>
28 <td>
29 商品名称:<input name="itemsCustom.name" />
30 </td>
31 <td><input type="button" value="查询" onclick="queryItems()"/>
32 <input type="button" value="批量修改提交" onclick="editItemsAllSubmit()"/>
33 </td>
34 </tr>
35 </table>
36 商品列表:
37 <table width="100%" border=1>
38 <tr>
39 <td>商品名称</td>
40 <td>商品价格</td>
41 <td>生产日期</td>
42 <td>商品描述</td>
43 <td>操作</td>
44 </tr>
45 <c:forEach items="${itemsList }" var="item" varStatus="status">
46 <tr>
47
48 <td><input name="itemsList[${status.index }].name" value="${item.name }"/></td>
49 <td><input name="itemsList[${status.index }].price" value="${item.price }"/></td>
50 <td><input name="itemsList[${status.index }].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
51 <td><input name="itemsList[${status.index }].detail" value="${item.detail }"/></td>
52
53
54 </tr>
55 </c:forEach>
56
57 </table>
58 </form>
59 </body>
60
61 </html>
(4)error.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>错误提示</title>
8 </head>
9 <body>
10 ${message }
11 </body>
12 </html>
(5)success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>成功提示</title>
8 </head>
9 <body>
10 操作成功!
11 </body>
12 </html>
(6)login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>系统登陆</title>
8 </head>
9 <body>
10 <form action="${pageContext.request.contextPath }/login.action" method="post">
11 用户账号:<input type="text" name="username" /><br/>
12 用户密码 :<input type="password" name="password" /><br/>
13 <input type="submit" value="登陆"/>
14 </form>
15 </body>
16 </html>
(7)jsonTest.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>json交互测试</title>
8 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
9 <script type="text/javascript">
10 //请求json,输出是json
11 function requestJson(){
12
13 $.ajax({
14 type:'post',
15 url:'${pageContext.request.contextPath }/requestJson.action',
16 contentType:'application/json;charset=utf-8',
17 //数据格式是json串,商品信息
18 data:'{"name":"手机","price":999}',
19 success:function(data){//返回json结果
20 console.log(data);
21 }
22
23 });
24
25
26 }
27 //请求key/value,输出是json
28 function responseJson(){
29
30 $.ajax({
31 type:'post',
32 url:'${pageContext.request.contextPath }/responseJson.action',
33 //请求是key/value这里不需要指定contentType,因为默认就 是key/value类型
34 //contentType:'application/json;charset=utf-8',
35 //数据格式是json串,商品信息
36 data:'name=手机&price=999',
37 success:function(data){//返回json结果
38 alert(data.name);
39 }
40
41 });
42
43 }
44 </script>
45 </head>
46 <body>
47 <input type="button" onclick="requestJson()" value="请求json,输出是json"/>
48 <input type="button" onclick="responseJson()" value="请求key/value,输出是json"/>
49 </body>
50 </html>
10.MyBatis配置文件
(1)sqlMapConfig.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration
3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6
7 <!-- 全局setting配置,根据需要添加 -->
8
9 <!-- 配置别名 -->
10 <typeAliases>
11 <!-- 批量扫描别名 -->
12 <package name="com.tony.ssm.po"/>
13 </typeAliases>
14
15 <!-- 配置mapper
16 由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
17 必须遵循:mapper.xml和mapper.java文件同名且在一个目录
18 -->
19
20 <!-- <mappers>
21
22 </mappers> -->
23 </configuration>
(2)generatorConfig.xml(反向工程配置文件)
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7 http://www.springframework.org/schema/mvc
8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.2.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15
16 <!-- 事务管理器
17 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
18 -->
19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
20 <!-- 数据源
21 dataSource在applicationContext-dao.xml中配置了
22 -->
23 <property name="dataSource" ref="dataSource"/>
24 </bean>
25
26 <!-- 通知 -->
27 <tx:advice id="txAdvice" transaction-manager="transactionManager">
28 <tx:attributes>
29 <!-- 传播行为 -->
30 <tx:method name="save*" propagation="REQUIRED"/>
31 <tx:method name="delete*" propagation="REQUIRED"/>
32 <tx:method name="insert*" propagation="REQUIRED"/>
33 <tx:method name="update*" propagation="REQUIRED"/>
34 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
35 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
36 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
37 </tx:attributes>
38 </tx:advice>
39 <!-- aop -->
40 <aop:config>
41 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tony.ssm.service.impl.*.*(..))"/>
42 </aop:config>
43
44 </beans>
11.Spring配置文件
(1)springmvc.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7 http://www.springframework.org/schema/mvc
8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.2.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15
16 <!-- 配置Handler
17 <bean id="itemsController1" name="/queryItems1.action" class="com.tony.ssm.controller.ItemsController1" />
18 -->
19 <!-- 对于注解的Handler可以单个配置
20 实际开发中建议使用组件扫描
21
22 <bean class="com.tony.ssm.controller.ItemsController" /> -->
23 <!--
24 可以扫描controller、service、...
25 这里让扫描controller,指定controller的包
26
27 -->
28 <!-- -->
29 <context:component-scan base-package="com.tony.ssm.controller"/>
30
31 <!-- 静态资源解析包括 :js、css、img、.. -->
32 <mvc:resources location="/js/" mapping="/js/**"/>
33 <!--<mvc:resources location="/img/" mapping="/img/**"/>-->
34
35 <!-- 视图解析器 解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包 -->
36 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
37 <!-- 配置jsp路径的前缀 -->
38 <property name="prefix" value="/WEB-INF/jsp/"/>
39 <!-- 配置jsp路径的后缀 -->
40 <property name="suffix" value=".jsp"/>
41 </bean>
42
43 <!--
44 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
45 mvc:annotation-driven默认加载很多的参数绑定方法,
46 比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
47 实际开发时使用mvc:annotation-driven
48
49 -->
50 <mvc:annotation-driven conversion-service="conversionService" validator="validator"></mvc:annotation-driven>
51 <bean id="conversionService"
52 class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
53 <!-- 转换器 -->
54 <property name="converters">
55 <list>
56 <bean class="com.tony.ssm.controller.converter.CustomDateConverter"/>
57 </list>
58 </property>
59 </bean>
60
61 <!-- 校验器 -->
62 <bean id="validator"
63 class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
64 <!-- hibernate校验器-->
65 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
66 <!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
67 <property name="validationMessageSource" ref="messageSource" />
68 </bean>
69 <!-- 校验错误信息配置文件 -->
70 <bean id="messageSource"
71 class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
72 <!-- 资源文件名-->
73 <property name="basenames">
74 <list>
75 <value>classpath:CustomValidationMessages</value>
76 </list>
77 </property>
78 <!-- 资源文件编码格式 -->
79 <property name="fileEncodings" value="utf-8" />
80 <!-- 对资源文件内容缓存时间,单位秒 -->
81 <property name="cacheSeconds" value="120" />
82 </bean>
83
84 <!-- 全局异常处理器
85 只要实现HandlerExceptionResolver接口就是全局异常处理器,若写多个也只有一个才有效
86 -->
87 <bean class="com.tony.ssm.exception.CustomExceptionResolver"></bean>
88
89 <!-- 文件上传 -->
90 <bean id="multipartResolver"
91 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
92 <!-- 设置上传文件的最大尺寸为5MB -->
93 <property name="maxUploadSize">
94 <value>5242880</value>
95 </property>
96 </bean>
97
98 <!--拦截器 -->
99 <mvc:interceptors>
100 <!--多个拦截器,顺序执行 -->
101 <!-- 登陆认证拦截器 -->
102 <mvc:interceptor>
103 <mvc:mapping path="/**"/>
104 <bean class="com.tony.ssm.interceptor.LoginInterceptor"/>
105 </mvc:interceptor>
106 <mvc:interceptor>
107 <!-- /**表示所有url包括子url路径 -->
108 <mvc:mapping path="/**"/>
109 <bean class="com.tony.ssm.interceptor.HandlerInterceptor1"/>
110 </mvc:interceptor>
111 <mvc:interceptor>
112 <mvc:mapping path="/**"/>
113 <bean class="com.tony.ssm.interceptor.HandlerInterceptor2"/>
114 </mvc:interceptor>
115 </mvc:interceptors>
116
117 </beans>
(2)applicationContext-dao.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7 http://www.springframework.org/schema/mvc
8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.2.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15
16 <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
17 <context:property-placeholder location="classpath:db.properties" />
18 <!-- 配置数据源 ,dbcp -->
19
20 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
21 destroy-method="close">
22 <property name="driverClassName" value="${jdbc.driver}" />
23 <property name="url" value="${jdbc.url}" />
24 <property name="username" value="${jdbc.username}" />
25 <property name="password" value="${jdbc.password}" />
26 <property name="maxActive" value="30" />
27 <property name="maxIdle" value="5" />
28 </bean>
29 <!-- sqlSessionFactory -->
30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
31 <!-- 数据库连接池 -->
32 <property name="dataSource" ref="dataSource" />
33 <!-- 加载mybatis的全局配置文件 -->
34 <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
35 </bean>
36
37 <!--
38 <bean id="itmesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
39 <property name="mapperInterface" value="com.tony.ssm.mapper.ItemsMapper"/>
40 <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
41 </bean>
42 <bean id="itmesMapperCustom" class="org.mybatis.spring.mapper.MapperFactoryBean">
43 <property name="mapperInterface" value="com.tony.ssm.mapper.ItemsMapperCustom"/>
44 <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
45 </bean>
46 -->
47 <!-- mapper扫描器 ,cmlgb,一用扫描器就报错-->
48 <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开-->
49 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
50 <property name="basePackage" value="com.tony.ssm.mapper"></property>
51 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
52 </bean>
53
54
55 </beans>
(3)applicationContext-service.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7 http://www.springframework.org/schema/mvc
8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.2.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15 <!-- 商品管理的service -->
16 <bean id="itemsService" class="com.tony.ssm.service.impl.ItemsServiceImpl"/>
17 </beans>
(4)applicationContext-transaction.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7 http://www.springframework.org/schema/mvc
8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.2.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15
16 <!-- 事务管理器
17 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
18 -->
19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
20 <!-- 数据源
21 dataSource在applicationContext-dao.xml中配置了
22 -->
23 <property name="dataSource" ref="dataSource"/>
24 </bean>
25
26 <!-- 通知 -->
27 <tx:advice id="txAdvice" transaction-manager="transactionManager">
28 <tx:attributes>
29 <!-- 传播行为 -->
30 <tx:method name="save*" propagation="REQUIRED"/>
31 <tx:method name="delete*" propagation="REQUIRED"/>
32 <tx:method name="insert*" propagation="REQUIRED"/>
33 <tx:method name="update*" propagation="REQUIRED"/>
34 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
35 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
36 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
37 </tx:attributes>
38 </tx:advice>
39 <!-- aop -->
40 <aop:config>
41 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tony.ssm.service.impl.*.*(..))"/>
42 </aop:config>
43
44 </beans>
12.资源文件
(1)log4j.properties
1 # Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
2 log4j.rootLogger=DEBUG, stdout
3 # Console output...
4 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
5 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
6 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(2)db.properties
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/mybatis
3 jdbc.username=root
4 jdbc.password=xxx
(3)CustomValidationMessages.properties
1 #\u6dfb\u52a0\u6821\u9a8c\u9519\u8bef\u63d0\u4ea4\u4fe1\u606f
2 items.name.length.error=\u8bf7\u8f93\u51651\u523030\u4e2a\u5b57\u7b26\u7684\u5546\u54c1\u540d\u79f0
3 items.createtime.isNUll=\u8bf7\u8f93\u5165 \u5546\u54c1\u7684\u751f\u4ea7\u65e5\u671f
13.server配置文件web.xml
(1)web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
5 id="WebApp_ID" version="2.5">
6 <display-name>springmvc_mybatis</display-name>
7
8 <!-- 加载spring容器 -->
9 <context-param>
10 <param-name>contextConfigLocation</param-name>
11 <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
12 </context-param>
13 <listener>
14 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15 </listener>
16
17
18 <!-- springmvc前端控制器 -->
19 <servlet>
20 <servlet-name>springmvc</servlet-name>
21 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22 <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
23 <init-param>
24 <param-name>contextConfigLocation</param-name>
25 <param-value>classpath:springmvc.xml</param-value>
26 </init-param>
27 </servlet>
28
29 <servlet-mapping>
30 <servlet-name>springmvc</servlet-name>
31 <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析
32 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
33 使用此种方式可以实现 RESTful风格的url
34 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 -->
35 <url-pattern>*.action</url-pattern>
36 </servlet-mapping>
37
38
39 <!-- springmvc前端控制器,rest配置 -->
40 <servlet>
41 <servlet-name>springmvc_rest</servlet-name>
42 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
43 <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
44 <init-param>
45 <param-name>contextConfigLocation</param-name>
46 <param-value>classpath:springmvc.xml</param-value>
47 </init-param>
48 </servlet>
49
50 <servlet-mapping>
51 <servlet-name>springmvc_rest</servlet-name>
52 <url-pattern>/</url-pattern>
53 </servlet-mapping>
54
55 <!-- post乱码过虑器 -->
56 <filter>
57 <filter-name>CharacterEncodingFilter</filter-name>
58 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
59 <init-param>
60 <param-name>encoding</param-name>
61 <param-value>utf-8</param-value>
62 </init-param>
63 </filter>
64 <filter-mapping>
65 <filter-name>CharacterEncodingFilter</filter-name>
66 <url-pattern>/*</url-pattern>
67 </filter-mapping>
68
69 <welcome-file-list>
70 <welcome-file>index.html</welcome-file>
71 <welcome-file>index.htm</welcome-file>
72 <welcome-file>index.jsp</welcome-file>
73 <welcome-file>default.html</welcome-file>
74 <welcome-file>default.htm</welcome-file>
75 <welcome-file>default.jsp</welcome-file>
76 </welcome-file-list>
77 </web-app>
14.反向工程文件GeneratorSqlmap.java
1 import java.io.File;
2 import java.util.ArrayList;
3 import java.util.List;
4
5 import org.mybatis.generator.api.MyBatisGenerator;
6 import org.mybatis.generator.config.Configuration;
7 import org.mybatis.generator.config.xml.ConfigurationParser;
8 import org.mybatis.generator.internal.DefaultShellCallback;
9
10 public class GeneratorSqlmap {
11
12 public void generator() throws Exception{
13
14 List<String> warnings = new ArrayList<String>();
15 boolean overwrite = true;
16 //指定 逆向工程配置文件
17 File configFile = new File("D:\\generatorConfig.xml");
18 ConfigurationParser cp = new ConfigurationParser(warnings);
19 Configuration config = cp.parseConfiguration(configFile);
20 DefaultShellCallback callback = new DefaultShellCallback(overwrite);
21 MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
22 callback, warnings);
23 myBatisGenerator.generate(null);
24
25 }
26 public static void main(String[] args) throws Exception {
27 try {
28 GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
29 generatorSqlmap.generator();
30 } catch (Exception e) {
31 e.printStackTrace();
32 }
33
34 }
35
36 }
网盘资料
http://pan.baidu.com/s/1i3ShQ1B
http://pan.baidu.com/s/1dEuGpOl
来源:oschina
链接:https://my.oschina.net/u/4304158/blog/4274194