springmvc(四)&註解開發

9.商品修改功能的開發

需求
    操作流程
    1.進入商品的查詢頁面
    2.點擊修改連接,進入商品的修改頁面,頁面中顯示的要修改的商品信息(從數據庫查詢)
        需要修改的商品從數據庫查詢,根據商品id(主鍵)查詢商品修改信息
    3.在商品修改頁面,修改商品信息,修改後點擊提交

9.1開發mapper

mapper  
    根據id查詢商品信息
    更新items表的數據
不用開發,採用逆向工程生成的代碼            

9.2開發service

接口功能,
    根據id查詢商品信息
    修改商品信息
    //根據id查詢商品信息
/**
     * 
     * <p>Title: findItemsById</p>
     * <p>Description: </p>
     * @param id 查詢商品的id
     * @return
     * @throws Exception
     */
    public ItemsCustom findItemsById(Integer id) throws Exception;

    //修改商品信息
    /**
     * 
     * <p>Title: updateItems</p>
     * <p>Description: </p>
     * @param id 修改商品的id
     * @param itemsCustom 修改的商品信息
     * @throws Exception
     */
    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception;

    實現類
    public class ItemsServiceImpl implements ItemsService{

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    @Autowired
    private ItemsMapper itemsMapper;

    @Override
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
            throws Exception {
        //通過ItemsMapperCustom查詢數據庫
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }

    @Override
    public ItemsCustom findItemsById(Integer id) throws Exception {

        Items items = itemsMapper.selectByPrimaryKey(id);
        if(items==null){
            throw new CustomException("修改的商品信息不存在!");
        }
        //中間對商品信息進行業務處理
        //....
        //返回ItemsCustom
        ItemsCustom itemsCustom = null;
        //將items的屬性值拷貝到itemsCustom
        if(items!=null){
            itemsCustom = new ItemsCustom();
            BeanUtils.copyProperties(items, itemsCustom);
        }


        return itemsCustom;

    }

    @Override
    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
        //添加業務校驗,通常在service接口對關鍵參數進行校驗
        //校驗 id是否爲空,如果爲空拋出異常

        //更新商品信息使用updateByPrimaryKeyWithBLOBs根據id更新items表中所有字段,包括 大文本類型字段
        //updateByPrimaryKeyWithBLOBs要求必須轉入id
        itemsCustom.setId(id);
        itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
    }   

9.3開發controller

方法
    商品信息修改頁面信息
    商品信息修改提交

10.@requestMapping

    URL映射
    定義controller方法對應的URL,進行處理器映射使用
    窄化請求映射
    @Controller
    // 爲了對url進行分類管理 ,可以在這裏定義根路徑,最終訪問url是根路徑+子路徑
    // 比如:商品列表:/items/queryItems.action
    @RequestMapping("/items")

    限制http請求方法
    @Controller
    // 爲了對url進行分類管理 ,可以在這裏定義根路徑,最終訪問url是根路徑+子路徑
    // 比如:商品列表:/items/queryItems.action
    @RequestMapping("/items")   
    出於安全性考慮。對http的連接進行方法的限制
    如果限制請求爲post請求,進行get請求,報錯。

11.controller方法的返回值

