一、Sprig MVC简介1.1介绍1.2MVC是什么 二、Spring MVC实现原理2.1核心组件2.2工作流程 三、第一个Spring MVC四、常用注解五、参数绑定5.1URL风格参数绑定5.2RESTful风格
文章是看楠哥的视频做的总结,自己还查阅了一些资料,文章也加了自己的总结,这篇博客可以帮助大家入门,还有一些知识大家如果用到的话可以到时候再去学习一下,我写这篇主要是为了方便后面复习。
spring MVC是Spring Framework提供的WEB组件,全称是Spring Web MVC,是目前主流的实现MVC设计模式的框架,提供前端路由映射、视图解析等功能
Java web开发者必须要掌握的技术框架
MVC是一种软件架构思想,把软件按照模型,视图,控制器来划分
Model:模型层,指工程中的JavaBean,用来处理数据
JavaBean分成两类:
4.0.0 org.example springMVC 1.0-SNAPSHOT war SpringMVC Maven Webapp Http://www.example.com UTF-8 1.8 1.8 junit junit 4.11 test org.springframework spring-webmvc 5.3.19
org.springframework spring-webmvc 5.3.19
然后在web.xml 配置Spring MVC的DispatcherServlet
Archetype Created Web Application dispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 dispatcherServlet System.out.println("接收到了请求"); //返回逻辑视图 逻辑视图相当于视图的别名 通过这个找到物理视图,也就是真正的视图 //这里返回的只是页面的名称,不是完整的页面访问路径 return "index"; }}
@Controller注解是为了让Spring ioc容器初始化时自动扫描到该Controller类;@RequestMapping是为了映射请求路径,这里因为类与方法上都有映射所以访问时应该是/;方法返回的结果是视图的名称index,该名称不是完整页面路径,最终会经过视图解析器解析为完整页面路径并跳转。
配置Tomcat
5. 测试
流程梳理
Spring MVC搭建成功
@RequestMapping
Spring MVC通过@RequestMapping注解把URL请求和业务方法进行映射,在控制器的类定义处以及方法定义处都可以添加@RequestMapping,在类定义处添加相当于多了一层访问路径
@RequestMapping常用参数
- value:指定URL请求的实际地址,是@RequestMapping的默认值
- method:指定请求的method类型,包括GET、POST、PUT、DELETE等
@RequestMapping(value = "/index",method = RequestMethod.POST) public String index(){ System.out.println("接收到了请求"); //返回逻辑视图 逻辑视图相当于视图的别名 通过这个找到物理视图,也就是真正的视图 //注意:这里返回的只是页面名称,不是完整的页面访问路径 return "index"; }
上述代码表示只有POST请求可以访问该方法,如果使用其他请求访问的话,直接抛出异常,比如GET请求
- params:指定request请求中必须包含的参数值,如果不包含的话,就无法调用该方法
params是对URL请求参数进行限制,不满足条件的URL无法访问该方法,需要在业务方法中获取URL的参数值。
Spring MVC可以自动完成数据类型转换,该工作是由HandlerAdapter来完成的
@RequestMapping("/restful/{id}/{name}") public String restful(@PathVariable("id") Integer num, @PathVariable("name") String name){ System.out.println(num+"-"+name); return "index"; }
@RequestMapping("/cookie") public String getCookie(@CookieValue("JSESSIONID") String sessionId){ System.out.println(sessionId); return "index"; }
Spring MVC会根据请求参数名和POJO属性名进行匹配,自动为该对象填充属性值,并且支持属性级联
首先创建实体类
为了方便测试,写一个addUser.jsp页面
<%-- Created by IntelliJ IDEA. User: 17614 Date: 2022-07-04 Time: 21:01 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %> Title
然后在Handler中,编写相关方法
启动Tomcat服务器
结果发现出现乱码问题
为了解决这个问题,我们只需要在web.xml配置文件中配置过滤器就可以了
encodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 encodingFilter @Controller@RequestMapping("/course")public class CourseController { @Autowired private CourseRepository courseRepository; @GetMapping("/findAll") public ModelAndView findAll() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("courseList"); modelAndView.addObject("list", courseRepository.findAll()); return modelAndView; } @DeleteMapping("/deleteById/{id}") public String deleteById(@PathVariable("id") Integer id){ courseRepository.deleteById(id); return "redirect:/course/findAll"; } @PostMapping("/save") public String save(Course course) { courseRepository.saveOrUpdate(course); return "redirect:/course/findAll"; } @GetMapping("/findById/{id}") public ModelAndView findById(@PathVariable("id") Integer id) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("edit"); modelAndView.addObject("courser", courseRepository.findById(id)); return modelAndView; } @PutMapping("/update") public String update(Course course){ courseRepository.saveOrUpdate(course); return "redirect:/course/findAll"; }}
JSP
courseList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page isELIgnored="false" %> Title 编号: 名称: 价格: 操作: ${course.id} ${course.name} ${course.price} 修改
save.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> Title
edit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page isELIgnored="false" %> Title
点击删除
点击修改
点提交
底层使用的是Apache fileupload 组件完成上传功能,Spring MVC只是对其进行了封装,简化开发,pom.xml
commons-io commons-io 2.8.0 commons-fileupload commons-fileupload 1.4
springmvc.xml
为了把二进制数据解析成对象
JSP页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@page isELIgnored="false" %> Title
@Component@RequestMapping("/file")public class FileHandler { @PostMapping("/upload") public String upload(@RequestParam("img") MultipartFile img, httpservletRequest request){ if (img.getSize()>0){ String path = request.getSession().getServletContext().getRealPath("file"); String filename = img.getOriginalFilename(); File descFile=new File(path, filename); try { img.transferTo(descFile); request.setAttribute("src", "/file/"+filename); } catch (IOException e) { e.printStackTrace(); } } return "upload"; }}
然后选择文件
提交
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@page isELIgnored="false" %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 多文件上传
@PostMapping("/uploads") public String uploads(@RequestParam("imgs") MultipartFile[] imgs,HttpServletRequest request){ List pathList=new ArrayList<>(); for (MultipartFile img:imgs){ if (img.getSize()>0){ String path = request.getSession().getServletContext().getRealPath("file"); String filename = img.getOriginalFilename(); File descFile=new File(path, filename); try { img.transferTo(descFile); pathList.add("/file/"+filename); } catch (IOException e) { e.printStackTrace(); } } } request.setAttribute("pathList", pathList); return "uploads"; }
JSP页面通过超链接点击进行下载
<%@ page contentType="text/html;charset=UTF-8" language="java" %> 文件下载 皮卡丘.jpg 柯南.png springmvc.png
Handler
@GetMapping("/download") public void download(String fileName, HttpServletRequest request, HttpServletResponse response) { if (fileName!=null){ String path = request.getSession().getServletContext().getRealPath("file"); File file=new File(path,fileName); OutputStream out=null; if (file.exists()){ //设置下载文件 response.setContentType("applicationContext/force-download"); //设置文件名 response.setHeader("Context-Disposition", "attachment;filename="+fileName); try { out=response.getOutputStream(); out.write(FileUtils.readFileToByteArray(file)); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if (out!=null){ try {out.close(); } catch (IOException e) {e.printStackTrace(); } } } } } }
拦截器配置1
拦截器配置方式2
preHandle方法..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("3.目标Handler执行后,视图执行前执行MyInterceptor2---->postHandle方法..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("5.目标Handler执行后,视图执行后执行MyInterceptor2---->afterCompletion方法..."); }}
Handler
@RequestMapping("/hello")@Controllerpublic class HelloContro @RequestMapping("/packageType") @ResponseBody public String packageType(@RequestParam(value = "id", required = true) Integer id) { System.out.println("拦截的方法..."); return "id=" + id; }}
来源地址:https://blog.csdn.net/qq_52797170/article/details/125591705
--结束END--
本文标题: Spring MVC详解(学习总结)
本文链接: https://www.lsjlt.com/news/372149.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0