1、定义Action接口
public interface Action {
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
2、实现自定义Action接口
public class LoginAction implements Action {
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String name = request.getParameter("uid");
String password = request.getParameter("pwd");
// 业务处理
CustomerBiz ub = new CustomerBizImpl();
Customer user = ub.login(name, password);
// 判断登录是否成功
if (user == null) {
request.setAttribute("message", "用户名或密码错误");
return "login.jsp";
} else {
request.getSession().setAttribute("login", user);
return "index.jsp";
}
}
}
3、实现Controller类ActionServlet
1)获取自定义Action
public Action getAction(HttpServletRequest request){
//获取请求的uri
String uri = request.getRequestURI();
//获取上下文路径
String contextPath = request.getContextPath();
//截取上下文路径以后的部分
String actionPath = uri.substring(contextPath.length());
//获取Action 名称
String actionName =
actionPath.substring(1,actionPath.lastIndexOf('.')).trim();
Action action = null;
//添加新功能时在这里添加
if("login".equals(actionName)){
action = new LoginAction();
}
return action;
}
2)调用execute方法
public void doGet(HttpServletRequestrequest,
HttpServletResponse response) throws Exception {
//获得Action
Action action = this.getAction(request);
//调用Action execute 方法
String resultView = action.execute(request, response);
//actionMapping
request.getRequestDispatcher(resultView).forward(
request, response);
}
4、配置ActionServlet
1)修改web.xml文件,配置ActionServlet
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>*.*.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
5、上面只能接受一个action处理,如果有多个action,如何接收呢?
2)Controller的完善ActionServlet,增加架构配置文件mystruts.xml
3)保存Action信息,修改Action,ActionMapping,保存配置的Result 属性信息Map<String,String>
4)读取Action信息,修改ActionServlet的init方法
5)使用反射生成Action,ActionManager的createAction方法用来获取Action实例
6)loadClass方法动态加载类ActionManager,loadClass方法动态加载类
7)修改ActionServlet配置信息
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>com.birlt.dangdang.servlet.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>mystruts.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
6、完善视图
1)保存视图Result类
2)修改ActionMapping,保存配置的Result 属性信息Map<String,Result>
3)增加ActionMappingManager类
4)修改ActionServlet,需要修改init方法,并将getAction改为getActionMapping,并将修改获取mapping内容
7、注册完成功能
转载请注明出处。