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编码














猜你喜欢

转载自blog.csdn.net/qq_39128354/article/details/81428457