现在的位置: 首页 > 综合 > 正文

奥斯科技-开发类似于struts1.2的简…

2019年03月08日 ⁄ 综合 ⁄ 共 2314字 ⁄ 字号 评论关闭
奥斯科技-开发类似于struts1.2的简单框架奥斯科技-开发类似于struts1.2的简单框架
1.一个Servlet入口处理所有请求,并根据不同的请求来反射不同的实现类,最好是写个xml配置文件,按照不容的实现类来控制对象的实现!!
例如:
<?xml version="1.0"
encoding="UTF-8"?>
<actions>
<action type="login"
class="cn.ouyang.oa.web.action.LoginAction" topath="result.jsp"
isforward="false"></action>
<action type="show"
class="cn.ouyang.oa.web.action.ShowAction" topath="index.jsp"
isforward="true"></action>
</actions>
先来看下我项目的结构吧.
奥斯科技-开发类似于struts1.2的简单框架

2.在:Contrller.java这个Servlet中代码如下:
package cn.ouyang.framework;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Contrller extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public Action getActionByPath(HttpServletRequest request,
HttpServletResponse response) {
Action action = null;
String path = request.getServletPath();
String actionstr = path.substring(path.lastIndexOf("/") +
1, path
.length() - 3);
try {
DocumentBuilder domBuilder =
DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
//在Web项目中使用
InputStream input =
getServletContext().getResourceAsStream(
"config\\mystruct.xml");
Document doc = domBuilder.parse(input);
NodeList actionNode =
doc.getElementsByTagName_r("action");
if (actionNode != null) {
for (int i = 0, size = actionNode.getLength(); i
< size; i++) {
Element  student =
(Element)actionNode.item(i);
String type = student.getAttribute("type");
//获取该节点的各种属性
if(type.equals(actionstr)){
//得到各属性的值
boolean isforward
=Boolean.valueOf(student.getAttribute("isforward"));
String clazz = student.getAttribute("class");
String topath = student.getAttribute("topath");
System.out.println(clazz);
action =
(Action)Class.forName(clazz).newInstance();
action.Excute(request, response);//执行
//判断是否转发
if(isforward){
request.getRequestDispatcher(topath).forward(request,
response);
}else{
response.sendRedirect(topath);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return action;
}

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
getActionByPath(request,response);

}

}

抱歉!评论已关闭.