Spring Web MVC is the original web framework built on the Servlet API and has beenincluded in the Spring Framework from the very beginning. The formal name, “Spring WebMVC,” comes from the name of its source module ( spring-webmvc ), but it is more commonly known as “Spring MVC”.引用来自: https://docs.spring.io/springframework/docs/current/reference/html/web.html#spring-web
Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架,从一开始就包含在 Spring 框架中。它的正式名称“Spring Web MVC” 来自其源模块的名称 (Spring-webmvc) ,但它通常被称为 “Spring MVC”。
1. 连接的功能 :将用户(浏览器)和 Java 程序连接起来,也就是访问一个地址能够调用到我们的 Spring 程序。2. 获取参数的功能 :用户访问的时候会带一些参数,在程序中要想办法获取到参数。3. 输出数据的功能 :执行了业务逻辑之后,要把程序执行的结果返回给用户。对于 Spring MVC 来说,掌握了以上 3 个功能就相当于掌握了 Spring MVC 。
接下来,创建一个 UserController 类,实现用户到 Spring 程序的互联互通,具体实现代码如下:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller // 让 spring 框架启动时,加载
@ResponseBody // 返回一个 text/html 信息
@RequestMapping("/user") // 路由器规则注册
public class UserController {
// 路由器规则注册
@RequestMapping("/hi")
public String sayHi(){
return "Hi,Spring MVC.
";
}
}
import com.example.demo.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/p")
public class PersonController {
@RequestMapping("/index")
public Object index(Person person){
// 获取参数
System.out.println(person.getName() +":"+
person.getPassword());
// 执行业务...
return "/index.html";
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody // 定义返回的数据格式为非视图(text/html)
public class UserController {
@RequestMapping("/hi")
public String sayHi(){
return "Hi,Spring MVC.
";
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody // 定义返回的数据格式为非视图(text/html)
public class UserController {
@RequestMapping(value = "/hi",method= RequestMethod.POST)
public String sayHi(){
return "Hi,Spring MVC.
";
}
}
// 写法1
@RequestMapping("/index")
// 写法2
@RequestMapping(value = "/index",method = RequestMethod.GET)
// 写法3
@GetMapping("/index")
// 写法1
@RequestMapping(value = "/index",method = RequestMethod.POST)
// 写法2
@PostMapping("/index")
@RequestMapping("/m1")
public Object method_1(String name){
System.out.println("参数 name:"+name);
return "/index.html";
}
程序的执行结果:
import lombok.Data;
@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";
}
最终执行结果:
@RequestMapping("/m3")
public Object method_3(String name, String pwd) {
System.out.println("name 参数:" + name);
System.out.println("pwd 参数:" + pwd);
return "/index.html";
}
前台访问地址:
@RequestMapping("/m4")
public Object method_4(@RequestParam("time") String createtime) {
System.out.println("时间:" + createtime);
return "/index.html";
}
非必传参数设置
@RequestMapping("/m4")
public Object method_4(@RequestParam(value = "time", required = false) String
createtime) {
System.out.println("时间:" + createtime);
return "/index.html";
}
后端接收代码:
@RequestMapping(value = "/m5", method = RequestMethod.POST)
public Object method_5(@RequestBody Person person) {
System.out.println("Person:" + person);
return "redirect:/index.html";
}
尝试去除掉 @RequestBody 试试。
@PostMapping("/m6/{name}/{password}")
public Object method_6(@PathVariable String name, @PathVariable String password)
{
System.out.println("name:" + name);
System.out.println("password:" + password);
return "redirect:/index.html";
}
@RequestMapping("/param9")
public String param9(String name, @RequestPart("myfile") MultipartFile file)
throws IOException {
// 获取文件后缀名
String fileName =
file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")
);
// 文件保存地址
String filePath =
ClassUtils.getDefaultClassLoader().getResource("static").getPath() +
"/" + UUID.randomUUID() + fileName;
// 保存文件
file.transferTo(new File(filePath));
return filePath + " 上传成功.";
}
获取项目目录的几种方式:
ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
new ClassPathResource("").getFile().getAbsolutePath();
ClassUtils.getDefaultClassLoader().getResource("").getPath();
ResourceUtils.getFile("classpath:static/").getPath();
@RequestMapping("/param10")
public String param10(HttpServletResponse response, HttpServletRequest request)
{
String name = request.getParameter("name");
// 获取所有 cookie 信息
Cookie[] cookies = request.getCookies();
return name + " 你好.";
}
@RequestMapping("/param10")
@ResponseBody
public String param10(HttpServletResponse response, HttpServletRequest request)
{
String name = request.getParameter("name");
// 获取所有 cookie 信息
Cookie[] cookies = request.getCookies();
String userAgent = request.getHeader("User-Agent");
return name + ":"+userAgent;
}
@RequestMapping("/cookie")
@ResponseBody
public String cookie(@CookieValue("bite") String bite) {
return "cookie:" + bite;
}
@RequestMapping("/header")
@ResponseBody
public String header(@RequestHeader("User-Agent") String userAgent) {
return "userAgent:"+userAgent;
}
@RequestMapping("/setsess")
@ResponseBody
public String setsess(HttpServletRequest request) {
// 获取 HttpSession 对象,参数设置为 true 表示如果没有 session 对象就创建一个
session
HttpSession session = request.getSession(true);
if(session!=null){
session.setAttribute("username","java");
}
return "session 存储成功";
}
读取 Session 可以使用 HttpServletRequest,如下代码所示:
@RequestMapping("/sess")
@ResponseBody
public String sess(HttpServletRequest request) {
// 如果 session 不存在,不会自动创建
HttpSession session = request.getSession(false);
String username = "暂无";
if(session!=null && session.getAttribute("username")!=null){
username = (String) session.getAttribute("username");
}
return "username:"+username;
}
获取 Session 更简洁的方式:
@RequestMapping("/sess2")
@ResponseBody
public String sess2(@SessionAttribute(value = "username",required = false)
String username) {
return "username:"+username;
}
hello,spring mvc
Hello,Spring MVC.
创建控制器 controller:
import com.example.demo.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/p")
public class PersonController {
@RequestMapping("/index")
public Object index(){
// 执行业务...
// 返回view -> index.html
return "/index.html";
}
}
@RequestMapping("/m7")
@ResponseBody
public String method_7() {
return "Hello,HTML~
";
}
计算器示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@ResponseBody
@Controller
@RequestMapping("/calc")
public class CalcController {
@RequestMapping("/sum")
public String sum(Integer num1,Integer num2){
return String.format("计算的结果是:%d
返回",num1+num2);
}
}
@RequestMapping("/m8")
@ResponseBody
public HashMap method_8() {
HashMap map = new HashMap<>();
map.put("Java", "Java Value");
map.put("MySQL", "MySQL Value");
map.put("Redis", "Redis Value");
return map;
}
@RequestMapping(value = "/login")
@ResponseBody
public HashMap login(String username, String password){
HashMap res = new HashMap<>();
int succ = 200;
if(username!=null && password!=null &&
username.equals("admin") && password.equals("admin")){
res.put("msg","登录成功");
}else{
res.put("msg","登录失败");
}
res.put("succ",succ);
return res;
}
前端代码:
Document
登录
用户:
密码:
// 请求重定向
@RequestMapping("/index")
public String index(){
return "redirect:/index.html";
}
// 请求转发
@RequestMapping("/index2")
public String index2(){
return "forward:/index.html";
}
程序的执行结果如下:
尝试将转发 foward 换成重定向 redirect,如下代码所示:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/index")
public String sayHi(){
return "redirect:/index.html";
}
}
页面就可以正常获取到外部资源 js 了。
官方 API : https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvcann-requestmapping