Struts入门,写一个通用的Servlet


web.xml的配置

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>com.test.framework.ActionServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>


写一个mystruts.xml,用来动态读取<action..>,以下就简单写一个登录的action

<?xml version="1.0" encoding="UTF-8"?>
<mystruts>
	<package>
		<action name="login" class="com.test.framework.action.LoginAction" method="login">
			<result name="loginSuccess" type="redirect">/index.jsp</result>
			<result name="loginFaild">/login.jsp</result>
		</action>
	</package>
</mystruts>


通用ActionServlet

package com.test.framework;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Element;

import com.test.framework.bean.ActionMapping;
import com.test.framework.bean.ActionMappingManager;
import com.test.framework.bean.Result;


/**
 * 核心控制器,此项目只有这一个serclet
 * 
 * 
 * @author csz
 *
 *总结:获取传过来的uri *.action *部分的内容然后在读取的xml文件中的action中的name属性,得到xml的name,class,method,
 *然后通过反射得到该类的一个实例调用method方法返回的标识,通过该标识和当前配置文件的result比较,看看跳转的页面是哪个
 *
 */
public class ActionServlet extends HttpServlet{
	
	private ActionMappingManager actionMappingManager;


	//启动时候执行执行一次
	@Override
	public void init() throws ServletException {
		actionMappingManager = new ActionMappingManager();
		
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			//1.获取请求的uri,得到请求路径名称
			String uri = request.getRequestURI();
			//得到login
			String actionName = uri.substring(uri.lastIndexOf("/")+1, uri.indexOf(".action"));
			
			//2.根据路径名称,读取配置文件,得到类的全名
			ActionMapping actionMapping = actionMappingManager.getActionMapping(actionName);
			String className = actionMapping.getClassName();
			//当前请求的处理方法
			String method = actionMapping.getMethod();
			
			//3.反射:创建对象,调用方法,获取方法返回的标记
			Class<?> clazz = Class.forName(className);
			Object object = clazz.newInstance();
			Method m = clazz.getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
			//调用方法的的标记
			String returnFlag = (String) m.invoke(object, request,response);
			
			//4.拿到标记,读取配置文件得到标记对应的页面,跳转类型
			Result result = actionMapping.getResult().get(returnFlag);
			//类型
			String type = result.getType();
			//页面
			String page = result.getPage();
			
			if ("redirect".equals(type)) {
				response.sendRedirect(request.getContextPath()+page);
				
			}else {
				request.getRequestDispatcher(page).forward(request, response);
			}
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	
}

ActionMappingManager类

package com.test.framework.bean;

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.Element;
import org.dom4j.io.SAXReader;


/**
 * 加载配置文件,封装都有的整个mystruts.xml
 * @author csz
 *
 */
public class ActionMappingManager {
	
	private Map<String,ActionMapping> allActions;

	public ActionMappingManager(){
		allActions = new HashMap<String, ActionMapping>();
		this.init();
		
	}
	
	public ActionMapping getActionMapping(String ActionName){
		if (ActionName==null) {
			throw new  RuntimeException("传入参数有误,请查看配置文件配置路径");
		}
		ActionMapping actionMapping = allActions.get(ActionName);
		if (actionMapping==null) {
			throw new  RuntimeException("在配置文件中找不到路径");
		}
		
		return actionMapping;
		
		
	}
	
	
	
	// 初始化allActions集合
	@SuppressWarnings("unchecked")
	private void init(){
	//读取配置文件
		try {
			//1.得到解析器
			SAXReader reader = new SAXReader();
			// 2. 加载文件
			InputStream inputStream = this.getClass().getResourceAsStream("/mystruts.xml");
			Document doc = reader.read(inputStream);
			
			//3.获取根
			Element root = doc.getRootElement();
			
			//4.得到package节点
			Element ele_package = root.element("package");
			
			//5.得到package节点下,所有的action子节点
			List<Element> listAction = ele_package.elements("action");
			
			//6.遍历,封装
			for (Element ele_action : listAction) {
				ActionMapping actionMapping = new ActionMapping();
				actionMapping.setName(ele_action.attributeValue("name"));
				actionMapping.setClassName(ele_action.attributeValue("class"));
				actionMapping.setMethod(ele_action.attributeValue("method"));
				
				//封装当前aciton节点下的results
				HashMap<String, Result> results = new HashMap<String, Result>();
				
				//得到当前action节点下所有的result子节点
				Iterator<Element> iterator = ele_action.elementIterator("result");
				
				while(iterator.hasNext()){
					 // 当前迭代的每一个元素都是 <result...>
					Element ele_result = iterator.next();
					Result res = new Result();
					res.setName(ele_result.attributeValue("name"));
					res.setType(ele_result.attributeValue("type"));
					res.setPage(ele_result.getTextTrim());
					results.put(res.getName(), res);
				}
				
				actionMapping.setResult(results);
				allActions.put(actionMapping.getName(), actionMapping);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	
}

ActionMapping类

package com.test.framework.bean;

import java.util.Map;

/**
 * 封装action节点 
 * 
 * @author csz
 * 
 */
public class ActionMapping {
	// 请求路径的名称
	private String name;

	// 处理action类的全名
	private String className;

	// 处理方法
	private String method;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public Map<String, Result> getResult() {
		return result;
	}

	public void setResult(Map<String, Result> result) {
		this.result = result;
	}

	private Map<String, Result> result;

}


result 类

/**
 * 封装result节点
 * 
 * 
 * @author csz
 */
public class Result {
	// 跳转的标记
	private String name;

	// 跳转类型
	private String type;

	// 跳转页面
	private String page;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}
}


jsp页面:

<form action="${pageContext.request.contextPath }/login.action" name="frmLogin"  method="post">
   	   用户名: <input type="text" name="name"> <br/>
   	 密码: <input type="text" name="pwd"> <br/>
   	   <input type="submit" value="登陆"> <br/>
   	</form>

简单些一个action

/**
 * 简单写一个action
 * 
 * @author csz
 * 
 */
public class LoginAction {
	
	public String login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String uri = null;
		if ("qqq".equals(name)&&"123".equals(pwd)) {
			uri = "loginSuccess";
		}else {
			uri = "loginFaild";
		}
		return uri;

	}
}



跳转到index就显示登录成功几个字。。。不贴代码了



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