springMVC框架--註解開發(三)

1.1    商品修改

1.1.1    需求

功能描述:商品信息修改

操作流程:

1、  在商品列表頁面點擊修改連接

 

2、打開商品修改頁面,顯示了當前商品的信息

         根據商品id查詢商品信息

3、修改商品信息,點擊提交。

         更新商品信息


1.1.2    mapper

使用mybatis逆向工程生成代碼:

ItemsMapper.java

ItemsMapper.xml

 itemsMapper.java裏面有兩個方法:

       1:  根據商品id查詢商品信息

         2:更新商品信息


1.1.3    service

public interface ItemsService {
         //商品查詢列表
         public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
                            throws Exception;
         //根據商品id查詢商品信息
         public ItemsCustom findItemsById(int id) throwsException;
         //更新商品信息
         public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
}

1.2  @requestMapping講解

1.2.1    設置方法對應的url(完成url映射)

controller類中的一個方法對應一個請求的url

@RequestMapping("/queryItems")

         public ModelAndView queryItems(HttpServletRequest request) throws Exception {

}

1.2.2    窄化請求映射

在controller類上定義根路徑,這樣有助於系統的模塊化開發

@Controller

//定義url的根路徑,訪問時根路徑+方法的url

@RequestMapping("/items")

public class ItemsController {

}

1.2.3    限制http請求的方法

通過requestMapping限制url請求的http方法,

 如果限制請求必須是post,如果get請求就拋出異常:

 

商品修改方法,限制爲http的get:

@RequestMapping(value="/editItems",method={RequestMethod.GET})

         public String editItems(Model model,Integerid)throws Exception{

}

1.3    controller方法返回值

1.3.1    返回ModelAndView

@RequestMapping("/queryItems")
         public ModelAndView queryItems(HttpServletRequestrequest) throws Exception {
                  
                   System.out.println(request.getParameter("id"));
                   //調用service查詢商品列表
                   List<ItemsCustom> itemsList = itemsService.findItemsList(null);
                   ModelAndView modelAndView = new ModelAndView();
                   modelAndView.addObject("itemsList", itemsList);
                   // 指定邏輯視圖名
                   modelAndView.setViewName("itemsList");
                   return modelAndView;
         }

1.3.1    返回字符串

如果controller方法返回jsp頁面,可以簡單將方法返回值類型定義爲字符串,最終返回邏輯視圖名。

//方法返回 字符串,字符串就是邏輯視圖名,Model作用是將數據填充到request域,在頁面展示

       

  @RequestMapping(value="/editItems",method={RequestMethod.GET})
         public String editItems(Model model,Integer id)throws Exception{
                  
                   //調用 service查詢商品信息
                   ItemsCustom itemsCustom = itemsService.findItemsById(id);
                   model.addAttribute("item", itemsCustom);
                   return"editItem";
         }

1.3.2    返回void

//方法返回void

  @RequestMapping(value="/editItems",method={RequestMethod.GET})
         public void editItems(
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Integer id
                            )
                            throwsException {
                   //調用 service查詢商品信息
                   ItemsCustom itemsCustom = itemsService.findItemsById(id);
                   request.setAttribute("item", itemsCustom);
                   //注意如果使用request轉向頁面,這裏指定頁面的完整路徑
                   request.getRequestDispatcher("/WEB-INF/jsp/editItem.jsp").forward(request, response);
         }

使用此方法,容易輸出json、xml格式的數據:

通過response指定響應結果,例如響應json數據如下:

response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");

1.3.3    redirect重定向和forward轉發

如果方法重定向到另一個url,方法返回值爲“redirect:url路徑”,如果方法轉發則方法返回值爲“forward:url路徑”

      

   //商品修改提交
         //itemsQueryVo是包裝類型的pojo
         @RequestMapping("/editItemSubmit")
         public String editItemSubmit(Integer id,ItemsCustomitemsCustom)throws Exception{
                   //調用service接口更新商品信息
                   itemsService.updateItems(id, itemsCustom);
                   //請求重定向
                   return "redirect:queryItems.action";
                   //轉發
//               return"forward:queryItems.action";
         }

