SpringMVC使用

文章目录

一.MVC基础概念

1.MVC定义

MVC 是 Model View Controller 的缩写,它是软件⼯程中的⼀种软件架构模式,它把软件系统分为模型、视图和控制器三个基本部分

  • Model:处理程序数据的逻辑部分
  • View: 处理显示数据的部分
  • Controller:处理服务器与用户交互的部分

2.SpringMVC和MVC的关系

MVC是一种思想,SpringMVC是框架,有MVC的具体实现

二.SpringMVC的使用

代码样例:

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
@Controller // 让 spring 框架启动时,加载

@ResponseBody // 返回⾮⻚⾯数据

@RequestMapping("/user") // 路由器规则注册

public class UserController {
 // 路由器规则注册

 @RequestMapping("/hi")
 public String sayHi(){
 return "<h1>Hi,Spring MVC.</h1>";
 }
}

1.@RequestMapping

@RequestMapping是Spring MVC中的一个注解,用于处理请求地址映射。

@RequestMapping的六个属性如下:

  • value:指定请求的实际地址,指定的地址可以是URI Template模式。
  • method:指定请求的method类型,如GET、POST、PUT、DELETE等。
  • consumes:指定处理请求的提交内容类型(Content-Type),例如application/json,text/html。
  • produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。
  • params:指定request中必须包含某些参数值才让该方法处理。
  • headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

2.获取参数

1.获取单个参数

URL http://127.0.0.1:8080/hello?name=张三

@RequestMapping("/m1")

public Object method_1(String name){
 System.out.println("参数 name:"+name);
 return "/index.html";
}
如果post在body中的name=张三,那么不能够传递

2.传递对象

@Data

public class Person {
 private int id;
 private String name;
 private String password;
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@RequestMapping("/m2")
public Object method_2(Person p){
 System.out.println("对象中的 name:"+p.getName());
 System.out.println("对象中的 password:"+p.getPassword());
 return "/index.html";
}

URL:http://127.0.0.1:8080/hello?name=张四\&password=120

注意

当有多个参数时,前后端进⾏参数匹配时,是以参数的名称进⾏匹配的,因此参数的位置是不影响后端获取参数的结果。

3.后端参数重命名(后端参数映射)

如果前端传递的参数和我们后端接受的名字冲突,这时候就需要重命名

@RequestMapping("/m4")

public Object method_4(@RequestParam("time") String createtime) {
 System.out.println("时间:" + createtime);
 return "/index.html";
}

4.获取URL中参数@PathVariable

@PostMapping("/m6/{name}/{password}")

public Object method_6(@PathVariable String name, @PathVariable String pass
word) {
 System.out.println("name:" + name);
 System.out.println("password:" + password);
 return "redirect:/index.html";
}

{}的值要和形参中的name对应

5.上传文件@RequestPart

@RequestMapping("/param9")

public String param9(String name, @RequestPart("myfile") MultipartFile file) throws IOException {
 // 获取⽂件后缀名
 String fileName = file.getOriginalFilename().substring(file.getOrigina
lFilename().lastIndexOf("."));
 // ⽂件保存地址
 String filePath = ClassUtils.getDefaultClassLoader().getResource("	").getPath() + "/" + UUID.randomUUID() + fileName;
 // 保存⽂件
 file.transferTo(new File(filePath));
 return filePath + " 上传成功.";
}
  • @RequestPart注解用于将HTTP请求的一部分映射到控制器处理方法的参数中,通常用于处理multipart/form-data类型的请求

获取项⽬⽬录的⼏种⽅式:

ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();

new ClassPathResource("").getFile().getAbsolutePath();

ClassUtils.getDefaultClassLoader().getResource("").getPath();

ResourceUtils.getFile("classpath:static/").getPath();

6.获取Cookie/Session/header

获取 Request 和 Response 对象

@RequestMapping("/param10")

public String param10(HttpServletResponse response, HttpServletRequest requ
est) {
 String name = request.getParameter("name");
 // 获取所有 cookie 信息

 Cookie[] cookies = request.getCookies();
 return name + " 你好.";
}

这就到了我们熟悉的Servlet环节了

简洁的获取 Cookie---@CookieValue

@RequestMapping("/cookie")
@ResponseBody

public String cookie(@CookieValue("bite") String bite) {
 return "cookie:" + bite;
}

简洁获取 Header---@RequestHeader

@RequestMapping("/header")
@ResponseBody

public String header(@RequestHeader("User-Agent") String userAgent) {
 return "userAgent:"+userAgent;
}

获取 Session 更简洁的⽅式:

@RequestMapping("/sess2")
@ResponseBody

public String sess2(@SessionAttribute(value = "username",required = false) 

String username) {
 return "username:"+username;
}

3.返回数据

1.返回静态⻚⾯

@Controller

@RequestMapping("/p")

public class PersonController {
 @RequestMapping("/index")
 public Object index(){
 // 执⾏业务...

 // 返回view -> index.html

 return "/index.html";  
 }
}

2.返回 JSON 对象

@RequestMapping("/m8")
@ResponseBody

public HashMap<String, String> method_8() {
 HashMap<String, String> map = new HashMap<>();
 map.put("Java", "Java Value");
 map.put("MySQL", "MySQL Value");
 map.put("Redis", "Redis Value");
 return map;
}

添加ResponseBody自动将返回值转换为json格式

3.请求转发或请求重定向

forward VS redirect

return 不但可以返回⼀个视图,还可以实现跳转,跳转的⽅式有两种:

forward 是请求转发;

redirect:请求重定向。

// 请求重定向

@RequestMapping("/index")

public String index(){
 return "redirect:/index.html";
}

// 请求转发

@RequestMapping("/index2")

public String index2(){
 return "forward:/index.html";
}

两者区别

