携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第19天,点击查看活动详情
哈喽,大家好!我是Why,一名在读学生,目前刚刚开始进入自己的编程学习生涯。虽然学习起步较晚,但我坚信做了才有0或1的可能。学了一段时间以后也是选择在掘金上分享自己的日常笔记,也希望能够在众多道友的大家庭中打成一片。 本文主要讲解处理器方法的参数,如果大家读后觉得有用的话,还请大家多多支持博主:欢迎 ❤️点赞👍、收藏⭐、留言💬 ✨✨✨个人主页:JinHuan
处理器方法的参数
处理器方法可以包括以下四类参数,这些参数会在系统调用时由系统自动赋值,所以我们可以在方法内直接使用。以下是这四类参数
HttpSerletRequest HttpServletResponse HttpSession 请求中所携带的请求参数
栗子
创建控制器ParamController.java和前端界面hello.jsp页面,以及页面跳转后的成功页面ok.jsp
@Controller
@RequestMapping("param")
public class ParamController {
@RequestMapping("hello")
public ModelAndView hello(){
return new ModelAndView("hello");
}
}
<html>
<head>
<title>Ok</title>
</head>
<body>
<h1>ok----------</h1>
</body>
</html>
1、直接使用方法的参数逐个接收
<h3>1、直接使用方法接收参数</h3>
<form action="/param/test01" method="post">
球队id:<input type="text" name="teamId"><br/>
球队name:<input type="text" name="teamName"><br/>
球队location:<input type="text" name="teamLocation"><br/>
<button type="submit">提交</button>
</form>
/**
* @param teamId:
* @param teamName:
* @param teamLocation:
* @return org.springframework.web.servlet.ModelAndView
* decription: 直接使用方法的参数逐个接收:方法的参数名必须和用户请求中携带的参数保持一致,否则获取不到数据
*/
@RequestMapping("test01")
public ModelAndView test01(Integer teamId,String teamName, String teamLocation){
System.out.println("test01");
System.out.println(teamId);
System.out.println(teamName);
System.out.println(teamLocation);
return new ModelAndView("ok");
}
2、使用对象接收发多个参数
<%--注意,此处的name必须和实体类对象属性名一致--%>
<h3>2、使用对象一次性接收多个参数</h3>
<form action="/param/test02" method="post">
球队id:<input type="text" name="teamId"><br/>
球队name:<input type="text" name="teamName"><br/>
球队location:<input type="text" name="teamLocation"><br/>
<button type="submit">提交</button>
</form>
/**
* @param team:
* @return org.springframework.web.servlet.ModelAndView
* decription: 使用对象接收多个参数:要求用户请求中携带的参数必须和实体类中属性保持一致,否则获取失败
*/
@RequestMapping("test02")
public ModelAndView test02(Team team){
System.out.println("test02");
System.out.println(team);
return new ModelAndView("ok");
}
3、方法名称参数与请求参数名称不一致
<%--请求参数和方法参数不一致怎么做?--%>
<h3>3、方法名称参数与请求参数名称不一致</h3>
<form action="/param/test03" method="post">
球队id:<input type="text" name="teamId"><br/>
球队name:<input type="text" name="teamName"><br/>
球队location:<input type="text" name="teamLocation"><br/>
<button type="submit">提交</button>
</form>
/**
* @param id:
* @param name:
* @param location:
* @return org.springframework.web.servlet.ModelAndView
* decription: 方法名称参数与请求参数名称不一致---->手动校正法
* 使用该注解进行校正@RequestParam(value = "表示参数名称",
* required = 表示参数是否是必须的
* true:表示必须赋值,否则出现400错误[默认值]
* fasle:表示不强制必须赋值,当不存在时,该值默认为 null)
*/
@RequestMapping("test03")
public ModelAndView test03(@RequestParam(value = "teamId",required = false) Integer id,
@RequestParam("teamName")String name,
@RequestParam("teamLocation")String location){
System.out.println("test03");
System.out.println(id);
System.out.println(name);
System.out.println(location);
return new ModelAndView("ok");
}