比如我们在一个jsp页面中操作一个用户,我们操作的用户的id传到后台后,我们查询出该用户的信息,紧接着要更新该用户,也就是说,需要在后台再转发一次,在springmvc中怎么实现呢?
前台页面我们就固定死,传入一个固定的id:
edit.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
pageContext.setAttribute("basePath", basePath);
%>
<body>
1 哈哈 7000
<a href="${basePath}emp/find.action?id=1" style="text-decoration:none">编辑</a>
</body>
</html>
web.xml只需要配置servet和一个编码过滤器即可。
spring.xml只需要配置一个需要扫描的包就可以。
看一下重点控制类:
@Controller
@RequestMapping(value="/emp")
public class EmpAction {
@RequestMapping(value="/find")
public String findEmpById(int id,Model model) throws Exception{
System.out.println("查询"+id+"号员工信息");
//转发到EmpAction的另一个方法中去,即再次发送请求
// return "forward:/emp/update.action";
//重定向到EmpAction的另一个方法中去,即再次发送请求
return "redirect:/emp/update.action?id=" + id;
}
@RequestMapping(value="/update")
public String updateEmpById(int id,Model model) throws Exception{
System.out.println("更新" + id +"号员工信息");
model.addAttribute("message","更新员工信息成功");
return "/jsp/ok.jsp";
}
}
@Controller和@RequestMapping(value=”“)这两个注解想必都已经知道含义。
当前台页面访问/emp/find时候接收到前台的id属性,如果想通过转发的形式再次转发到另一个action。我们可以用传统的request和response的转发和重定向,但是这样需要在我们的业务方法中添加两个参数,耦合性太高,所以我们可以用springmvc提供的方法来实现:
转发:可以在业务方法中 return “forward:/emp/update.action”;
重定向:可以在业务方法中:return “redirect:/emp/update.action?id=” + id;
这样就可以访问到另一个action,执行另一个action中的业务方法。