  1. 请求重定向(redirect)将请求重新定位到资源;请求转发(forward)服务器端转发。

  2. 请求重定向地址发⽣变化,请求转发地址不发⽣变化。

  3. 请求重定向与直接访问新地址效果⼀直,不存在原来的外部资源不能访问;请求转发服务器端转发

    有可能造成原外部资源不能访问。

  4. 前者客户端会进行两次请求,后者一次即可

4.@ResponseBody 说明

@ResponseBody 返回的值如果是字符会转换成 text/html,如果返回的是对象会转换成

application/json 返回给前端。

@ResponseBody 可以⽤来修饰⽅法或者是修饰类,修饰类表示类中的所有⽅法都会返回 html 或者

json,⽽不是视图。

相关推荐
众智创新团队7 分钟前
Android的Activity生命周期知识点总结,详情
android·java·开发语言
&岁月不待人&12 分钟前
Android 常用设计模式和实例
java·开发语言·设计模式
musir118 分钟前
UDP小实验
网络·网络协议·udp
qq_139484288221 分钟前
springboot239-springboot在线医疗问答平台(源码+论文+PPT+部署讲解等)
java·数据库·spring boot·后端·spring·maven·intellij-idea
蔚一22 分钟前
微服务SpringCloud Alibaba组件nacos教程【详解naocs基础使用、服务中心配置、集群配置,附有案例+示例代码】
java·后端·spring cloud·微服务·架构·intellij-idea·springboot
神仙别闹25 分钟前
基于Springmvc+MyBatis+Spring+Bootstrap+EasyUI+Mysql的个人博客系统
java·mysql·ssm
计算机小白一个29 分钟前
蓝桥杯 Java B 组之函数定义与递归入门
java·算法·职场和发展·蓝桥杯
用键盘当武器的秋刀鱼1 小时前
Spring boot(maven) - Mybatis 超级入门版
java·spring boot·mybatis
管大虾1 小时前
设计模式-适配器模式
java·设计模式·适配器模式
Shinka-深深2 小时前
《图解设计模式》笔记(八)管理状态
java·笔记·设计模式