实例模拟struts核心流程
Struts,经典框架之一,每个java web 开发人员都应该晓得它的大名。这里,我就用一个简单实例来模拟一下struts的核心流程。具体实例如下:
主界面:
点击提交后,程序根据具体的action,跳转到不同的页面。下面看一下具体的实现代码。
文件树:
ActionConfig.xml 代码:
<?xml version="1.0" encoding="UTF-8"?>
<action-config>
<action path = "/addUser.action" type = "com.tigaoban.manager.AddUserAction">
<forward name = "success">/addSuccess.jsp</forward>
<forward name = "error">/addError.jsp</forward>
</action>
<action path = "/delUser.action" type = "com.tigaoban.manager.DelUserAction">
<forward name = "success">/delSuccess.jsp</forward>
<forward name = "error">/delError.jsp</forward>
</action>
<action path = "/modifyUser.action" type = "com.tigaoban.manager.ModifyUserAction">
<forward name = "success">/modifySuccess.jsp</forward>
<forward name = "error">/modifyError.jsp</forward>
</action>
<action path = "/queryUser.action" type = "com.tigaoban.manager.QueryUserAction">
<forward name = "success">/querySuccess.jsp</forward>
<forward name = "error">/queryError.jsp</forward>
</action>
</action-config>
ActionMapping 代码:
package com.tigaoban.domain;
import java.util.Map;
public class ActionMapping {
private String path;
private String type;
private Map<String, String> forwardMap;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, String> getForwardMap() {
return forwardMap;
}
public void setForwardMap(Map<String, String> forwardMap) {
this.forwardMap = forwardMap;
}
}
XmlConfigReader 代码:
package com.tigaoban.util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.tigaoban.domain.ActionMapping;
/**
* 采用单例模式解析ActionConfig.xml文件
* @author Haitao
*
*/
public class XmlConfigReader {
//懒汉式
private static XmlConfigReader instance = null;//XmlConfigReader 实例
//key=名称,value = 具体的动作实体类
private Map<String, ActionMapping> actionMap = new HashMap<String, ActionMapping>();
/**
* 构造方法
*/
private XmlConfigReader(){
SAXReader reader = new SAXReader();
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("ActionConfig.xml");
try {
Document doc = reader.read(in);
//取得Action相关的配置信息,并存入ActionMapping实体中
List<Element> actionList = doc.selectNodes("//action");
for (Iterator<Element> iter = actionList.iterator(); iter.hasNext();){
Element element = iter.next();
String path = element.attributeValue("path");
String type = element.attributeValue("type");
//System.out.println(path);
List<Element> forwardList = element.elements("forward");
//存放forward中信息的map
Map<String,String> forwardMap = new HashMap<String, String>();
for (Iterator<Element> iterator = forwardList.iterator();iterator.hasNext();){
Element forward = iterator.next();
String name = forward.attributeValue("name");
String value = (String)forward.getData();
forwardMap.put(name, value);
}
//新建ActionMapping实体
ActionMapping actionMapping = new ActionMapping();
actionMapping.setPath(path);
actionMapping.setType(type);
actionMapping.setForwardMap(forwardMap);
//将actionMapping放入map中
actionMap.put(path, actionMapping);
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static synchronized XmlConfigReader getInstance() {
if(instance == null){
instance = new XmlConfigReader();
}
return instance;
}
/**
* 取得action相关配置
* @return
*/
public Map<String, ActionMapping> getMap() {
return actionMap;
}
}
UserManager代码:
package com.tigaoban.manager;
import java.util.ArrayList;
import java.util.List;
public class UserManager {
public void addUser(String username){
System.out.println("添加成功" + username);
}
public void delUser(String username){
System.out.println("删除成功" + username);
}
public void modifyUser(String username){
System.out.println("修改成功" + username);
}
public List<String> queryUser(String username){
System.out.println("查询成功" + username);
List<String> userList = new ArrayList<String>();
userList.add("a");
userList.add("b");
userList.add("c");
return userList;
}
}
Action代码:
package com.tigaoban.manager;
import javax.servlet.http.*;
public interface Action {
public String execute(HttpServletRequest request,HttpServletResponse response)
throws Exception;
}
AddUserAction代码
package com.tigaoban.manager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddUserAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
UserManager userManager = new UserManager();
userManager.addUser(userName);
return "/addSuccess.jsp";
}
}
DelUserAction代码:
package com.tigaoban.manager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DelUserAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
UserManager userManager = new UserManager();
userManager.delUser(userName);
return "/delSuccess.jsp";
}
}
ModifyUserAction代码:
package com.tigaoban.manager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ModifyUserAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
UserManager userManager = new UserManager();
userManager.modifyUser(userName);
return "/modifySuccess.jsp";
}
}
QueryUserAction代码:
package com.tigaoban.manager;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryUserAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
UserManager userManager = new UserManager();
List<String> userList = userManager.queryUser(userName);
for (Iterator<String> itor = userList.iterator();itor.hasNext();){
String user = itor.next();
System.out.println(user);
}
return "/querySuccess.jsp";
}
}
TestServlet代码
package com.tigaoban.servlet;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tigaoban.domain.ActionMapping;
import com.tigaoban.manager.Action;
import com.tigaoban.util.XmlConfigReader;
@SuppressWarnings("serial")
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestUrl = request.getServletPath();
String path = requestUrl.substring(requestUrl.indexOf("/",1),requestUrl.length());
//System.out.println(path);
String forward = "";
Action action = null;
//取得actionMap
Map<String,ActionMapping> actionMap = XmlConfigReader.getInstance().getMap();
//根据path取得对应的ActionMapping
ActionMapping actionMapping = (ActionMapping)actionMap.get(path);
//取得本请求对应的Action类的完整路径
String type = actionMapping.getType();
try {
//使用反射动态实例化Action
action = (Action)Class.forName(type).newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
forward = action.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + forward);
}
}
一下是几个很简单的jsp页面:
user.jsp页面:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
<form action="servlet/addUser.action" method="post">
姓名:<input type ="text" name = "userName" /><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
addSuccess.jsp、modifySuccess.jsp、delSuccess.jsp、querySuccess.jsp页面:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
添加/修改/删除/查询成功!
</body>
</html>
以上就是struts的核心流程,明白了这个例子,相信对你理解struts有很大帮助。