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";
    }
相关文章
|
存储 前端开发 数据可视化
老码农花3分钟给老爸做了个生日祝福的APP,他是怎么做到的呢?
老码农花3分钟给老爸做了个生日祝福的APP,他是怎么做到的呢?
359 1
|
9天前
|
域名解析 人工智能 Linux
|
19天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17717 63
|
17天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
3天前
|
人工智能 安全 网络安全
|
7天前
|
云安全 数据采集 人工智能
|
8天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1399 5
|
14天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2446 8
|
19天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
3971 22
|
21天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是DeepSeek AI开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、跑命令、处理表格、联网搜索等操作。免费开源,兼容Windows/macOS/Linux,提供桌面端与网页端,可灵活安装插件扩展能力。

热门文章

最新文章