1. 程式人生 > >SpringMVC學習(二)

SpringMVC學習(二)

接受請求的方式:

1.直接將請求的引數作為控制器的方法入參,要求控制器的方法入參必須和請求引數的key一致。

@RequestMapping("/test1")
    public String test1(String username,String userpwd) {
        System.out.println(username + " " + userpwd);
        return "welcome";
    }

2.使用ServletAPI作為控制器方法的入參,常見的ServletAPI有HttpServletRequest,HttpServletResponse,HttpSession等 3.當請求的引數較多時,建議將其封裝在一個pojo中,再用該pojo作為控制器的方法入參。要求pojo中的屬性的名稱,必須和請求引數的key保持一致。

 @RequestMapping("/test2")
    public String test2(UserPojo po) {
        System.out.print(po.getUsername() + "  " + po.getUserpwd());
        return "welcome";
    }

將引數返回到view中

1.採用servlet API方式 2.採用model方式,將要傳遞引數放入請求域中

@RequestMapping("test4")
    public String test4(Model model) {
        String name = "aaa"
; model.addAttribute("name",name); return "welcome"; }

3.採用Map方式,將要傳遞的引數放入請求域中

 @RequestMapping("test5")
    public String test5(Map map) {
        String name = "qjy";
        String pwd = "123";
        map.put("name",name);
        map.put("pwd",pwd);
        return "welcome"
; }

4.採用ModelAndView方式,將要傳遞的引數和跳轉的檢視,放入到ModelAndView物件,再返回給前端控制器解析。

 @RequestMapping("test6")
    public ModelAndView test6() {
        String name = "aaa";
        int id = 12;
        ModelAndView mav = new ModelAndView();
        mav.addObject("name",name);
        mav.addObject("id",id);
        mav.setViewName("welcome");
        return mav;
    }

5.通過@sessionAttribute或者@ModelAttribute直接將制定的引數放入對應的域中 在類名上面註解@sessionAttribute,如果在會話中找不到對應的屬性,則丟擲 HttpSessionRequiredException 異常,@ModelAttribute 被該名稱註釋的方法,會在控制器方法執行之前先呼叫


@SessionAttributes("user")
@Controller
public class UserController {
    private User user=new User();

    @ModelAttribute("user")
    public User getUser() {
        user.setUsername("張三");
        user.setUserpwd("111");
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
  @RequestMapping("test7")
    public String test7(Map map) {
        map.put("user",user);
        return "welcome";
    }

SpringMVC Restful 風格程式設計

HTTP 協議裡面,四個表示操作方式的動 詞:GET、POST、PUT、DELETE。它們分別對應四種基本操作:GET 用來獲 取資源,POST 用來新建資源,PUT 用來更新資源,DELETE 用來刪除資源。

<!--  restful風格,如果想要實現將post提交改成put或者delete的方式,那麼就必須新增隱藏支援 -->

  <filter>
  <filter-name>HiddenHttpMethodFilter</filter-name>
  <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>HiddenHttpMethodFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

GET 獲取資源 基本上所有的請求,預設都是get方式,get方式不需要偽裝。

Post 新增資源 Post方式需要顯式指明提交方式是post(只能在表單的action中的method來指明)

Delete 刪除資源 必須藉助於post提交方式來偽裝成delete方式,而且只能是表單的提交

Put 修改資源 必須藉助於post提交方式來偽裝成put方式,而且只能是表單的提交

需要注意的是: Get方式傳遞多個引數用來查詢時,如果是非動態引數(也就是這些引數必須要有值),那麼建議還是繼續採用restful風格來設計,如果是動態引數,建議使用非restful風格來設計。

@RequestParam 和 @PathVariable的區別 @RequstParam 將位址列或者表單請求的值設定到控制器方法的入參中 @PathVariable 將restful風格的地址對應位置的值,注入到控制器的方法入參中

SpringMVC表單標籤

1.匯入相應標籤庫

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

2.常用的標籤元素

<form:form action="" method="" modelAttribute=""></form:form>

表示表單標籤,modelAttribute表示將表單內所有要提交的value都存入到該屬性,後臺直接通過該屬性就能獲取所有提交的value。

form:input、form:password、form:hidden、form:textarea :對應 HTML 表單的 text、password、hidden、textarea 標籤

form:radiobutton:單選框元件標籤 form:checkbox:複選框元件。用於構造單個複選框 form:checkboxs:用於構造多個複選框。使用方式同 form:radiobuttons 標籤 form:select:用於構造下拉框元件。使用方式同 form:radiobuttons 標籤 form:option:下拉框選項元件標籤。使用方式同 form:radiobuttons 標籤 form:errors:顯示錶單元件或資料校驗所對應的錯誤

<form:errors path= “ *” /> :顯示錶單所有的錯誤
<form:errors path= “ user*” /> :顯示所有以 user 為字首的屬性對應
的錯誤
<form:errors path= “ username” /> :顯示特定表單物件屬性的錯誤

SpringMVC檔案上傳

1.匯入jar包 2.在SpringMVC配置檔案加入bean節點

<!-- 配置檔案上傳的節點 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定檔案最大上傳大小-->
        <property name="maxUploadSize" value="102400000"></property>
    </bean>

3.在需要上傳的表單中,設定表單提交method 是post, encotype是二進位制檔案流

4.在springMVC控制器方法中編寫上傳的程式碼

//獲取當前專案所在的部署伺服器的本地地址的路徑+/upload
        String path=session.getServletContext().getRealPath("/upload");

        File file2=new File(path);
        //判斷該資料夾是否存在,如果不存在則建立該資料夾
        if(!file2.exists()){
            file2.mkdirs();
        }

        boolean b=true;
         //遍歷二進位制檔案陣列
        for (MultipartFile multipartFile : myfile) {
            //設定要儲存的檔案地址(要儲存的檔案路徑+原始檔的名稱)
            File file =new File(path+"/"+multipartFile.getOriginalFilename());

            //將上傳的檔案以流的形式寫入到指定的位置
            try {
                FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
            } catch (IOException e) {
                b=false;
                System.out.println("檔案上傳異常"+e.getMessage());
            //  e.printStackTrace();
            }

        }