SringMVC框架入门

简介: SringMVC框架入门

视图解析器


 视图解析器:将页面路径部分添加到配置文件中

image.png

 

没有视图解析器


return "/WEB-INF/show01.jsp";

     

有了视图解析器


return "show01.jsp";

 

 SpringMVC中配置视图解析器 设置前缀和后缀 把视图解析器放入Spring容器


    @Bean
    public InternalResourceViewResolver viewResolver(){
        //创建视图解析器
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        //设置前缀
        viewResolver.setPrefix("/WEB-INF/");
        //设置后缀
        viewResolver.setSuffix(".jsp");
        return viewResolver;


异常处理器


       在SpringMVC中 提供了一个全局异常处理器 对于系统中的异常进行统一处理 在一般系统中 Dao Service Controller 出现异常都往上throws Exception 最后由SpringMVC的前端控制器进行统一的全局异常处理


一般都是自定义异常 然后解析该异常 判断该异常属于那种异常 对其进行处理 若非自定义异常 在


报错系统错误 请与管理员联系异常


第一步自定义异常


public class CustomException extends Exception{
    private static final long serialVersionUID = 8222256702797084775L;
    public CustomException() {
    }
    public CustomException(String message) {
        super(message);
    }
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
    public CustomException(Throwable cause) {
        super(cause);
    }
    public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


第二步定义异常处理器


       异常处理器需要实现HandlerExceptionResolver接口 重写方法resolverException

@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        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;
    }
}


第三步 定义异常显示界面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    您的操作出现错误如下: <br>
    ${message}
</body>
</html>


第四步 测试程序


    @RequestMapping("index")
    public String index(String id) throws CustomException {
        if(id == null){
            throw new CustomException("没有id参数");
        }
        return "itemlist";
<a href = "${pageContext.request.contextPath}/user/index.aticon">异常演示</a>


异常处理器分析

image.png


拦截器


 概述


SpringMVC中的拦截器就像Servlet中的过滤器一样Filter 用于对处理器的前后顺序进行处理

拦截器需要实现接口:HandlerInterceptor


 分析


image.png

  方法



       boolean preHandle() :返回一个boolean值 返回true继续执行 返回false直接结束


       void postHandle() :在执行完处理器方法后 视图显示之前执行


       void afterCompletion() :在视图解析成功后执行


     

拦截器



 第一步定义拦截器 实现HandlerInterceptor接口


@Component
public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1拦截器的preHandle");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1拦截器的postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1拦截器的afterCompletion");
    }
}

 

第二步 配置类 注册拦截器 设置拦截路径


    @Autowired
    private MyInterceptor1 myInterceptor1;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor1);
        interceptorRegistration.addPathPatterns("/**");
    }

多拦截器配置

       分析


image.png  

配置类 注册拦截器


    @Autowired
    private MyInterceptor1 myInterceptor1;
    @Autowired
    private MyInterceptor2 myInterceptor2;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor1);
        interceptorRegistration.addPathPatterns("/**");
        InterceptorRegistration interceptorRegistration2 = registry.addInterceptor(myInterceptor2);
        interceptorRegistration2.addPathPatterns("/**");
    }

  使用场景

       1.用户名权限校验      

       2.解决乱码

       3.日志记录


文件上传


第一步定义上传页面


<form id="itemForm" action="${pageContext.request.contextPath }/user/upload.action" method="post" enctype="multipart/form-data">
    姓名:<input type="text" name="name"/> <br/>
    价格:<input type="text" name="price"/> <br/>
    图片:<input type="file" name="picFile"/> <br/>
    <input type="submit" value="提交" />
  </form>

     

第二步 Controller


    public String upload(String name, Double price, @RequestParam(required = false,value = "picFile") MultipartFile picFile) throws IOException {
        System.out.println("姓名:" + name);
        System.out.println("价格:" + price);
        String originalFilename = picFile.getOriginalFilename();
        System.out.println("上传文件名:" + originalFilename);
        File file = new File("F:\\Temp", originalFilename);
        picFile.transferTo(file);
        return "itemslist";
    }        

 

第三步配置中配置文件上传解析器


    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        // 设置所有的上传文件的总大小 10M
        multipartResolver.setMaxInMemorySize(10*1024*1024);
        // 设置单个文件上传的大小 4M
        multipartResolver.setMaxUploadSize(4*1024*1024);
        multipartResolver.setDefaultEncoding("utf-8");
        return multipartResolver;
    }

     导入jar包或坐标

       使用的commons-fileupload完成上传,确定导入fileupload jar包

