1、创建springboot项目,勾选Spring web
- 当前springboot选择的是2.6.13版本,jdk1.8
- 尽量选2.几的springboot
2、在pom.xml中导入相应的坐标
java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、配置application.yml,按需配置,可选
xml
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进行测试
java
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、访问静态资源
java
默认的静态资源路径为:
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工具类
javapackage com.pj.util; import java.io.Serializable; import java.util.List; /** * ajax请求返回Json格式数据的封装 */ public class AjaxJson implements Serializable{ private static final long serialVersionUID = 1L; // 序列化版本号 public static final int CODE_SUCCESS = 200; // 成功状态码 public static final int CODE_ERROR = 500; // 错误状态码 public static final int CODE_WARNING = 501; // 警告状态码 public static final int CODE_NOT_JUR = 403; // 无权限状态码 public static final int CODE_NOT_LOGIN = 401; // 未登录状态码 public static final int CODE_INVALID_REQUEST = 400; // 无效请求状态码 public int code; // 状态码 public String msg; // 描述信息 public Object data; // 携带对象 public Long dataCount; // 数据总数,用于分页 /** * 返回code * @return */ public int getCode() { return this.code; } /** * 给msg赋值,连缀风格 */ public AjaxJson setMsg(String msg) { this.msg = msg; return this; } public String getMsg() { return this.msg; } /** * 给data赋值,连缀风格 */ public AjaxJson setData(Object data) { this.data = data; return this; } /** * 将data还原为指定类型并返回 */ @SuppressWarnings("unchecked") public <T> T getData(Class<T> cs) { return (T) data; } // ============================ 构建 ================================== public AjaxJson(int code, String msg, Object data, Long dataCount) { this.code = code; this.msg = msg; this.data = data; this.dataCount = dataCount; } // 返回成功 public static AjaxJson getSuccess() { return new AjaxJson(CODE_SUCCESS, "ok", null, null); } public static AjaxJson getSuccess(String msg) { return new AjaxJson(CODE_SUCCESS, msg, null, null); } public static AjaxJson getSuccess(String msg, Object data) { return new AjaxJson(CODE_SUCCESS, msg, data, null); } public static AjaxJson getSuccessData(Object data) { return new AjaxJson(CODE_SUCCESS, "ok", data, null); } public static AjaxJson getSuccessArray(Object... data) { return new AjaxJson(CODE_SUCCESS, "ok", data, null); } // 返回失败 public static AjaxJson getError() { return new AjaxJson(CODE_ERROR, "error", null, null); } public static AjaxJson getError(String msg) { return new AjaxJson(CODE_ERROR, msg, null, null); } // 返回警告 public static AjaxJson getWarning() { return new AjaxJson(CODE_ERROR, "warning", null, null); } public static AjaxJson getWarning(String msg) { return new AjaxJson(CODE_WARNING, msg, null, null); } // 返回未登录 public static AjaxJson getNotLogin() { return new AjaxJson(CODE_NOT_LOGIN, "未登录,请登录后再次访问", null, null); } // 返回没有权限的 public static AjaxJson getNotJur(String msg) { return new AjaxJson(CODE_NOT_JUR, msg, null, null); } // 返回一个自定义状态码的 public static AjaxJson get(int code, String msg){ return new AjaxJson(code, msg, null, null); } // 返回分页和数据的 public static AjaxJson getPageData(Long dataCount, Object data){ return new AjaxJson(CODE_SUCCESS, "ok", data, dataCount); } // 返回,根据受影响行数的(大于0=ok,小于0=error) public static AjaxJson getByLine(int line){ if(line > 0){ return getSuccess("ok", line); } return getError("error").setData(line); } // 返回,根据布尔值来确定最终结果的 (true=ok,false=error) public static AjaxJson getByBoolean(boolean b){ return b ? getSuccess("ok") : getError("error"); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @SuppressWarnings("rawtypes") @Override public String toString() { String data_string = null; if(data == null){ } else if(data instanceof List){ data_string = "List(length=" + ((List)data).size() + ")"; } else { data_string = data.toString(); } return "{" + "\"code\": " + this.getCode() + ", \"msg\": \"" + this.getMsg() + "\"" + ", \"data\": " + data_string + ", \"dataCount\": " + dataCount + "}"; } }
7、请求转发和重定向
1、forward请求转发
java
/*** 使用forward关键字进行请求转发 * "forward:转发的JSP路径",不走视图解析器了,所以需要编写完整的路径 * @return * @throws Exception */
@RequestMapping("/delete")
public String delete() throws Exception {
System.out.println("delete方法执行了...");
// return "forward:/WEB-INF/pages/success.jsp";
return "forward:/user/findAll";
}
2、redirect重定向
java
/*** 重定向 * @return * @throws Exception */
@RequestMapping("/count")
public String count() throws Exception {
System.out.println("count方法执行了...");
return "redirect:/add.jsp";
// return "redirect:/user/findAll"; }
}
8、拦截器
1、新建Interceptor包,包下新建MyHandlerInterceptor文件
java
package com.example.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre Handle: " + request.getMethod() + " " + request.getRequestURI());
System.out.println("在控制器方法调用之前执行");
return true; // 继续处理请求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Post Handle: " + request.getRequestURI());
System.out.println("在控制器方法调用之后执行,但在视图渲染之前");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("After Completion: " + request.getRequestURI());
System.out.println("在整个请求完成后执行,无论是否出现异常");
}
}
2、XML 配置
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:interceptors>
<bean class="com.example.Interceptor.MyHandlerInterceptor" />
</mvc:interceptors>
</beans>
3、新建config包,包下新建WebMvcConfigurer文件
java
package com.example.config;
import com.example.Interceptor.MyHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor())
.addPathPatterns("/**") // 指定拦截器的应用路径
.excludePathPatterns("/resources/**", "/static/**"); // 排除静态资源
}
}