SpringMvc笔记

SpringMVC

表现层框架,友好地支持Restful

SpringMVC处理流程

Created with Raphaël 2.1.2 用户 用户 前端控制器DispatcherServlet 前端控制器DispatcherServlet HandlerController处理器 HandlerController处理器 jsp页面 jsp页面 用户请求 请求业务处理 返回处理结果 处理结果转发给jsp 返回html 响应用户

SSM整合

  1. dao层

    pojo和映射文件及接口使用逆向工程生成
    SqlMapConfig.xml mybatis核心配置文件
    ApplicationContext-dao.xml 整合后的spring在dao层的配置
            数据源
            会话工厂
            扫描Mapper
    
  2. service层

    事务                          ApplicationContext-trans.xml
    @Service注解扫描        ApplicationContext-service.xml
    
  3. controller层

    SpringMvc.xml
        注解扫描:扫描@Controller注解
        注解驱动:替我们显示地配置最新版的注解处理器映射器和注解处理器适配器
        视图解析器:显示地配置是为了在controller中不用每个方法都写页面的全路径
    
  4. web.xml

    springMvc前端控制器配置
    spring监听器
    

springmvc VS struts2

springmvcstruts2
入口servlet即前端控制器
开发基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例)
数据值栈存储请求和响应的数据,通过OGNL存取数据

Demo

@RequestMapping("/items")
@Controller
public class ItemsController{

    @RequestMapping("/itemEdit")
    public String itemEdit(HttpServletRequest req, HttpServletResponse rsp, HttpSession session, Model model) throws Exception{
        String idStr = req.getParameter("id");
        Items items = itemsService.findItemsById(Integer.parseInt(idStr);

        // Model模型,模型中放入返回给页面的数据
        // model底层是用request域来传递数据的,但对request域进行来拓展
        model.addAttribute("item",tiems);
        return "";
    }


    // SpringMvc可以直接接收基本数据类型数据并自动类型转换。
    // Controller方法接收的参数变量名,**必须**要和页面上的name属性相同
    // springMvc也可以直接接收pojo类型,要求页面name和pojo属相名相同
    @RequestMapping("/updateitem")
    public String update(Integer id, String name, Float price, String detail) throws Exception{
        Items items = new Items(id, name, price, detail);
        itmesService.updateItems(items);
        return "success";
    }
    或
    @RequestMapping("/updateitem/{id}")
    public String update(Items items,@PathVariable("id") String id) throws Exception{
        itmesService.updateItems(items);
        return "success";
    }
}

路径(web项目)

  • 相对路径: 相对于当前路径
  • 绝对路径: 相对于项目

说明:

  • .action 代表拦截后缀名为.action结尾的
  • / 代表拦截除.jsp以外的所有资源
  • /* 代表拦截所有,包含.jsp

Controller返回值

  1. ModelAndView

  2. String

    • ”itemlist” 表示转发到 前缀 + itemlist + 后缀 页面
    • “forword:/items/editItems.action” 返回值表示转发到指定路径
    • “redirect:/items/editItems.action” 表示转发到指定路径
      • 使用model存储数据,转发不会丢失数据,request则会。

异常处理

  1. 自定义异常

    为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。

    public class CustomException extends Exception {
        private static final long serialVersionUID = 1L;
    
        public CustomException(String message){
            super(message);
            this.message = message;
        }
    
        //异常信息
        private String message;
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    }
  2. 自定义全局异常处理器,实现HandlerExceptionResolver接口

    public class CustomExceptionResolver implements HandlerExceptionResolver {
        @Override
        publicModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex) {
    
            ex.printStackTrace();
            CustomException customException = null;
    
            //如果抛出的是系统自定义异常则直接转换
            if(ex instanceof CustomException){
                customException = (CustomException)ex;
            }else{
                //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。
                customException = **new** CustomException("系统错误,请与系统管理  员联系!");
            }
    
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("message", customException.getMessage());
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }
  3. 在springmvc.xml中添加:

    <!-- 异常处理器 -->
    <bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>
  4. 错误页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>错误页面</title>
        </head>
        <body>
            您的操作出现错误如下:<br/>
            ${message }
        </body>
    </html>

文件上传

  1. springMvc.xml中配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件最大尺寸为5Mb -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>
  2. MultipartFile

    • getOriginalFilename() 获取图片完整名称
    • transferTo(File savedFile)

Json数据交互

@RequestBody、@ResponseBody

    作用:导入jackson包后,在Controller的方法中可以使用@RequestBody,让SpringMvc将json格式字符串自动转化成pojo对象,页面的name对应pojo的属性名。
    使用@ResponseBody,并且方法返回值为pojo类型的对象,springMvc会自动将pojo对象将返回数据转为json格式字符串。Demo:
    ```
@RequestMapping("/sendJson")
@ResponseBody
public void json(@RequestBody Items items){
    ...
}
```

Restful风格

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。

资源定位: 互联网所有的事物都是资源,要求url中没有动词,只有名词。没有参数

url格式:http://blog.csdn.net/beat_the_world/article/details/45621673

资源操作: 使用put、delete、post、get,使用不同方法对资源进行操作。分别对应添加、删除、修改、查询。一般使用时还是post和get。put和delete几乎不使用。

@RequestMapping

拦截器

<mvc:interceptors>  
     <mvc:interceptor>  
          <!-- 拦截请求路径,/**代表拦截所有 -->  
          <mvc:mapping path="/**"/>  

          <!-- 指定拦截位置 -->  
          <bean class="com.cuncaojin.MyHandlerInterceptor"/>  
     </mvc:interceptor>  
</mvc:interceptors>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值