使用redirect進行重定向,request數據無法共享,url地址欄會發生變化的, 使用forward進行請求轉發,request數據可以共享,url地址欄不會。

1.4    參數綁定

1.4.1    默認支持的參數類型

處理器形參中添加如下類型的參數處理適配器會默認識別並進行賦值。

1.4.1.1             HttpServletRequest

通過request對象獲取請求信息

1.4.1.2             HttpServletResponse

通過response處理響應信息

1.4.1.3             HttpSession

通過session對象得到session中存放的對象

1.4.2    Model

通過model向頁面傳遞數據,如下:

//調用service查詢商品信息
Items item =itemService.findItemById(id);
model.addAttribute("item",item);

頁面通過${item.XXXX}獲取item對象的屬性值。

1.4.3    @RequestParam註解

如果request請求的參數名和controller方法的形參數名稱一致,適配器自動進行參數綁定。如果不一致可以通過

@RequestParam 指定request請求的參數名綁定到哪個方法形參上。

//方法返回void
         @RequestMapping(value="/editItems",method={RequestMethod.GET})
         public void editItems(
                            HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam(value = "id", required = false, defaultValue = "1")
                            Integer item_id//這裏前端傳過來的是參數名是id這裏controller方法接收則用item_id如果這裏沒加@RequestParam這個註解則接收不到這個參數
                            )
                            throwsException {
}

對於必須要傳的參數,通過@RequestParam中屬性required設置爲true,如果不傳此參數則報錯。

對於有些參數如果不傳入,還需要設置默認值,使用@RequestParam中屬性defaultvalue設置默認值。

1.4.4    可以綁定簡單類型

可以綁定整型、字符串、單精/雙精度、日期、布爾型。

1.4.5    可以綁定簡單pojo類型

簡單pojo類型只包括簡單類型的屬性。

綁定過程:

request請求的參數名稱和pojo的屬性名一致,就可以綁定成功。

簡單pojo類型存在的問題:

如果controller方法形參中有多個pojo且pojo中有重複的屬性,使用簡單pojo綁定無法有針對性的綁定,

比如:方法形參有items和User,pojo同時存在name屬性,從http請求過程的name無法有針對性的綁定到items或user。

1.4.6    可以綁定包裝的pojo

包裝的pojo裏邊包括了其他的pojo。

頁面參數定義:

修改商品信息:

<table width="100%"border=1>
<tr>
         <td>商品名稱</td>
         <td><input type="text"name="itemsCustom.name"value="${item.name}"/></td>
</tr>
<tr>
         <td>商品價格</td>
         <td><input type="text"name="itemsCustom.price"value="${item.price}"/></td>
</tr>
</table>

包裝類型的屬性也是itemsCustom:

public class ItemsQueryVo {
         //商品信息
         private ItemsCustom itemsCustom;
         public ItemsCustom getItemsCustom() {
                   return itemsCustom;
         }
         public voidsetItemsCustom(ItemsCustom itemsCustom) {
                   this.itemsCustom= itemsCustom;
         }
}

按照上邊的規則進行包裝類型的綁定。

1.4.7    參數綁定集合類型

集合類型的參數綁定和包裝類POJO類似,需要在包裝類POJO中定義

List的簡單POJO如:

public class ItemsQueryVo {
         //商品信息
         privateItemsCustom itemsCustom;
         //商品信息列表
         privateList<ItemsCustom> itemsList;
}

JSP頁面如下:

<c:forEach items="${itemsList }" var="item" varStatus="s">
<tr>
<td><input type="text"name="itemsList[${s.index}].name"value="${item.name }"/></td>
         <td><input type="text"name="itemsList[${s.index}].price"value="${item.price }"/></td>
