Java EE --- Spring MVC 程序开发

x33g5p2x  于2022-06-06 转载在 Java  
字(6.5k)|赞(0)|评价(0)|浏览(336)

Spring MVC程序开发

1. 什么是 Spring MVC

Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架,从⼀开始就包含在 Spring 框架中。它的正式名称“Spring Web MVC”来⾃其源模块的名称(Spring-webmvc),但它通常被称为“SpringMVC”。

1.1 什么是 MVC

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

  • Model(模型) : 是应⽤程序中⽤于处理应⽤程序数据逻辑的部分。通常模型对象负责在数据库中存取数据。
  • View(视图) : 是应⽤程序中处理数据显示的部分。通常视图是依据模型数据创建的。
  • Controller(控制器) : 是应⽤程序中处理⽤户交互的部分。通常控制器负责从视图读取数据,控制⽤户输⼊,并向模型发送数据。

2. Spring MVC 的连接

在 Spring MVC 中 使用 @RequestMapping 来实现 URL 路由映射.

例如代码:

@Controller
public class UserController {

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(String name) {
        return "Hello! " + name;
    }
}

启动项目之后, 在 浏览器输入 http://localhost:8080/hello?name=SpringMVC

3. Spring MVC 中常用的注解

3.1 @RequestMappping

@RequestMapping是用来实现 URL 路由映射的.

@RequestMapping 既可以修饰方法, 也可以修饰类

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(String name) {
        return "Hello! " + name;
    }
}

访问http://localhost:8080/user/hello?name=SpringMVC

3.2 @GetMapping 和 @PostMapping

@GetMapping@PostMapping 都只能修饰方法, 不能修饰类

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/hello")
    @ResponseBody
    public String sayHello(String name) {
        return "Hello! " + name;
    }
}
@Controller
@RequestMapping("/user")
public class UserController {

    @PostMapping("/hello")
    @ResponseBody
    public String sayHello(String name) {
        return "Hello! " + name;
    }
}

3.3 三者区别

@GetMapping 是 GET 请求
@PostMapping 是 POST 请求
@RequestMapping 即支持 GET 请求 又 支持 POST 请求

GET请求的写法:

// 写法1
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    
    // 写法2
    @GetMapping("/hello")

POST 请求的写法:

// 写法1
    @RequestMapping(value = "/hello", method = RequestMethod.POST)

    // 写法2
    @PostMapping("/hello")

注意 : 当只写 @RequestMapping("/hello")的时候, 即支持POST请求,也支持GET请求

4. Spring MVC 中获取参数

4.1 传递单个参数

传递单个参数, 可以使用方法中的参数.
例如:

注意 : 这里的name和浏览器中输入的参数key要一致, 否则不能正确的获取

4.2 传递对象

现有一个 User 对象

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class User {
    public String name;
    public int age;
    public String sex;
}

传递对象的代码:

@RequestMapping("/register")
    @ResponseBody
    public Object Register( User user) {
        return user;
    }

4.3 传递多个参数

@RequestMapping("/login")
    @ResponseBody
    public String Login(String username,String password) {
        return username + " " + password;
    }

4.4 传递JSON对象

User对象如上面代码

@RequestMapping("/register")
    @ResponseBody
    public Object Register(@RequestBody User user) {
        return user;
    }

使用postman测试

4.5 后端参数重命名@RequestParam

如果前端传递的是一个time, 后端写不是time

解决办法

@RequestMapping("/test")
    @ResponseBody
    public String test(@RequestParam("time") String createtime){
        return "time: " + createtime;
    }

出现问题. 如果 这里没有time 就会报错.

解决办法

@RequestMapping("/test")
    @ResponseBody
    public String test(@RequestParam(value = "time",required = false) String createtime){
        return "time: " + createtime;
    }

4.6 获取URL中的参数 @PathVariable

@RequestMapping("/{name}/{age}")
    public String test(@PathVariable String name, @PathVariable String age){
        return "姓名: " + name + " " + "年龄: " + age;
    }

4.7 上传文件 @RequestPart

设置配置文件的环境

不同的环境配置一个文件, 每次只需要更改 application.properties 中的配置文件即可

application.properties中的内容

# 设置配置文件的环境
spring.profiles.active=dev

