接收前端页面发送过的数据
(一) 使用原始的request接收数据
@Controller
public class UserController {
@RequestMapping("/findUserById")
public ModelAndView findUserById(HttpServletRequest request){
System.out.println(request.getParameter("id"));
ModelAndView mv = new ModelAndView("user");
mv.addObject("id",request.getParameter("id"));
return mv;
}
}
前端代码 user.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/11/8
Time: 10:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户页面</title>
</head>
<body>
${id}
${username}
${age}
${hr}
${user.id} ${user.username} ${user.age}
</body>
</html>
(二) 方法形参与前端参数同名,指定变量名和数据类型直接接收
@RequestMapping("/findUserBySearch")
public ModelAndView findUserBySearch(int id,String username, int age){
User user1 = new User(id,username,age);//通过有参构造将数据存入对象中
System.out.println(id +" "+username+" "+age);
ModelAndView mv = new ModelAndView("user");
mv.addObject("user",user1);
return mv;
}
1,当前端传递的参数名和方法形参名不一致时,通过@RequestParam指定转换关系
/*
* id1:前端传递的参数
* id : 服务端接收的参数
* (@RequestParam(“id1”)int id
* */
@RequestMapping("/findUserBySearch0")
public ModelAndView findUserBySearch0(@RequestParam("id1")int id, String username, int age){
User user = new User(id,username,age);
System.out.println(id +" "+username+" "+age);
ModelAndView mv = new ModelAndView("user");
mv.addObject("user",user);
return mv;
}
(三) 通过对象传递参数
@RequestMapping("/findUserBySearch1")
public ModelAndView findUserBySearch1(User user){
System.out.println(user.getId()+" "+user.getUsername()+" "+user.getAge());
ModelAndView mv = new ModelAndView("user");
return mv;
}
(四) 地址栏传参
@RequestMapping("/find/{id}")
public ModelAndView findUserBySearch(@PathVariable("user") int id){
System.out.println(id);
return null;
}
在地址栏输入 localhost:8080/find/3,控制台会输出3
向视图层(前端页面,或者其他controller)传递数据,String指返回的页面
(一) 通过request.setAttribute()
/*
*默认情况下走的是转发跳转到指定页面
* 转发:forward
* 重定向:redirect(request里面的东西丢了)
* */
@RequestMapping("/findUser1")
public String findUser1(HttpServletRequest request){
User u = new User(1111,"asfsa",33);
request.setAttribute("user",u);
return "user";//转发到页面
//return "forward:/user.jsp";//转发页面
//return "redirect:/user.jsp";//重定向到页面
//return "forward:/findUserById";//转发到其他controller
//return "redirect:/findUserById";//重定向到其他controller
}
(二) addObject()的方式
@RequestMapping("/findUserBySearch")
public ModelAndView findUserBySearch(int id,String username, int age){
User user1 = new User(id,username,age);
System.out.println(id +" "+username+" "+age);
ModelAndView mv = new ModelAndView("user");
mv.addObject("user",user1);
return mv;
}
(三) 通过Model方式返回对象
@RequestMapping("/findUser")
public String findUser(Model model){
User u = new User(1001,"lisi",20);
//指定返回的数据
model.addAttribute("user",u);
//指定返回的页面
return "user";
}