返回:ModelAndView
            需要方法結束時,定義ModelAndView,將model和view分別進行設置
        返回string
            如果controller方法返回string1.表示返回邏輯視圖名
            真正視圖(jsp路徑)=前綴 +邏輯視圖名+後綴
                @RequestMapping(value = "/editItems", method = { RequestMethod.POST,
            RequestMethod.GET })

        public String editItems(Model model throws Exception {

        // 調用service根據商品id查詢商品信息
        ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
        //判斷商品是否爲空,根據id沒有查詢到商品,拋出異常,提示用戶商品信息不存 在
//      if(itemsCustom == null){
//          throw new CustomException("修改的商品信息不存在!");
//      }

        // 通過形參中的model將model數據傳到頁面
        // 相當於modelAndView.addObject方法
        model.addAttribute("items", itemsCustom);

        return "items/editItems";
    }
        2.redirect重定向
        商品修改提交後,重定向到商品查詢列表
        redirect重定向特點;瀏覽器地址欄中的URL會變化,修改提交的request數據無法傳到重定向的地址
        因爲,重定向後重新進行request(request無法共享)
        //重定向到商品的查詢列表
        return "redirect:queryItems.action";
        3.forward頁面轉發
        通過forward進行頁面轉發,瀏覽器地址欄URL不變,request可以共享
        //頁面轉發
        return "forward:queryItems.action";

    返回void
        在controller方法參數上定義request和response,使用request或repose指定響應結果
        1.使用request轉發頁面:如下
            request.getRequestDispatcher("頁面路徑").forward(request,response);
            2.也可以通過response頁面重定向
            response.sendRedirect("URL");
            3.也可以通過response指定響應結果,例如響應json數據如下
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json:charset=utf-8");
                response.getWriter().writer("json串");
        12.參數綁定
        12.1springmvc參數綁定過程
        從客戶端請求key/value數據,經過參數綁定,將key/value數據綁定到controller方法的形參上
        springmvc中,接受頁面提交的數據是通過方法形參來接收,而不是在controller類中定義成員變量接收

        12.2參數綁定默認支持的類型
        直接在controller方法形參上定義下邊類型的對象,就可以使用這些對象。在參數綁定過程中,如果遇到下邊類型直接進行綁定。 
        HttpServletRequest 
        通過request對象獲取請求信息
        HttpServletResponse 
        通過response處理響應信息
        HttpSession 
        通過session對象得到session中存放的對象
        Model/ModelMap 
        model是一個接口,modelMap是一個接口實現 。 
        作用:將model數據填充到request域。

12.3簡單類型

整型 字符型 單/雙精度 布爾型 
            // @RequestParam裏邊指定request傳入參數名稱和形參進行綁定。
            // 通過required屬性指定參數是否必須要傳入
            // 通過defaultValue可以設置默認值,如果id參數沒有傳入,將默認值和形參綁定。
            public String editItems(Model model,
            @RequestParam(value = "id", required = true) Integer items_id)
            throws Exception {  
            通過@RequestParam對簡單類型的參數進行綁定
            如果不使用@RequestParam,要求request傳入參數名稱和controller方法的形參名稱一致,方可綁定成功。
            如果使用@RequestParam,不用限制request傳入參數名稱和controller方法的形參名稱一致。
            通過required屬性指定參數是否必須要傳入,如果設置爲true,沒有傳入參數,報下邊錯誤:
             Http Status 400 -Required Integer parameter "id" is not present

12.4pojo綁定

頁面中input的name和controller的pojo形參中的屬性名稱一致,將頁面中數據綁定到pojo
        頁面定義:
            <input type="text" name="name" value="${itemsCustom.name}"/>
        controller的pojo形參的定義
            public class Items{
                private Integer id;
                private String name;
                private Float price;

            }

12.5自定義參數綁定

對於controller形參中pojo,如果屬性中有日期類型,需要自定義參數綁定
        將請求日期數據串傳成 日期類型,要轉換的日期類型和pojo中日期屬性的類型保持一致
        private Date createtime;
        所以自定義參數綁定將日期串轉成java.util.Date類型。 
        需要向處理器適配器中注入自定義的參數綁定組件。
        12.5.1自定義日期類型綁定
            public class CustomDateConverter implements Converter<String,Date>{

    @Override
    public Date convert(String source) {

        //實現 將日期串轉成日期類型(格式是yyyy-MM-dd HH:mm:ss)

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            //轉成直接返回
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //如果參數綁定失敗返回null
        return null;
    }
    12.5.2配置方式
        <mvc:annotation-driven conversion-service="conversionService"
    ></mvc:annotation-driven>
    <!-- 自定義參數綁定 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!-- 轉換器 -->
        <property name="converters">
            <list>
                <!-- 日期類型轉換 -->
                <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
            </list>
        </property>
    </bean>

13.SpringMVC和Struts2的區別

pringmvc基於方法開發的,struts2基於類開發的。
springmvc將url和controller方法映射。映射成功後springmvc生成一個Handler對象,對象中只包括了一個method。方法執行結束,形參數據銷燬。springmvc的controller開發類似service開發。
springmvc可以進行單例開發,並且建議使用單例開發,struts2通過類的成員變量接收參數,無法使用單例,只能使用多例。
經過實際測試,struts2速度慢,在於使用struts標籤,如果使用struts建議使用jstl。

14問題

解決post亂碼

<!-- 解決post請求亂碼 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

    以上可以解決post請求亂碼問題
    對於get請求中文參數出現亂碼問題有倆個解決方法
    修改Tomcat配置文件添加編碼與工程編碼一致
    <Connector UREncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1"
        redirectPort=‘8443“/>
    另一種方法對參數進行重新編碼
    String userName new
    String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8");
    ISO8859-1是Tomcat默認編碼,需要將Tomcat編碼後的內容按utf-8編碼














發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章