zoukankan      html  css  js  c++  java
  • Spring MVC 02

    高级参数绑定

    绑定数组

    http://localhost:8080/springmvc-mybatis/item/itemlist.action

    前端传来的ids是数组

    <form action="${pageContext.request.contextPath }/deletes.action" method="post">
    <table width="100%" border=1>
    <tr>
        <td><input type="checkbox" name="ids" value=""></td>
        <td>商品名称</td>
        <td>商品价格</td>
        <td>生产日期</td>
        <td>商品描述</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${itemList }" var="item" varStatus="s">
    <tr>
        <td><input type="checkbox" name="ids" value="${item.id }"></td>
        <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>
        <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
        <td>${item.detail }</td>
        
        <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
    
    </tr>
    </c:forEach>
    </table>
    <input type="submit"  value="删除">

    后端用数组属性接收

    //删除多个
    @RequestMapping(value = "/deletes.action")
    public ModelAndView deletes(QueryVo vo){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");
        return mav;
    }
    
    public class QueryVo {
        //商品
        private Items items;
        Integer[] ids;
        private List<Items> itemsList;

    @RequestMapping注解

    @RequestMapping(value = "/updates.action",method = {RequestMethod.POST,RequestMethod.GET})

    method = {RequestMethod.POST,RequestMethod.GET}限定请求方式

    value = "/updates.action"访问路径

    如果value中的目录有多级,并且整个controller中的方法访问路径都在同一目录下,可以提取出来

    放一个@RequestMapping(value = "/item")到类头上

    多个url映射到同一个方法

    @RequestMapping(value = {"/item/itemlist.action","/item/itemlisthaha.action"})
    public String itemList(Model model,HttpServletRequest request,HttpServletResponse response) throws MessageException{
    //        Integer i = 1/0;
        //从Mysql中查询
        List<Items> list = itemService.selectItemsList();
    //        if(null == null){
    //            throw new MessageException("商品信息不能为空");
    //        }
        model.addAttribute("itemList", list);
        return "itemList";
    }

    controller方法返回值

    /**
     * 1.ModelAndView  无敌的    带着数据  返回视图路径           不建议使用
     * 2.String    返回视图路径     model带数据      官方推荐此种方式   解耦   数据  视图  分离  MVC  建议使用  
     * 3.void       ajax  请求   合适   json格式数据 (response   异步请求使用
     */
    @RequestMapping(value = {"/item/itemlist.action","/item/itemlisthaha.action"})
    public String itemList(Model model,HttpServletRequest request,HttpServletResponse response) throws MessageException{
        //从Mysql中查询
        List<Items> list = itemService.selectItemsList();
    //        if(null == null){
    //            throw new MessageException("商品信息不能为空");
    //        }
        model.addAttribute("itemList", list);
        return "itemList";
    }

     重定向/转发

    //提交修改页面 入参  为 Items对象  
    @RequestMapping(value = "/updateitem.action")
    //    public ModelAndView updateitem(Items items){
    public String updateitem(QueryVo vo,MultipartFile pictureFile) throws Exception{
    
        //保存图片到 
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //jpg
        String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
        
        pictureFile.transferTo(new File("D:\upload\" + name + "." + ext));
        
        vo.getItems().setPic(name + "." + ext);
        //修改
        itemService.updateItemsById(vo.getItems());
        
    //        ModelAndView mav = new ModelAndView();
    //        mav.setViewName("success");
        return "redirect:/itemEdit.action?id=" + vo.getItems().getId();
    //        return "forward:/item/itemlist.action";//转发有个问题,页面刷新会把刚才的提交动作再做一遍
    } 

    异常处理器(配置好后,出现异常会自动进入这个方法)

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * 异常处理器的自定义的实现类
     */
    public class CustomExceptionResolver implements HandlerExceptionResolver{
    
        public ModelAndView resolveException(HttpServletRequest request, 
                HttpServletResponse response, Object obj,
                Exception e) {
            // TODO Auto-generated method stub  发生异常的地方 Serivce层  方法  包名+类名+方法名(形参) 字符串
            //日志    1.发布 tomcat war  Eclipse  2.发布Tomcat  服务器上  Linux  Log4j
            
            ModelAndView mav = new ModelAndView();
            //判断异常为类型
            if(e instanceof MessageException){
                //预期异常
                MessageException me = (MessageException)e;
                mav.addObject("error", me.getMsg());
            }else{
                mav.addObject("error", "未知异常");
            }
            mav.setViewName("error");
            return mav;
        }
    
    }

    自定义异常

    public class MessageException extends Exception{
    
        private String msg;
    
        public MessageException(String msg) {
            super();
            this.msg = msg;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

    交给spring管理

    springmvc.xml

    <!-- Springmvc的异常处理器 -->
    <!-- <bean class="com.itheima.springmvc.exception.CustomExceptionResolver"/> -->

    只改处理业务,不修改返回和请求相关的内容,不需要重启服务器(eclipse server)


    上传图片

    有一波操作

    http://localhost:8080/pic/HD.jpg

    <form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">
    
    <td>商品图片</td>
    <td>
        <c:if test="${item.pic !=null}">
            <img src="/pic/${item.pic}" width=100 height=100/>
            <br/>
        </c:if>
        <input type="file"  name="pictureFile"/> 
    </td>

    springmvc.xml

    <!-- 上传图片配置实现类 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传图片的大小   B   5M  1*1024*1024*5-->
        <property name="maxUploadSize" value="5000000"/>
    </bean>

    ItemController.java

    //提交修改页面 入参  为 Items对象
    @RequestMapping(value = "/updateitem.action")
    public String updateitem(QueryVo vo,MultipartFile pictureFile) throws Exception{
    
        //保存图片到 
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //jpg
        String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
        
        pictureFile.transferTo(new File("D:\upload\" + name + "." + ext));
        
        vo.getItems().setPic(name + "." + ext);
        //修改
        itemService.updateItemsById(vo.getItems());
        return "redirect:/itemEdit.action?id=" + vo.getItems().getId();
    }

    json数据交互

    • jackson-annotations-2.4.0.jar
    • jackson-core-2.4.2.jar
    • jackson-databind-2.4.2.jar
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
    $(function(){
        var params = '{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
    
        $.ajax({
            url : "${pageContext.request.contextPath }/json.action",
            data : params,
            contentType : "application/json;charset=UTF-8",//发送数据的格式
            type : "post",
            dataType : "json",//回调
            success : function(data){
                alert(data.name);
            }
        });
    });
    </script>

    后台接收与返回

    //json数据交互
    @RequestMapping(value = "/json.action")
    public @ResponseBody//返回 对象 转为 json
    Items json(@RequestBody Items items){//接收 json 放到 对象
        
    //        System.out.println(items);
        
        return items;
    }

    可用谷歌浏览器测试工具测试


    restful

    是一种风格,可以理解为极简主义,或者一个程序特别内敛特别妥帖,跟人交互特别之清新!

    传统方式操作资源
    http://127.0.0.1/item/queryItem.action?id=1	查询,GET
    http://127.0.0.1/item/saveItem.action		新增,POST
    http://127.0.0.1/item/updateItem.action		更新,POST
    http://127.0.0.1/item/deleteItem.action?id=1	删除,GET或POST
    使用RESTful操作资源
    http://127.0.0.1/item/1		查询,GET
    http://127.0.0.1/item		新增,POST
    http://127.0.0.1/item		更新,PUT
    http://127.0.0.1/item/1		删除,DELETE

    让前台请求后台时链接极其简约

    //RestFul风格的开发
    @RequestMapping(value = "/itemEdit/{id}.action")
    public ModelAndView toEdit1(@PathVariable Integer id,
            HttpServletRequest request,HttpServletResponse response
            ,HttpSession session,Model model){
        
    }

    拦截器配置

    springmvc.xml中配置

    <!-- SPringmvc的拦截器 -->
    <mvc:interceptors>
        <!-- 多个拦截器 -->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!-- 自定义的拦截器类 -->
            <bean class="com.itheima.springmvc.interceptor.Interceptor1"/>
        </mvc:interceptor>
    <!--         <mvc:interceptor>
            <mvc:mapping path="/**"/>
            自定义的拦截器类
            <bean class="com.itheima.springmvc.interceptor.Interceptor2"/>
        </mvc:interceptor> -->
    </mvc:interceptors>

    拦截未登陆

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    public class Interceptor1 implements HandlerInterceptor{
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
            // 返回true就放行
            System.out.println("方法前 1");
            //判断用户是否登陆  如果没有登陆  重定向到登陆页面   不放行   如果登陆了  就放行了
            // URL  http://localhost:8080/springmvc-mybatis/login.action
            //URI /login.action
            String requestURI = request.getRequestURI();
            if(!requestURI.contains("/login")){//不拦截登陆
                String username = (String) request.getSession().getAttribute("USER_SESSION");
                if(null == username){
                    response.sendRedirect(request.getContextPath() + "/login.action");
                    return false;
                }
            }
            return true;
        }
        public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
                throws Exception {
            // TODO Auto-generated method stub
            System.out.println("方法后 1");
            
        }
        public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
            // TODO Auto-generated method stub
            System.out.println("页面渲染后 1");
        }
    }

    登陆

    //去登陆的页面
    @RequestMapping(value = "/login.action",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/login.action",method = RequestMethod.POST)
    public String login(String username
            ,HttpSession httpSession){
        httpSession.setAttribute("USER_SESSION", username);
        return "redirect:/item/itemlist.action";
    }

    击石乃有火,不击元无烟!!
  • 相关阅读:
    Python基础23_os,sys,序列化,pickle,json
    Python基础22_模块,collections,time,random,functools
    Python基础21_类与类型, MRO, C3算法, super()
    Python基础20_类的约束,异常处理,MD5加密,日志
    python反射机制
    python 依赖关系 与关联关系
    python 类的常见的特殊成员
    类的成员(*变量与*方法)
    初识面向对象
    简说匿名函数与递归
  • 原文地址:https://www.cnblogs.com/rain2020/p/12942203.html
Copyright © 2011-2022 走看看