SpringMVC笔记

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"); //将name传递给Model
return modelAndView;
//返回后会经过视图解析器进行处理
}

@RequestMapping(value = "/index")
public String index(Model model){ //这里不仅仅可以是Model,还可以是Map、ModelMap
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的作用域:

  1. Singleton
  2. Prototype
  3. Request HTTP请求产生新实例,结束后Bean消失
  4. Session 每一个会话
  5. 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配置Multipart相关配置,必须配置临时上传路径,建议选择方便打开的
// 同样可以设置其他属性:maxFileSize, maxRequestSize, fileSizeThreshold
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>