Spring入門學習手冊 6:Spring MVC基礎中的基礎

目錄java

完整代碼在這web

1、獲取請求參數

Spring獲取請求參數很是簡單,只要用到 @RequestParam 註解就能夠了spring

若是不指定請求method的話,不管是get仍是post參數均可以輕易獲取到app

代碼是下面這樣:post

package com.learn.springMVCDemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RequestController {

    @RequestMapping("requestDemo")
    public String doRequest(Model model, @RequestParam(name="info", defaultValue = "some information") String info) {
        model.addAttribute("info", info);
        return "hello";
    }
}
複製代碼

在這段代碼中 @RequestParam 註解的括號中 name表示參數名, defaultValue 指明默認的參數值。ui

GET方法請求這個頁面: 訪問地址 http://localhost:8080/LearnSpringMVCDemoFirst_war/requestDemo?info=helloWorldFromGETMethodspa

運行效果:3d

POST方法請求這個頁面:code

訪問地址 http://localhost:8080/LearnSpringMVCDemoFirst_war/orm

提交表單

運行結果

2、頁面重定向

重定向的時候只要在返回的時候加上 redirect 就能夠了:

package com.learn.springMVCDemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RedirectController {

    @RequestMapping("redirect")
    public String redirectDemo(Model model) {

        model.addAttribute("message", "redirectInfo");
        //重定向
        return "redirect:/demo";
    }

}
複製代碼

上面的代碼就是重定向到 /demo頁面了。

訪問地址: localhost:8080/LearnSpringMVCDemoFirst_war/redirect

3、獲取URI路徑(@PathVariable)

package com.learn.springMVCDemo;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class PathVariableController {

    @RequestMapping("path/{prefix}/{name}/{suffix}")
    public ModelAndView PathDemo(Model model, @PathVariable(value = "prefix") String prefix, @PathVariable(value = "name") String name, @PathVariable(value = "suffix") String suffix) {
        ModelAndView mv = new ModelAndView("hello");
        mv.addObject("message","website URI path");
        model.addAttribute("prefix", prefix);
        model.addAttribute("name", name);
        model.addAttribute("suffix", suffix);
        return mv;
    }


}
複製代碼

@RequestMapping的括號中固定一個以上的路徑名稱,而後給分固定的路徑名稱直接加上大括號,在請求映射的方法參數中加上 @PathVariable註解的參數中,按照前後順序一一對應就能夠獲取到路徑名稱。

運行結果:

4、不返回視圖直接返回字符串

@RequestMapping("ResponseBody")
@ResponseBody
public String RequestBody() {
    return "request body message!!!";
}
複製代碼

在請求映射方法前直接加上 @ResponseBody註解,那麼返回的就不是視圖,而直接是ResponseBody

運行結果:

相關文章
相關標籤/搜索