Spring MVC--RequestMapping

好久不见. 提交于 2019-12-04 13:26:11

1. 窄化请求

在类上用注解 @RequestMapping 相当于在加一层目录  访问时 : 项目名/user/.......

1 //窄化请求
2 @RequestMapping("user")
3 public class UserControoler {}

 

2. 参数绑定

1 @ResponseBody
2 @RequestMapping("/findById.action")   
3 public String findById(HttpServletRequest request,@RequestParam(name = "uid",required = true) Integer id){ // 必须要有参数uid
4   return "***";  
5 }

 

2.2 提交方式

1 @RequestMapping  (    path = "/queryAll.action",    method = {RequestMethod.POST,RequestMethod.GET},
2      params = {"uid=1"}
3   )

 

 

3. controller方法返回值 ModelandView (最常用)   String    void 

1  public ModelAndView test1(){ // 最常用,最方便
2      ModelAndView modelAndView = new ModelAndView();
3       modelAndView.addObject("msg","你好");
4       modelAndView.setViewName("../index.jsp");
5    
6       return modelAndView;
7 }
1   public String test2(Model model){ //model将数据保存到了request域中了,所以转发数据共享,重定向时,是两次请求,数据不共享
2       model.addAttribute("msg","你好");
3       return "forward:../index.jsp";
4       return "redirect:../index.jsp"
5  }  
1     public void test3(HttpServletRequest request, HttpServletResponse response){
2         request.setAttribute("msg","日月星辰");
3         request.getRequestDispatcher("../index.jsp").forward(request,response);
4     }

 

5. 文件上传

springmvc.xml -- 解析fileUpload组件 id 必须为:multipartResolver

  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

 

 

web.jsp

1     <form method="post" enctype="multipart/form-data" action="user/upload.action">
2         <input type="file" name="file">
3         <input type="submit" value="上传">
4     </form>

 

Controller Class @RequestMapping("user") // 窄化请求

 1     @RequestMapping("/upload.action")
 2     @ResponseBody
 3     public String upload(MultipartFile file) throws IOException {
 4         //文件名
 5         String originalFilename = file.getOriginalFilename();
 6         String uuid = UUID.randomUUID().toString().replace("-", ""); // 32位字符用不重复
 7         int i = originalFilename.lastIndexOf(".");
 8         String suffix = originalFilename.substring(i);
 9 
10         //页面的file的name属性值
11         String name = file.getName();
12         System.out.println(originalFilename);
13         System.out.println(name);
14         File file1 = new File("E:\\upload\\"+uuid+suffix);
15         file.transferTo(file1);
16         return "上传中";
17     }

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!