1、创建springboot项目,勾选Spring web
- 当前springboot选择的是2.6.13版本,jdk1.8
- 尽量选2.几的springboot
2、在pom.xml中导入相应的坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、配置application.yml,按需配置,可选
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypassword
driver-class-name: com.mysql.cj.jdbc.Driver
servlet:
multipart:
max-file-size: 10MB # 设置单个文件最大上传大小
max-request-size: 50MB # 设置请求的最大总数据大小
enabled: true # 开启文件上传支持
format:
date-time-patterns:
- yyyy-MM-dd HH:mm:ss # 日期时间格式
-
mvc:
static-path-pattern: /static/** # 指定静态资源的访问路径模式
resources:
static-locations: file:/path/to/your/static/files/ # 指定静态资源文件的存储位置
view:
prefix: /WEB-INF/views/ # view前缀
suffix: .jsp # view后缀,如:.jsp
4、创建controller包,报下新建UserController进行测试
package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("hello")
public String test(){
return "hello ssm";
}
}
//访问http://localhost:8080/user/hello,返回hello ssm即为测试成功
5、访问静态资源
默认的静态资源路径为:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/(一般放置在这个文件夹下)
classpath:/public/
只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理
6、相关注解
1、@RequestMapping
- 用于Controller类、类中方法上,用来处理请求地址映射的注解
- @RequestMapping(value = “/login”,produces = “application/json;charset=utf-8”, method = RequestMethod.GET)
- value:url的值,
- method:提交方式 ,get或者post
- produces:指定响应体返回类型和编码
- @GetMapping,与@RequestMapping作用一致,但指定必须为get请求,且只能用在类上
- @PostMapping,与@RequestMapping作用一致,但指定必须为post请求,且只能用在类上
2、@RequestParam
- 用于Controller类的方法参数前,如4中test()如果有参数,即可使用test(@RequestParam String name)
- @RequestParam(value=“username”, required=true, defaultValue=“zhang”) String name)
- value表示 入参的请求参数名字,前端传过来的必须和这个名称一样
- required默认值是true,意思为该参数必传
- defaultValue表示默认值,当前设定为zhang
- 注解可用于map与对象:test(@RequestParam Map query)、test(@RequestParam User user)
3、@RequestBody
- 用于Controller类的方法上,效果是接收JSON数据
4、@PathVariable
- 拥有绑定url中的占位符的。例如:url中有/delete/{id},{id}就是占位符
- deleteById(@PathVariable (“id”) String uid):将占位符{id}的值绑定给了形参uid
5、@ResponseBody
-
用于Controller类的方法上,效果是返回JSON数据给前端。
-
返回值一般写AjaxResult
-
AjaxResult工具类
package com.pj.util; import java.io.Serializable; import java.util.List