政务网站建设标准在线培训管理系统
目录
SpringMVC
1、MVC定义
2、MVC和SpringMVC之间的关系
学SpringMVC
1、Spring MVC的创建和连接
浏览器获取前端接口和后端程序连接功能实现
2、获取参数
2.1、传递单个参数/多个参数
2.2、传递对象
2.3、传递表单参数
2.4、后端参数重命名
2.5、@RequestBody接收JSON对象
2.6、获取URL中的参数@PathVariable
2.7、上传文件@RequestPart
2.8、获取Cookie/Session/header
3、返回数据
3.1、返回静态页面
3.2、返回text/html
3.3、返回JSON对象
3.4、请求转发或者请求重定向
SpringMVC
1、构建在Servlet(API)之上的;
2、是一个Web框架(具备http);
3、来自于Spring webMVC模块
1、MVC定义
MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器,使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。
M即model模型是指模型表示业务规则。在MVC的三个部件中,模型拥有最多的处理任务。被模型返回的数据是中立的,模型与数据格式无关,这样一个模型能为多个视图提供数据,由于应用于模型的代码只需写一次就可以被多个视图重用,所以减少了代码的重复性。
V即View视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,它只是作为一种输出数据并允许用户操作的方式。
C即controller控制器是指控制器接受用户的输入并调用模型和视图去完成用户的需求,控制器本身不输出任何东西和做任何处理。它只是接收请求并决定调用哪个模型构件去处理请求,然后再确定用哪个视图来显示返回的数据。
2、MVC和SpringMVC之间的关系
springmvc提供了 前端控制器 DispatcherServlet,仅针对对客户端的请求和响应进行统一 处理(就是说封装了servlet),是个框架 。是针对三层架构的表述层(或表示层) 开发提供的框架 ,而mvc是一种思想。对于原先的mvc思想来说,springmvc只是包含了mvc思想的一部分 Controller进行实现。
当用户在浏览器中输入url之后,SpringMVC项目就可以感知用户的请求
学SpringMVC
1、构建在servlet(API)之上;
2、是一个Web框架(HTTP);
3、来自于Spring webMVC模块
1、Spring MVC的创建和连接
@RequestMapping("/test") //路由注册
//@Controller //程序返回的是数据而非页面
//@ResponseBody //只有加载的类,别人才能访问
@RestController
public class TestConstroller {@RequestMapping("/hi")public String sayHi(){return "hi,spring mvc";}
}
@RequestMapping既可以修饰类,也可以修饰方法。当修饰类和方法时,访问的地址是类+方法
方法地址:localhost:8080/test/hi
浏览器获取前端接口和后端程序连接功能实现
1.1、@RequestMapping(" /xxx' )既能修饰类又能修饰方法
特性:既支持GET方式的请求又支持POST方式的请求...
1.2、@RequestMapping设置只支持GET/POST请求
@RequestMapping("/test") //路由注册
//@Controller //程序返回的是数据而非页面
//@ResponseBody //只有加载的类,别人才能访问
@RestController
public class TestConstroller {//@RequestMapping("/hi")@RequestMapping(value = "/hi",method = RequestMethod.POST)public String sayHi(){return "hi,spring mvc";}
}
1.3、@PostMapping
@RequestMapping("/test") //路由注册
//@Controller //程序返回的是数据而非页面
//@ResponseBody //只有加载的类,别人才能访问
@RestController
public class TestConstroller {//@RequestMapping("/hi")@RequestMapping(value = "/hi",method = RequestMethod.POST)@PostMapping("/hi")public String sayHi(){return "hi,spring mvc";}
}
1.4、@GetMapping
@RequestMapping("/test") //路由注册
//@Controller //程序返回的是数据而非页面
//@ResponseBody //只有加载的类,别人才能访问
@RestController
public class TestConstroller {//@RequestMapping("/hi")@RequestMapping(value = "/hi",method = RequestMethod.POST)@GetMapping("/hi")public String sayHi(){return "hi,spring mvc";}
}
2、获取参数
2.1、传递单个参数/多个参数
@RequestMapping("/test") //路由注册
//@Controller //程序返回的是数据而非页面
//@ResponseBody //只有加载的类,别人才能访问
@RestController
public class TestConstroller {@GetMapping("/hi")public String sayHi(String name){return "hi"+name;}
}
传参注意事项:在Spring Boot(Spring MVC)中传参一定要传包装类型,而不是基础类型
原因:当需要一个基础类型,但又忘记传递时,使用基础类型会报错(500),而包装类型不会错,只是值为null
@GetMapping("/num")public String getnum(Integer num){return "num="+num;}
@GetMapping("/hi")public String sayHi(String name,Integer age){return "hi"+name+" age:"+age;}
2.2、传递对象
后端实现
@Data
public class User {private int id;private String name;private int age;
}
@GetMapping("/showuser")public String showu(User user){return user.toString();}
前端实现
2.3、传递表单参数
当参数较少时,可以使用传递多个参数的方法;
当参数较多时,可以使用传递对象的方法
2.4、后端参数重命名
后端实现
@GetMapping("/showtime")public String shoeTime(@RequestParam("t") String startTime,@RequestParam("t2") String endTime){return "开始时间:" +startTime+ " 结束时间:" +endTime;}
前端实现
如果t值不是必须要传
@GetMapping("/showtime")public String shoeTime(@RequestParam(value = "t",required = false) String startTime,@RequestParam("t2") String endTime){return "开始时间:" +startTime+ " 结束时间:" +endTime;}
2.5、@RequestBody接收JSON对象
后端实现
//@RequestBody接收JSON对象@PostMapping("/show-json-user")public String showJSONuser(@RequestBody User user){return user.toString();}
前端实现
2.6、获取URL中的参数@PathVariable
后端实现
@RequestMapping("/login/{username}/{password}")public String login(@PathVariable("username")String username,@PathVariable("password")String password){return username + ":" + password;}
前端实现
2.7、上传文件@RequestPart
后端实现
@RequestMapping("/upfile")public String uofile(@RequestPart("myfile")MultipartFile file) throws IOException {String path="D:\\baekhyun\\bobo.jpg";file.transferTo(new File(path));return path;}
前端实现
最终上传文件后端实现
@RequestMapping("/finalfile")public String finalupfile(@RequestPart("myfile")MultipartFile file) throws IOException {//根目录String path="D:\\baekhyun\\";//根目录+【唯一的文件名】path+= UUID.randomUUID().toString();//根目录+唯一的文件名+文件的后缀path+=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));file.transferTo(new File(path));return path;}
前端实现
2.8、获取Cookie/Session/header
1、获取Cookie
//获取全部Cookie@RequestMapping("/getck")public String getCookie(HttpServletRequest request){Cookie[] cookies=request.getCookies();for (Cookie item:cookies){log.error(item.getName()+":"+item.getValue());}return "get cookie";}
2、获取单个Cookie @CookieValue
//获取单个Cookie@RequestMapping("/getck2")public String getCookie2(@CookieValue("do") String val){return "cookie value"+val;}
3、获取Header @RequestHeader
后端实现
//获取header@RequestMapping("/getheader")public String getheader(@RequestHeader("User-Agent") String userAgent){return userAgent;}
前端实现
4、存Session
后端实现
//存Session@RequestMapping("/setsession")public String setSession(HttpServletRequest request){HttpSession session=request.getSession();session.setAttribute("userinfo","userinfo");return "set Session success";}
前端实现
5、获取Session
后端实现
//读Session@RequestMapping("getsession")public String getSession(HttpServletRequest request){HttpSession session=request.getSession(false);if (session!=null && session.getAttribute("userinfo")!=null){return (String) session.getAttribute("userinfo");}else {return "暂无session信息";}}
前端实现
@RequestMapping("/getsession2")public String getSession2(@SessionAttribute(value = "userinfo",required = false)String userinfo){return userinfo;}
3、返回数据
3.1、返回静态页面
后端实现
@RequestMapping("/resp")
@Controller
public class RespController {@RequestMapping("/hi")public String sayHi(){return "/hello.html";}
}
前端实现
3.2、返回text/html
案例:计算器的实现
@ResponseBody
@Controller
public class CalcController {@RequestMapping("/calc")public String calc(Integer num1,Integer num2){if (num1==null || num2==null) return "参数错误";return "结果为=" +(num1+num2);}
}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><form action="/calc"><div style="margin-top: 100px;text-align: center;"><h1>计算器</h1>数字1:<input name="num1"><br>数字2:<input name="num2"><br><input value="提交" type="submit"></div></form></body>
</html>
3.3、返回JSON对象
后端实现
@RequestMapping("/respjson")public HashMap<String,String> respJson(){HashMap<String,String> map=new HashMap<>();map.put("baekhyun","baekhyun.value");map.put("do","do.value");map.put("sehun","sehun.value");return map;}
前端实现
3.4、请求转发或者请求重定向
forward和redirect
forward和redirect具体区别如下:
1.请求重定向(redirect) 将请求重新定位到资源;请求转发(forward) 服务器端转发。
2.请求重定向地址发生变化,请求转发地址不发生变化。
3.请求重定向与直接访问新地址效果一致, 不存在原来的外部资源不能访问;请求转发服务器端转发有可能造成原外部资源不能访问。