package cn.edu.imau.test;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = "/getParam")
public class LearnGetParam {
/** * 如下,获取方式: 在@RequestMapping中定义了/index1/{a},那么获取到的a就是index1/后的数据。 * 例如我的url是/getParam/index1/123,那么a=123。 * * @param a * @param model * @return */
@RequestMapping(value = "/index1/{a}")
public String index1(@PathVariable(value = "a") String a, Model model) {
model.addAttribute("result", "index1" + a);
return "result";
}
/** * 通过@RequestParam注解获取url传递的参数。 例如:/getParam/index2?a=234,结果a=234。 * * @param a * @param model * @return */
@RequestMapping(value = "/index2")
public String index2(@RequestParam(value = "a") String a, Model model) {
model.addAttribute("result", "index2" + a);
return "result";
}
/** * 使用HttpServletRequest获取参数 request.getParameter等同于@RequestParam * * @param request * @param model * @return */
@RequestMapping(value = "/index3")
public String index3(HttpServletRequest request, Model model) {
model.addAttribute("result", "index3" + request.getParameter("a"));
return "result";
}
/** * @ModelAttribute用法有两种: * 运用在参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用; * 运用在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值加入到ModelMap中 * * @param demo * 用来存储传递的参数,对象中必须有对应的set函数 * @return */
@RequestMapping(value = "/index4")
public String index4(@ModelAttribute("tempUser") Demo demo, Model model) {
model.addAttribute("result", "index4" + demo.getA());
return "result";
}
}
class Demo {
private String a;
public void setA(String a) {
this.a = a;
}
public String getA() {
return a;
}
}