MVC
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.10</version> </dependency>
|
Controller
页面
@Controller public class HelloController {
@RequestMapping("/index") public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView("index"); modelAndView.getModel().put("arg", "value"); return modelAndView; }
@RequestMapping(value = "/index") public String index(Model model){ model.addAttribute("arg", "value"); return "index"; } }
|
重定向
@RequestMapping("/index") public String index(){ return "redirect:page"; }
|
请求转发
@RequestMapping("/index") public String index(){ return "forward:home"; }
|
Bean的Web作用域
Bean的作用域:
- Singleton
- Prototype
- Request HTTP请求产生新实例,结束后Bean消失
- Session 每一个会话
- Global Session
RESTFul
一种设计风格。RESTful风格的设计允许将参数通过URL拼接传到服务端。
http://localhost:8080/mvc/index/13579
|
@RequestMapping("/index/{str}") public String index(@PathVariable String str) { System.out.println(str); return "index"; }
|
文件上传
public class MainInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
...
@Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setMultipartConfig(new MultipartConfigElement("/path/to/save")); } }
|
Controller模板
@RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam MultipartFile file) throws IOException { File fileObj = new File("filename.png"); file.transferTo(fileObj); System.out.println("用户上传的文件已保存到:"+fileObj.getAbsolutePath()); return "文件上传成功!"; }
|
前端模板
<div> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form> </div>
|