struts2工作原理圖:
執行步驟:
Action.java(Action接口)
package cn.itcast.action;
public interface Action {
public String execute();
}
Struts2Filter.java(filter過濾器,實現Filter接口):相當於strtus.xml的配置功能(這裏演示struts2的工作原理)
package cn.itcast.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Struts2Filter implements Filter {
Map<String, String> map = new HashMap<String, String>();
public void init(FilterConfig config) throws ServletException {
map.put("/primer/userAction.action", "cn.itcast.action.UserAction");
map.put("/helloWorld/helloWorldAction.action", "cn.itcast.action.HelloWorldAction");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//強轉
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String path = req.getServletPath();
System.out.println("path = "+path);
if(path.equals("/test.jsp")){
chain.doFilter(req, res);
}else{
try {
Action action;
//利用反射,通過newInstance()得到實例化
action = (Action)Class.forName(map.get(path)).newInstance();
action.execute();
req.getRequestDispatcher("/success.jsp").forward(req, res);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void destroy() {
// TODO Auto-generated method stub
}
}
UserAction,java(實現Action接口)
package cn.itcast.action;
public class UserAction implements Action {
public String execute() {
System.out.println("UserAction ********** execute()");
return "success";
}
}
HelloWorldAction(實現Action接口)
public class HelloWorldAction implements Action {
public String execute() {
System.out.println("HelloWorldAction ********** execute()");
return "success";
}
}
實現Action接口示例圖:
test.jsp
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
入門的路徑:<br>
<!--${pageContext.request.contextPath}絕對路徑表示:網站根路徑 -->
<!-- action: 命名空間/action名.action -->
<a href="${pageContext.request.contextPath}/primer/userAction.action">userWorld</a><br>
<br>
<a href="${pageContext.request.contextPath}/helloWorld/helloWorldAction.action">helloWorld</a><br>
</body>
</html>
success.jsp
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
Welcome!
</body>
</html>