spingmvc學習總結——6——在後臺轉發(重定向多次)
阿新 • • 發佈:2019-02-19
比如我們在一個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中的業務方法。