</tr>
</c:forEach>

controller裏面的方法通過包裝類POJO ItemsQueryVo就能和JSP傳過來的參數進行綁定:

  @RequestMapping(value="/editItems")
                                     public StringeditItems(ItemsQueryVo itemsQueryVo)throwsException{
                                               //調用 service批量修改商品信息的方法  
                                               return"success";
                                     }

注意:

request請求的參數名和controller方法的形參數名稱一致,適配器自動進行參數綁定,不然需要通過@RequestParam註解進行說明即:JSP頁面中的itemsList要和包裝類中的ItemsQueryVo屬性 List<ItemCustom> itemsList名稱一致

1.4.8 使用WebBindingInitializer進行自定義參數綁定

使用WebBindingInitializer讓多個controller共用 屬性編輯器(不適用)或者是屬性轉換器。

然後將自定義WebBindingInitializer,注入到處理器適配器中。

 

1.4.8.1             實現Converter接口:

定義日期類型轉換器

package cn.itcast.ssm.controller.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
importorg.springframework.core.convert.converter.Converter;
/**
 * 自定義日期轉換器
 *
 *@author xia
 *
 */
public class CustomDateConverter implementsConverter<String, Date> {
         publicDate convert(String source) {
                   try{
                            //進行日期轉換
                            returnnew SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
                   }catch (Exception e) {
                            e.printStackTrace();
                   }
                   returnnull;
         }
}

自定義字符串去除前後空格轉換器

packagecn.itcast.ssm.controller.converter;
importorg.springframework.core.convert.converter.Converter;
/**
 * 自定義空格轉換器
 * @authorxia
 *
 */
public classStringTrimConverter implements Converter<String, String> {
         publicString convert(String source) {
                   try{
                            //去掉字符串兩邊空格,如果去除後爲空設置爲null
                            if(source!=null){
                                     source= source.trim();
                                     if(source.equals("")){
                                               returnnull;
                                     }
                            }
                   }catch (Exception e) {
                            e.printStackTrace();
                   }
                   returnsource;
         }
}

1.4.8.2             配置轉換器(springmvc.xml)

方式一:(       不使用<mvc:annotation-drivenconversion-service="conversionService">

</mvc:annotation-driven>的方式配置):

   <!-- 使用spring組件掃描 -->
         <context:component-scanbase-package="cn.itcast.ssm.controller"/>
 
         <!-- 通過annotation-driven可以替代下邊的處理器映射器和適配器-->
<!--           <mvc:annotation-drivenconversion-service="conversionService">
</mvc:annotation-driven>       -->
 
         <!-- 註解處理器映射器 -->
         <bean
         class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
         </bean>
 
         <!-- 註解適配器 -->
         <bean
         class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
                   <!--在webBindingInitializer中注入自定義轉換器 -->
                    <property name="webBindingInitializer"ref="customBinder"></property>
         </bean>
 
         <!-- 配置視圖解析器要求將jstl的包加到classpath -->
         <!--ViewResolver -->
         <bean
                   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                   <property name="prefix"value="/WEB-INF/jsp/"/>
                   <property name="suffix"value=".jsp"/>
         </bean>
 
         <!-- 自定義webBindingInitializer-->
         <bean id="customBinder"
                   class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                   <!--使用converter進行參數轉 -->
                   <property name="conversionService"ref="conversionService"/>
         </bean>
 
         <!-- 轉換器 -->
    <bean id="conversionService"
         class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
                   <property name="converters">
                            <list>
                                     <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
                                     <bean class="cn.itcast.ssm.controller.converter.StringTrimConverter"/>
                            </list>
                   </property>
         </bean>
</beans>

方式二(使用<mvc:annotation-drivenconversion-service="conversionService">

</mvc:annotation-driven>的方式配置):

<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<!-- conversionService -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       <!-- 轉換器 -->
       <property name="converters">
           <list>
              <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
           </list>
       </property>
    </bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章