image.png

  坐标

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.2</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.3</version>
</dependency>

 MultipartFile对象


       String getOriginalFilename() :获得长传的文件名


       transferTo(File file) :将文件上传到指定的文件


       String getContentType() :获得文件MIME类型


       String getName() :获得表单中文件组件的名字


JSON数据交互


@RequestBody:将json、xml转换为Java对象


    @RequestMapping("tj.action")
    public void run1(@RequestBody String jsonStr){
        System.out.println(jsonStr);
    }


 @ResponseBodey:将Java对象转换成json、xml


1.    @RequestMapping("tj.action")
    public @ResponseBody QVo getInfo(String name,Double price){
        System.out.println("接收到前端数据:" + name + " " + price);
        QVo qVo = new QVo("lisiguang", 220.4);
        return qVo;
    }


RESTful支持


       概述


       RESTful就是一个资源定位及资源操作的一种风格 不是标准也不是协议 只是一种风格


       资源定位 要求URL没有动词 只有名词 没有参数


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


       资源操作 通过HTTP请求方式 确定不同的请求


       get查询资源 post新建资源(也可以修改资源) put更新资源 delete删除资源


       @RequestMapping(value = "/user/{xxx}",method = RequestMethod.GET)


       {xxx}相当于占位符 用于匹配到URL中的参数 通过@PathVariable("xxx")获得路径匹配的资源

    @RequestMapping("/viewItems/{id}")
    public String viewItems(@PathVariable("id")String id, Model model){
        model.addAttribute("id",id);
        return "itemslist";
    }
相关文章
|
Python
pycharm正确配置国内镜像源的方式
配置国内镜像源和解决虚拟环境(Venv)中安装bs4或者其他的第三方库的错误 —— Could not find a version that satisfies the requirement bs4 国内镜像源推荐 阿里 mirrors.aliyun.com/pypi/simple… 清华 pypi.tuna.tsinghua.edu.cn/simple/ 豆瓣 pypi.douban.com/simple/ 注意这里都是 https 的,不然下载包的时候会出现其他
10920 0
|
机器学习/深度学习 计算机视觉
Siamese网络和Triplet网络
【10月更文挑战第1天】
|
存储 编译器
关于数据在内存中的存储(整形篇)
关于数据在内存中的存储(整形篇)
277 0
|
安全 Linux Shell
Linux 文件安全,用户访问安全|学习笔记
快速学习 Linux 文件安全,用户访问安全
Linux 文件安全,用户访问安全|学习笔记
|
JSON 算法 物联网
Coap协议接入物联网平台(java实现)
本文介绍基于开源的CoAP协议进行对称加密自主接入的流程,并提供java示例代码。
Coap协议接入物联网平台(java实现)
|
弹性计算 负载均衡 监控
如何做好性能压测:压测环境的设计和搭建
性能压测,是保障服务可用性和稳定性过程中,不可或缺的一环。我们将从性能压测的设计、实现、执行、监控、问题定位和分析、应用场景等多个纬度对性能压测的全过程进行拆解,以帮助大家构建完整的性能压测的理论体系,并提供有例可依的实战。 01 性能环境要考虑的要素 系统逻辑架构,即组成系统的组件、应用之间的结构、交互关系的抽象。最简单最基本的就是这三层架构。 三层逻辑结构图 - 客户层:用户请
|
Ruby
RvmTranslator 3.0 is released
RvmTranslator 3.0 is released Enable translate multiple RVM files for RvmTranslator. Translate multiple RVM files in RvmTranslator is simple, just inp...
1700 0
|
C语言
OpenWrt编译
OpenWrt编译简单过程1,OpenWrt编译环境准备sudo apt-get install gcc g++ binutils patch bzip2 flex bison make autoconf gettext texinfo unzip sharutils subversion libn...
1334 0
|
XML 存储 安全
初识WCF之使用配置文件部署WCF应用程序
     二月份的开头,小编依旧继续着项目开发之路,开始接触全新的知识,EF,WCF,MVC等,今天小编来简单的总结一下有关于WCF的基础知识,学习之前,小编自己给自己提了两个问题,WCF是什么?WCF能用来做什么?WCF具有哪些优点?带着这样的问题,小编开始进行了一番搜索,一下是小编整理的结果。
1531 0
下一篇
开通oss服务