application-dev.properties中的内容

# 上传文件的路径
upload.path=E://logs//

注意: 这里的名称特别注意:

上传文件代码

注意这里的使用的是 UUID, 因为UUID不可能重复.
这里的 file.getOriginalFilename() 是获取了后缀的方法.

@Value("${upload.path}")
    public String uploadPath;

    @RequestMapping("/upload")
    public String Upload(@RequestPart("myfile") MultipartFile file) throws IOException {
        // 1. 上传文件目录
            String basePath = uploadPath;
        // 2. 生成动态的文件名
            String fileName = UUID.randomUUID() + (file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")));
        // 3. 保存文件
            file.transferTo(new File(basePath + fileName));
            return "上传成功";
    }

测试运行

使用 postman

Send之后查看路径下的目录

4.8 获取 Cookie/Session/header

@RequestMapping("/getCookie")
    public String GetCookie(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        // 获取所有的 Cookie 信息
        Cookie[] cookies = request.getCookies();
        String userAgent = request.getHeader("User-Agent");
        return name + "你好";
    }
@RequestMapping("/cookie")
    public String cookie(@CookieValue("bite") String bite) {
        return "cookie: " + bite;
    }

更简单的获取 Header — @RequestHeader

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

Session 存储和获取

存储 Session

@RequestMapping("/setsession")
    public String setSess(HttpServletRequest request) {
        // 这里的true 表示, 没有session对象就创建. false就是没有对象不创建
        HttpSession session = request.getSession(true);
        if(session != null){
            session.setAttribute("username","java");
        }
        return "session 存储成功";
    }

获取 Session

@RequestMapping("/getsession")
    public String getSess(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        String username = "暂无";
        if (session != null && session.getAttribute("username") != null) {
            username = (String) session.getAttribute("username");
         }
        return "username: " + username;
    }

更简单的获取 Session — @SessionAttribute

@RequestMapping("/getsession2")
    public String getSess2(@SessionAttribute(value = "username", required = false) String username) {
        return "username: " + username;
    }

4.9 返回数据

4.9.1 返回静态页面

@Controller
@RequestMapping("/user1")
public class UserController2 {
    @RequestMapping("/index")
    public Object reIndex() {
        return "/index.html";
    }
}

注意这里没有注解@ResponseBody

4.9.2 返回 text/html

@RequestMapping("/text")
    @ResponseBody
    public String reText() {
        return "<h1>HEllo!,MMMLL</h1>";
    }

4.9.3 返回 JSON 对象

@RequestMapping("/json")
    @ResponseBody
    public HashMap<String,String> reJson() {
        HashMap<String,String> map = new HashMap<>();
        map.put("JAVA","NB");
        map.put("MYSQL","NB");
        map.put("SPRING","NB");
        return map;
    }

4.9.4 请求转发和请求重定向

请求转发: forward 服务器帮客户进行请求转发并将结果响应给客户端, URL 地址是不变的
请求重定向: redirect 服务器端将请求重新定义到要访问的地址上, URL 地址会发生改变

请求转发和请求重定向的区别:

  1. 请求转发 URL 地址不变, 因为服务器端进行转发和响应.
    请求重定向 URL 地址发生改变, 因为服务器端直接将请求重定向到具体的地址上
  2. 使用请求转发那么有可能外部资源全部会丢失, 访问不到.
    请求重定向是直接重定向到 URL地址了, 所以不会存在外部资源丢失的情况

4.10 组合注解 @RestController

很多代码都会用到 @Controller 和 @ResponseBody , 这很复杂.
所以有了注解 @RestController, 这个注解就等于这两个注解.

5. idea 热部署

每次不需要重新启动, 就可以直接查看更新后的代码的效果

2.1 在 idea 中引入依赖

2.2 在 idea 的 setting 中开启自动编译

2.3 开启热部署

idea 2021版之前的版本

在全局搜索中, 搜 Registry

在这里搜索 compiler.automake.allow.when.app.running, 然后勾选上.

idea 2021版的

在Settings 中直接设置

2.4 直接debug就可以了

注意使用debug

开发者涨薪指南

48位大咖的思考法则、工作方式、逻辑体系

相关文章

微信公众号

最新文章

更多