springMVC

SpringMVC总结

1.MVC
- M model 即封装的数据模型
- V View 即视图 即响应的内容
- C Controller 即处理用户的请求和响应数据
2.三层架构与MVC的联系
  • MVC是三层架构视图层的一种设计模式
3.sprinMVC的概念
  • springMVC是基于MVC设计的轻量级开源框架、
4. springMVC部署的步骤
  1. 配置引入核心servlet

     
         mvc
         *.do
     
     
         mvc
         org.springframework.web.servlet.DispatcherServlet
         
             contextConfigLocation
             classpath:springMVC.xml
         
         1
     
    
  2. 配置springMVC.xml的配置

        
        
        
    
        
        
        
            
            
        
    
  3. 配置Contrioller

    @Controller
    public class demo {
        @RequestMapping(value = "hello")
        public String hello(String username ,Integer id){
            System.out.println("已经进来了");
            System.out.println(id);
            System.out.println(username);
            return "success";
        }
    
5. springMVC的主要组件
  1. 主要组件
    • 前端控制器(DispatchServlet) ,用于接受并分发客户端发送的请求
    • 后端控制器/处理器,用于处理用户的请求并响应数据
    • 视图,用于封装响应的内容的对象
  2. 三大组件
    • 处理器映射器 HandlerMapping 根据客户端的请求映射处理器中的方法
    • 处理器适配器 HandlerAdapter 适配调用处理器中的方法
    • 视图解析器(ViewResolver) 根据名称解析对应的视图对象
6. 参数的绑定方法
  1. 基本类型的绑定

    /*
    http://localhost:8080/hello?name=xxx&id=1
    将会解析url中的params,如果parm名与处理器映射方法的参数列表中的变量名相同就将该parm的值赋值给该方法的参数。没有值,或者没有改parm。就给默认值null,所以最好用包装类。
    */
    @RequestMapping("hello")
    public String hello(String name,Integer id){
      return "success";
    }
    
  1. 对象绑定

    /*
    1.当account中的属性全部为基本数据类型和String类型
     根据parms中的键名给account的成员方法进行set复制(必须提供set方法)
    2.当account中的属性有自定义类型时,参数键名就需要用user.id的方式给该user进行赋值
    3.当account中属性有集合类型时,参数名需要用user[0]=1,user[0].id=1赋值。
    */
    @RequestMapping("hello")
    public String hello(Account account){
      return "success";
    }
    
  1. 数组/集合绑定

    /*
    1.绑定数组
    http://localhost:8080/hello?ids=1&ids=2
    2绑定集合
    (@RequestParm List ids)
    */
    @RequestMapping("hello")
    public String hello(Integer ids){
      return "success";
    }
    
7. 自定义转换器
/*
自定义一个类实现Converter类<要被转换的类型,转换后的内容>
重写convert方法
将转换后的类型返回
*/

public class DateConverter implements Converter {
    @Override
    public Date convert(String s) {
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(s);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;

    }
}

 

  


        
            
                
            
        
    

8. json数据的交互
/*
@RequestBody:通知account接受的是一个json数据,required 默认等于true,表示必传
@ResponseBody:返回的是一个json数据
*/   

@RequestMapping("json")
    @ResponseBody
    public Object json(@RequestBody Account account){
        System.out.println("进来了");
        return account;
    }
9. RESTful风格支持
  • REST是一种URL编码规范
    1. 接口唯一 每个唯一的url对应一个资源
   /*
   @PathVariable 此注解是为了更加支持Restful风格,表示/user/1?id=1 表示此参数是从对应{id}里面拿,不从参数拿。required默认为ture,必传,设置为false,需要给value设置一个匹配url,使之url映射到此方法中。否则会报404错误。
   */

        @RequestMapping(value = {"user","user/{id}"},method = RequestMethod.GET)
    public String find(@PathVariable(value = "id",required = false) Integer id){
        System.out.println("查");
        return "success";
    }
  1. 接口统一 ,各种操作只需要一个url,由method识别

    /*
    现在浏览器不支持PUT和DELETE方法,只能在input方法的method
    
    <%-- 配合HiddenHttpMethodFilter过滤器检查真正的请求方法 --%> 改:
    设置过滤器检查真正的方法 restful org.springframework.web.filter.HiddenHttpMethodFilter restful /* */ @RequestMapping(value = "user",method = RequestMethod.POST) public String add(){ System.out.println("增"); return "success"; } @RequestMapping(value = "user/{id}",method = RequestMethod.DELETE) @ResponseBody public String del(Model model){ model.addAttribute("msg","删"); System.out.println("删"); return "success"; } @RequestMapping(value = "user/{id}",method = RequestMethod.PUT) @ResponseBody public String gai(Model model){ model.addAttribute("msg","改"); System.out.println("改"); return "success"; }
10. 文件上传
  1. 传统的文件上传
/*
传统的文件上传需要引入fileupload


    commons-fileupload
    commons-fileupload
    1.4

前端文件上传的三大条件
 1.必须是POST请求
 2.form表单必须有multipart/form-data类型
 3.必须type类型是file类型
*/
   public String file(HttpServletRequest res, Model model) throws FileUploadException {
        //得到上传路径
        String uploadname = getFilename(res);
        //得到文件解析器
        DiskFileItemFactory dsf = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(dsf);
        List fileItems = sfu.parseRequest(res);
        //对文件对象进行遍历
        fileItems.forEach(fileItem -> {
            if (fileItem.isFormField()){
                System.out.println(fileItem.toString());
            }else {
                String filename = uploadname+"/"+UUID.randomUUID().toString()+fileItem.getName();
                File distFile = new File(filename);
                try {
                    fileItem.write(distFile);
                    model.addAttribute("msg",distFile.getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        });
        return "success";
    }
    public String getFilename(HttpServletRequest res){
        String uploadname = res.getSession().getServletContext().getRealPath("upload");
        File dirFile = new File(uploadname);
        if (!dirFile.exists()){
            dirFile.mkdir();
        }
        return uploadname;
    }
  1. springMVC的文件上传

    /*
    注意两点
    1.配置文件解析器的时候名称必须是mulitpartReloveR 
    
          
      
    2.参数名是应该和前端的文件的name值一样
    */
        public String mvcFile(HttpServletRequest res, MultipartFile file,Model model) throws IOException {
            //得到上传路径
            String  filename = getFilename(res);
            System.out.println(file.getName());
            System.out.println(file.getOriginalFilename());
            System.out.println(file.getSize());
            File distFile = new File(filename + "/" + UUID.randomUUID().toString() + file.getOriginalFilename());
            //转移到目的文件
            file.transferTo(distFile);
            model.addAttribute("mag",distFile.getPath());
            return "success";
        }
    
11. 使用springMVC进行异常处理
/*
1.创建一个类实现HandlerExceptioEResolver
2.将这类添加到容器中
*/
public class ExHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        httpServletRequest.setAttribute("msg",e.getMessage());
        return mv;
    }
}
12. 拦截器
  1. 新建一个类实现HandlerInterceptor类
  2. 在MVC中配置文件中配置
public class CoustomInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行预处理方法了");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行后处理执行方法了");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行完成执行方法了");

    }
}

/*
/**代表/*拦截所有请求包括jsp文件的
*/
    
        
            
            
        
    

你可能感兴趣的:(springMVC)