Spring MVC, addition, deletion, modification and query of mybatis

1, Demand

Addition, deletion, modification and inspection of goods

2, Engineering structure

3, Code

1.Mapper layer

(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     //Product query list
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    <!-- Define the sql Fragment is the commodity query condition -->
 6    <sql id="query_items_where">
 7        <!-- Use dynamic sql,adopt if Judge and meet the conditions sql Splicing -->
 8        <!-- Product query criteria passed ItemsQueryVo In the packing object itemsCustom Property transfer -->
 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       <!-- Commodity list query -->
18       <!-- parameterType Incoming wrapper object(Packed query criteria)
19           resultType Extended objects are recommended
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 layer

(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:Commodity management service</p>
12  */
13 public interface ItemsService {
14     
15     //Product query list
16     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
17     
18     //according to id Query product information
19     /**
20      * 
21      * <p>Title: findItemsById</p>
22      * <p>Description: </p>
23      * @param id Query item id
24      * @return
25      * @throws Exception
26      */
27     public ItemsCustom findItemsById(Integer id) throws Exception;
28     
29     //Modify product information
30     /**
31      * 
32      * <p>Title: updateItems</p>
33      * <p>Description: </p>
34      * @param id Modify item id
35      * @param itemsCustom Modified product information
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: Commodity management</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         //adopt ItemsMapperCustom query data base
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("The modified product information does not exist!");
42         }
43         //Business processing of commodity information in the middle
44         //....
45         //return ItemsCustom
46         ItemsCustom itemsCustom = null;
47         //take items Copy property values of to 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         //Add business verification, usually in service Interface to verify key parameters
61         //check id If it is empty, throw an exception if it is empty
62         
63         //Update product information usage updateByPrimaryKeyWithBLOBs according to id to update items All fields in the table, including large text type fields
64         //updateByPrimaryKeyWithBLOBs Transfer in required id
65         itemsCustom.setId(id);
66         itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
67     }
68 
69 }

 

3.Controller layer

(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:Processor implementing controller interface</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         // test forward after request Can I share
 48         System.out.println(request.getParameter("id"));
 49         
 50         //call service Search database, query commodity list
 51         List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);
 52 
 53         //return ModelAndView
 54         ModelAndView modelAndView =  new ModelAndView();
 55         //amount to request Of setAttribut,stay jsp Page through itemsList Access to data
 56         modelAndView.addObject("itemsList", itemsList);
 57         
 58         //Specify view
 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 //        //call service By commodity id Query product information
 68 //        ItemsCustom itemsCustom = itemsService.findItemsById(1);
 69 //        
 70 //        // return ModelAndView
 71 //        ModelAndView modelAndView = new ModelAndView();
 72 //        
 73 //        //Put product information in model
 74 //        modelAndView.addObject("itemsCustom", itemsCustom);
 75 //        
 76 //        //Product modification page 1
 77 //        modelAndView.setViewName("items/editItems");
 78 //        
 79 //        return modelAndView;
 80 //    }
 81     
 82     //controller Possible return ModelAndView,String,void
 83     // @RequestParam Inside designated request The parameter name and parameter are passed in for binding.
 84     // adopt required Property specifies whether the parameter must be passed in
 85     // adopt defaultValue You can set the default value if id Parameter is not passed in. Bind the default value to the parameter.
 86     @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
 87     public String editItems(Model model,@RequestParam(value="id") Integer items_id) throws Exception {
 88         //call service By commodity id Query product information
 89         ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
 90         
 91 //        if(itemsCustom == null){
 92 //            throw new CustomException("Item does not exist");
 93 //        }
 94         
 95         // By model take model Data transfer to page
 96         // amount to modelAndView.addObject method
 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         // Get verification error information
109         if(bindingResult.hasErrors()){
110             List<ObjectError> allErrors = bindingResult.getAllErrors();
111             for(ObjectError error : allErrors){
112                 System.out.println(error.getDefaultMessage());
113             }
114             
115             // Send error message to page
116             model.addAttribute("allErrors", allErrors);
117             
118             //If not@ModelAttribute It can also be used model.addAttribute("items", itemsCustom)Complete data echo.
119             //model.addAttribute("items", itemsCustom);
120             
121             // Error to product modification page
122             return "items/editItems";
123         }
124         
125         //Upload picture
126         if(itemsPic != null){
127             //Original name
128             String originalFilename = itemsPic.getOriginalFilename();
129             
130             //Physical path to store pictures
131             String picPath = "D:\\Workspaces\\eclipseJ2EE\\springmvc_mybatis\\WebRoot\\pic\\";
132             
133             //New picture name
134             String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
135             
136             //New picture
137             File newFile = new File(picPath + newFileName);
138             
139             //Write data in memory to disk
140             itemsPic.transferTo(newFile);
141             
142             //Write the new picture name to itemsCustom in,Write to database table
143             itemsCustom.setPic(newFileName);
144         
145         }
146         //call service Update product information
147         itemsService.updateItems(id, itemsCustom);
148         // Redirect to product query list
149         //return "redirect:queryItems.action";
150         
151         // Page forwarding
152         //return "forward:queryItems.action";
153         
154         return "success";
155     }
156     
157     @RequestMapping("deleteItems")
158     public String deleteItems(Integer[] items_ids) throws Exception {
159         //call service Bulk delete
160         
161         return "success";
162     }
163 
164     //Binding collection type list
165     // Modify the product page in batch, query the product information, and edit the product information in the page
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     // Batch modify product submission
174     // adopt ItemsQueryVo Receive the commodity information submitted in batch and store the commodity information in itemsQueryVo in itemsList Property.
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", "Digital");
184         itemTypes.put("102", "books");
185         return itemTypes;
186     }
187     
188     //RESTful Query product information, output json
189     ///itemsView/{id}Inside{id}Represents a placeholder through@PathVariable Gets the parameter in the placeholder,
190     //If the name in the placeholder is the same as the parameter name, in the@PathVariable No name can be specified
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     //Sign in
12     @RequestMapping("/login")
13     public String login(HttpSession session, String username, String password) throws Exception{
14         
15         //towards session Record user identity information
16         session.setAttribute("username", username);
17         return "redirect:items/queryItems.action";
18     }
19     
20     //sign out
21     @RequestMapping("/logout")
22     public String logout(HttpSession session) throws Exception{
23         
24         //session be overdue
25         session.invalidate();
26         return "redirect:items/queryItems.action";
27     }
28 }

 

4.po class

(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     //Group is specified here ValidGroup1,this@Size Verification only applicable ValidGroup1 check
14     //The verification name is between 1 and 30 characters
15     //message It is the information that prompts the verification error
16     //groups: Which group does this verification belong to, groups Multiple groups can be defined
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: Extension class of commodity information</p>
 7  */
 8 public class ItemsCustom extends Items {
 9     
10     //Add extended properties of product information
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:Commodity packaging object</p>
 9  */
10 public class ItemsQueryVo {
11     
12     //Commodity information
13     private Items items;
14     
15     //For system scalability, the po Expand
16     private ItemsCustom itemsCustom;
17     
18     //Batch product information
19     private List<ItemsCustom> itemsList;
20     
21     //User information
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:Date Converter</p>
13  */
14 public class CustomDateConverter implements Converter<String,Date>{
15 
16     @Override
17     public Date convert(String source) {
18         
19         //Convert date string to date type(The format is yyyy-MM-dd HH:mm:ss)
20         
21         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
22         
23         try {
24             //Turn to direct return
25             return simpleDateFormat.parse(source);
26         } catch (ParseException e) {
27             // TODO Auto-generated catch block
28             e.printStackTrace();
29         }
30         //If parameter binding fails, return 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         //Direct conversion if system defined exception is thrown
16         if(ex instanceof CustomException){
17             ce = (CustomException)ex;
18         }else{
19             //If the system custom exception is not thrown, reconstruct an unknown error exception.
20             ce = new CustomException("Unknown exception");
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 Call this method before execution.
14      * Return true to continue execution and false to abort execution
15      * Here you can add login verification, permission interception, etc
16      */
17 
18     @Override
19     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
20             throws Exception {
21         //Release if login page,The path of release in development is written in the configuration file
22         if(request.getRequestURI().indexOf("login.action")>=0){
23             return true;
24         }
25         //Release if user is logged in
26         HttpSession session = request.getSession();
27         if(session.getAttribute("username") != null){
28             return true;
29         }
30         //User does not log in challenge to log in page
31         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
32         return false;
33     }
34 
35     /**
36      * controller Call this method before executing, but not returning to the view.
37      * Here, the model data can be processed before returning to the user. For example, public information can be added here for page display
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 This method is called after execution and after the view returns.
48      * Here you can get the exception information when executing the controller
49      * The operation log and resource cleaning can be recorded here
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 layer

(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>Query product list</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     Current user:${username }
20     <a href="${pageContext.request.contextPath }/logout.action">sign out</a>
21 </c:if>
22 <form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
23 Query criteria:
24 <table width="100%" border=1>
25 <tr>
26 <td>name:<input name="itemsCustom.name"/></td>
27 <td>
28     Commodity type:
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="query"/></td>
36 <td><input type="button" value="Bulk delete" onclick="deleteItems()"/></td>
37 </tr>
38 </table>
39 Product list:
40 <table width="100%" border=1>
41 <tr>
42     <td>choice</td>
43     <td>Commodity name</td>
44     <td>commodity price</td>
45     <td>date of manufacture</td>
46     <td>Product description</td>
47     <td>operation</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}">modify</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>Modify product information</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 Modify product information:
21 <table width="100%" border=1>
22 <tr>
23     <td>Commodity name</td>
24     <td><input type="text" name="name" value="${items.name }"/></td>
25 </tr>
26 <tr>
27     <td>commodity price</td>
28     <td><input type="text" name="price" value="${items.price }"/></td>
29 </tr>
30 <tr>
31     <td>Date of production</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>Product picture</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>Product introduction</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="Submit"/>
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>Query product list</title>
10 <script type="text/javascript">
11 function editItemsAllSubmit(){
12     //Submit form
13     document.itemsForm.action="${pageContext.request.contextPath }/items/editItemsAllSubmit.action";
14     document.itemsForm.submit();
15 }
16 function queryItems(){
17     //Submit 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 Query criteria:
26 <table width="100%" border=1>
27 <tr>
28 <td>
29 Commodity name:<input name="itemsCustom.name" />
30 </td>
31 <td><input type="button" value="query" onclick="queryItems()"/>
32 <input type="button" value="Batch modification and submission" onclick="editItemsAllSubmit()"/>
33 </td>
34 </tr>
35 </table>
36 Product list:
37 <table width="100%" border=1>
38 <tr>
39     <td>Commodity name</td>
40     <td>commodity price</td>
41     <td>date of manufacture</td>
42     <td>Product description</td>
43     <td>operation</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>Error prompt</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>Success tips</title>
 8 </head>
 9 <body>
10 Operation succeeded!
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>System login</title>
 8 </head>
 9 <body>
10 <form action="${pageContext.request.contextPath }/login.action" method="post">
11 User account:<input type="text" name="username" /><br/>
12 User password:<input type="password" name="password" /><br/>
13 <input type="submit" value="land"/>
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 Interactive testing</title>
 8 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
 9 <script type="text/javascript">
10 //request json,Output is 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         //The data format is json String, product information
18         data:'{"name":"mobile phone","price":999}',
19         success:function(data){//return json result
20             console.log(data);
21         }
22         
23     });
24     
25     
26 }
27 //request key/value,Output is json
28 function responseJson(){
29     
30     $.ajax({
31         type:'post',
32         url:'${pageContext.request.contextPath }/responseJson.action',
33         //Request is key/value There is no need to specify contentType,Because the default is key/value type
34         //contentType:'application/json;charset=utf-8',
35         //The data format is json String, product information
36         data:'name=mobile phone&price=999',
37         success:function(data){//return json result
38             alert(data.name);
39         }
40         
41     });
42     
43 }
44 </script>
45 </head>
46 <body>
47 <input type="button" onclick="requestJson()" value="request json,Output is json"/>
48 <input type="button" onclick="responseJson()" value="request key/value,Output is json"/>
49 </body>
50 </html>

10.MyBatis profile

(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 <! -- global setting configuration, add as needed -- >
 8     
 9 <! -- configure alias -- >
10     <typeAliases>
11 <! -- batch scan alias -- >
12         <package name="com.tony.ssm.po"/>
13     </typeAliases>
14 
15 <! -- configure mapper
Because of the use of spring and mybatis integration package for mapper scanning, there is no need to configure.
17 must follow: mapper.xml and mapper.java files have the same name and are in the same directory 
18      -->
19 
20     <!-- <mappers>
21     
22     </mappers> -->
23 </configuration>

(2) Generatorconfig.xml (reverse engineering configuration file)

 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 <!-- Transaction manager 
17     Yes mybatis Operational database transaction control, spring use jdbc Transaction control class of
18 -->
19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
20     <!-- data source
21     dataSource stay applicationContext-dao.xml Configured in
22      -->
23     <property name="dataSource" ref="dataSource"/>
24 </bean>
25 
26 <!-- notice -->
27 <tx:advice id="txAdvice" transaction-manager="transactionManager">
28     <tx:attributes>
29         <!-- Communication behavior -->
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 configuration file

(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     <!-- to configure Handler
 17     <bean id="itemsController1" name="/queryItems1.action" class="com.tony.ssm.controller.ItemsController1" />
 18      -->
 19     <!--  For annotated Handler Can be configured individually
 20     Component scanning is recommended in actual development
 21       
 22      <bean class="com.tony.ssm.controller.ItemsController" /> -->
 23     <!--
 24      Can scan controller,service,...
 25         Let's scan controller,appoint controller 's bag
 26          
 27     -->
 28     <!-- -->
 29     <context:component-scan base-package="com.tony.ssm.controller"/>
 30     
 31     <!-- Static resource resolution includes: js,css,img,.. -->
 32      <mvc:resources location="/js/" mapping="/js/**"/>
 33      <!--<mvc:resources location="/img/" mapping="/img/**"/>-->
 34     
 35     <!--  View parser parsing jsp Resolution, default use jstl label, classpath You have to jstl 's bag  -->
 36     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 37         <!--  to configure jsp Prefix of path  -->
 38         <property name="prefix" value="/WEB-INF/jsp/"/>
 39         <!--  to configure jsp Suffix of path  -->
 40         <property name="suffix" value=".jsp"/>
 41     </bean>
 42     
 43     <!--
 44      use mvc:annotation-driven Replace annotation mapper and annotation adapter configuration above
 45         mvc:annotation-driven Many parameter binding methods are loaded by default,
 46         such as json The transformation parser is loaded by default, if you use the mvc:annotation-driven No need to configure the top one RequestMappingHandlerMapping and RequestMappingHandlerAdapter
 47         Used in actual development 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         <!-- converter -->
 54         <property name="converters">
 55             <list>
 56                 <bean class="com.tony.ssm.controller.converter.CustomDateConverter"/>
 57             </list>
 58         </property>
 59     </bean>
 60     
 61     <!-- Calibrator -->
 62     <bean id="validator"
 63         class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
 64         <!-- hibernate Calibrator-->
 65         <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
 66         <!-- Specifies the resource file used for verification, and configures the verification error information in the file. If it is not specified, it will be used by default classpath Next ValidationMessages.properties -->
 67         <property name="validationMessageSource" ref="messageSource" />
 68     </bean>
 69     <!-- Verify error message profile -->
 70     <bean id="messageSource"
 71         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
 72         <!-- Resource file name-->
 73         <property name="basenames">   
 74             <list>    
 75             <value>classpath:CustomValidationMessages</value> 
 76             </list>   
 77         </property>
 78         <!-- Resource file encoding format -->
 79         <property name="fileEncodings" value="utf-8" />
 80         <!-- Cache time for resource file content, in seconds -->
 81         <property name="cacheSeconds" value="120" />
 82     </bean>
 83     
 84     <!-- Global exception handler
 85     As long as the implementation HandlerExceptionResolver Interface is the global exception handler,If you write more than one, only one is valid
 86      -->
 87     <bean class="com.tony.ssm.exception.CustomExceptionResolver"></bean>
 88     
 89     <!-- File upload -->
 90     <bean id="multipartResolver"
 91         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 92         <!-- Set the maximum size of the uploaded file to 5 MB -->
 93         <property name="maxUploadSize">
 94             <value>5242880</value>
 95         </property>
 96     </bean>
 97     
 98     <!--Interceptor -->
 99     <mvc:interceptors>
100         <!--Multiple interceptors,Sequential execution -->
101         <!-- Login authentication interceptor -->
102         <mvc:interceptor>
103             <mvc:mapping path="/**"/>
104             <bean class="com.tony.ssm.interceptor.LoginInterceptor"/>
105         </mvc:interceptor>
106         <mvc:interceptor>
107             <!-- /**Indicates all url Include child url route -->
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     <!-- load db.properties The contents of the document, db.properties In file key There must be some special rules for naming -->
17     <context:property-placeholder location="classpath:db.properties" />
18     <!-- Configure data sources, 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         <!-- Database connection pool -->
32         <property name="dataSource" ref="dataSource" />
33         <!-- load mybatis Global profile for -->
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 Scanner ,cmlgb,Error is reported as soon as the scanner is used-->
48     <!-- Scan the package path. If you need to scan multiple packages, use half angle comma to separate them-->
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 <!-- Commodity management 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 <!-- Transaction manager 
17     Yes mybatis Operational database transaction control, spring use jdbc Transaction control class of
18 -->
19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
20     <!-- data source
21     dataSource stay applicationContext-dao.xml Configured in
22      -->
23     <property name="dataSource" ref="dataSource"/>
24 </bean>
25 
26 <!-- notice -->
27 <tx:advice id="txAdvice" transaction-manager="transactionManager">
28     <tx:attributes>
29         <!-- Communication behavior -->
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. Resource documents

(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 configuration file 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     <!-- load spring container -->
 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 Front end controller -->
19     <servlet>
20         <servlet-name>springmvc</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22         <!-- contextConfigLocation to configure springmvc Loaded profile (configuration processor mapper, adapter, etc.) if not configured contextConfigLocation,The default load is/WEB-INF/servlet name-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         <!-- The first:*.action,Visit to.action Ending by DispatcherServlet Analyze 
32             Second:/,So all the addresses visited by DispatcherServlet For parsing of static files, you need to configure the DispatcherServlet Analyze 
33             It can be realized in this way RESTful Style url 
34             Third:/*,This configuration is not correct. If you use this configuration, you need to forward to a jsp Page, the DispatcherServlet analysis jsp Address, not based on jsp Page found handler,It will report an error. -->
35         <url-pattern>*.action</url-pattern>
36     </servlet-mapping>
37     
38     
39     <!-- springmvc Front end controller, rest to configure -->
40     <servlet>
41         <servlet-name>springmvc_rest</servlet-name>
42         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
43         <!-- contextConfigLocation to configure springmvc Loaded profile (configuration processor mapper, adapter, etc.) if not configured contextConfigLocation,The default load is/WEB-INF/servlet name-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 Random code filter -->
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. Reverse engineering file 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         //Specify reverse engineering profile
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 }

 

Network disk data

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

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

Tags: Java Spring xml JSP

Posted on Mon, 11 May 2020 11:45:44 -0400 by Pudgemeister