Implement a lightweight Struts2 with a servlet

Source: Internet
Author: User
Tags static class

Principle: Use a servlet as a general interceptor to intercept requests by URL Parttern, distribute requests to action by profile, and then distribution views.

Specific idea: Read the configuration file at the beginning of the servlet interceptor, save the configuration to the map, intercept the request, initialize the baseaction, reflect the specific action class, execute the configured method or the default Execute method.


Small frame named Galic, haha, the total interceptor servlet is called Galicservlet

public class Galicservlet extends HttpServlet {private static final long serialversionuid = 1L;
		@Override public void Init () throws Servletexception {Super.init ();
		try {galicparser.init ();
		catch (Exception e) {e.printstacktrace ();
    } public Galicservlet () {super ();
		} protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
	DoPost (request, response); 
		} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
		Request.setcharacterencoding ("UTF-8");
		String uri = Request.getrequesturi ();
		String ContextPath = Request.getcontextpath ();
		String Actionpath = Uri.replace (contextpath+ "/", "");
		Galicaction action = Galicparser.getactionbypath (Actionpath);
			if (action!= null) {String methodname = Action.getmethod ();
			String className = Action.getclazz ();
			
if (methodname = = null) methodname = "Execute";			Class clazz = Galicparser.getactionclassbyname (className);
			Object instance = reflectutil.getclassinstance (clazz, request, response);
			String resultname = Reflectutil.invokemethodnoargs (Clazz, instance, methodname). ToString ();
			Galicresult result = Action.getresults (). get (Resultname);
			String Resulttype = Result.gettype ();
			String Resultview = Result.getview (); /* <action path= "topic.do" class= "org.mybatis.bbs.action.TopicAction" method= "topic" > <result name= "suc"
			
			Cess "view="/res/topic.jsp "/> <result name=" error "view="/error.jsp "/> </action> * *
			if ("redirect". Equals (Resulttype)) {response.sendredirect (Contextpath+resultview); }else if ("JSON". Equals (Resulttype)) {}else if (' None '. Equals (Resulttype)) {}else{Request.getrequestdis
			Patcher (Resultview). Forward (request, response); }
		}
	}
}
Galicparser is the XML configuration file parser, where the configuration information is read into the map in the Init method

public class Galicparser {private static String Galic_config = "Galic-config.xml";
	private static map<string,galicaction> Galic_map;
	private static map<string,class> Galic_action_class_map = new hashmap<string, class> (0); public static void Init () throws exception{if (Galic_map = null) {Galic_map = new hashmap<string, galicaction&
		gt; ();
		}else{return;
		Saxreader reader = new Saxreader ();
		Document doc = Reader.read (GalicParser.class.getClassLoader (). getResourceAsStream (Galic_config));
		if (doc = = null) return;
		List<element> actionlist = doc.selectnodes ("//galic/action"); for (Element el:actionlist) {if (El.selectnodes ("result"). Size () ==0) throw new Galicexception ("Action" +el.attrib
			
			Utevalue ("path") + "' should have at least 1.");
			List<element> resultlist = (list<element>) el.selectnodes ("result");
			map<string,galicresult> results = new hashmap<string,galicresult> (0); for (Element rel: resultlist) {results.put (Rel.attributevalue ("name"), New Galicresult (Rel.attributevalue ("type"), rel.attr
			Ibutevalue ("View")); Galicaction ga = new Galicaction (El.attributevalue ("path"), El.attributevalue ("class"), El.attribut
			Evalue ("method"), results);
			Galic_map.put (El.attributevalue ("path"), GA);
		Galic_action_class_map.put (El.attributevalue ("Class"), Reflectutil.reflectclass (El.attributevalue ("class"));
	} System.out.println ("Galic initialized.");
	public static galicaction Getactionbypath (String path) {return galic_map.get (path);
	public static Class Getactionclassbyname (String classfullname) {return galic_action_class_map.get (classfullname); }
}
Reflectutil is primarily used to reflect action classes

public class Reflectutil {public static class Reflectclass (String className) {try {return class.forname Classnam
		e);
		catch (ClassNotFoundException e) {e.printstacktrace ();
	return null; public static Object getclassinstance (Class clazz, httpservletrequest request, httpservletresponse response) {T
			ry {Object ins = clazz.newinstance (); Invoke Sethttpservlet of Baseaction to initialize instance of Xxxaction Invokemethodwithargs (Clazz.getsuperclass (),
			INS, "Sethttpservlet", New Class[]{httpservletrequest.class, httpservletresponse.class}, request, response);
			Setattributesforinstance (Clazz,ins,request,null);
		return ins;
		catch (Exception e) {e.printstacktrace ();
	return null; private static void Setattributesforinstance (Class clazz, Object ins, httpservletrequest request, String prefix) t Hrows Exception {if (Prefix!=null&&prefix.indexof (".")! =-1) return; Do not assign value to level two attribute field[] fields = clazz.getdeclAredfields ();
			for (Field f:fields) {f.setaccessible (true);
			String Typeclass = F.gettype (). Getsimplename ();
			String fname = F.getname (); if (prefix!=null) fname = prefix+ "."
			+fname;
			String paramvalue = Request.getparameter (fname); try {if ("int". Equalsignorecase (typeclass) | |
				Integer ". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, Integer.parseint (paramvalue));
				}else if ("float". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, float.parsefloat (paramvalue));
				}else if ("Double". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, double.parsedouble (paramvalue));
				}else if ("Long" equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, Long.parselong (paramvalue));
				}else if ("short". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, Short.parseshort (paramvalue)); }else if ("Boolean". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (INS, boolean.parsebooleAn (paramvalue)); }else if ("Object". Equalsignorecase (typeclass) | | "
				String ". Equalsignorecase (Typeclass)) {if (paramvalue!= null) f.set (ins, paramvalue);
					}else{Object fieldins = F.gettype (). GetConstructor (). newinstance ();
					F.set (ins, fieldins);
				Setattributesforinstance (F.gettype (), fieldins, request, fname);
			} catch (IllegalArgumentException e) {e.printstacktrace ();
			catch (Illegalaccessexception e) {e.printstacktrace (); }} public static object Invokemethodnoargs (Class clazz, Object classinstance, String methodname) {object result
		= NULL;
			try {Method method = Clazz.getmethod (methodname);
			Method.setaccessible (TRUE);
		result = Method.invoke (classinstance);
		catch (Exception e) {e.printstacktrace ();
	return result; public static Object Invokemethodwithargs (Class clazz, Object classinstance, String methodname, class[] Argtype, Obje Ct...
		args) {Object result = null; try {Method method = Clazz.getDeclaredmethod (methodname, Argtype);
			Class returntype = Method.getreturntype ();
			Method.setaccessible (TRUE);
		result = Method.invoke (classinstance, args);
		catch (Exception e) {e.printstacktrace ();
	return result; }
}
Baseaction is primarily used to encapsulate Serlvet APIs and to provide some constants and methods for action subclasses

Public abstract class baseaction{protected static String SUCCESS = "SUCCESS";
	protected static String error = "Error";
	protected static String JSON = "JSON";
	protected static String none = "None";
	
	protected map<string,object> Servletmap = new hashmap<string, object> (0);
	Public baseaction () {System.out.println ("base action initialized.");
		Public Baseaction (HttpServletRequest request, httpservletresponse response) {servletmap.put ("request", request);
	Servletmap.put ("response", response);
	
	Public abstract String execute (); protected void Sethttpservlet (HttpServletRequest request, httpservletresponse response) {servletmap.put ("request")
		request);
		Servletmap.put ("response", response);
	Servletmap.put ("Session", Request.getsession ());
	} protected void Setapplicationvalue (String key, Object value) {Getservletcontext (). setattribute (key, value); } protected Object Getapplicationvalue (String key) {return Getservletcontext (). getattribute (kEY);
	} protected void Removeapplicationvalue (String key) {Getservletcontext (). removeattribute (key);
	} protected void Setcontextvalue (String key, Object value) {getservletrequest (). setattribute (key, value);
	} protected void Setsessionvalue (String key, Object value) {getservletsession (). setattribute (key, value);
	} protected Object Getsessionvalue (String key) {return getservletsession (). getattribute (key);
	} protected void Removesessionvalue (String key) {getservletsession (). removeattribute (key);
		} protected void Writejsonvalue (String jsonstring) {httpservletresponse response = Getservletresponse ();
		Response.setcharacterencoding ("Utf-8");
		PrintWriter pw = null;
			try {pw = Response.getwriter ();
		Pw.write (jsonstring);
		catch (IOException e) {e.printstacktrace ();
		} finally{if (pw!=null) pw.close ();
	} protected ServletContext Getservletcontext () {return getservletrequest (). GetSession (). Getservletcontext (); } protected HttpserVletrequest Getservletrequest () {return (HttpServletRequest) servletmap.get ("request");
	} protected HttpServletResponse Getservletresponse () {return (HttpServletResponse) servletmap.get ("response");
	} protected HttpSession Getservletsession () {return (HttpSession) Servletmap.get ("session"); }
}
The classes in which the action is encapsulated and the class that encapsulates action result are simple, as follows

public class Galicaction {
	private String path;
	Private String Clazz;
	Private String method;
	Private map<string,galicresult> results;
	
	Public galicaction () {
	} public
	galicaction (string path, String clazz,string method,
			map<string, Galicresult> results) {
		This.path = path;
		This.clazz = Clazz;
		This.method = method;
		This.results = results;
	}
	Public String GetPath () {return
		path;
	}
	public void SetPath (String path) {
		This.path = path;
	}
	Public String Getclazz () {return
		clazz;
	}
	public void Setclazz (String clazz) {
		this.clazz = clazz;
	}
	Public String GetMethod () {return method
		;
	}
	public void Setmethod (String method) {
		This.method = method;
	}
	Public map<string, Galicresult> GetResults () {return
		results;
	}
	public void SetResults (map<string, galicresult> results) {
		this.results = results;
	}
}
public class Galicresult {
	private String type;
	Private String view;
	
	Public Galicresult () {
	} public

	Galicresult (string type, string view) {
		this.type = type;
		This.view = view;
	}

	Public String GetType () {return
		type;
	}

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

	Public String GetView () {return
		view;
	}

	public void Setview (String view) {
		This.view = view;
	}
}
The writing is very simple, everybody does not take the brick. Use the same configuration and struts2, first in the Web.xml to add Galicservlet configuration, and then classpath add Galic-config.xml Configuration action and view.

<servlet>
    <servlet-name>GalicServlet</servlet-name>
    <servlet-class> org.mybatis.bbs.frame.servlet.galicservlet</servlet-class>
  </servlet>
  < servlet-mapping>
    <servlet-name>GalicServlet</servlet-name>
    <url-pattern>*.do </url-pattern>
  </servlet-mapping>
Galic-config.xml
<?xml version= "1.0" encoding= "UTF-8"?> <galic> <action path= "index.do" class= " Org.mybatis.bbs.action.IndexAction "> <result name=" Success "view="/index.jsp "/> <result" error " view= "/error.jsp"/> </action> <action path= "topics.do" class= "Org.mybatis.bbs.action.TopicAction" method= "Topics" > <result name= "Success" view= "/res/topic_list.jsp"/> <result "name=" error "view=" error.jsp "/> </action> <action path=" topic.do "class=" org.mybatis.bbs.action.TopicAction "method=" topic "> <result name=" Success "view="/res/topic.jsp "/> <result name=" error "view="/error.jsp "/> </action > <action path= "pub_topic.do" class= "org.mybatis.bbs.action.TopicAction" method= "pub_topic" > <result nam E= "Success" view= "/res/pub_topic.jsp"/> <result name= "error" view= "/error.jsp"/> <result name= "Go_login" view= "/login.jsp" ></result> </action> <action path= "add_tOpic.do "class=" org.mybatis.bbs.action.TopicAction "method=" Add_topic "> <result name=" Success "view="/res/ welcome.jsp "/> <result name=" error view= "/error.jsp"/> <result name= "Go_login" view= "/login.jsp" > </result> </action> <action path= "comments.do" class= org.mybatis.bbs.action.CommentAction "method=" Comments "> <result name=" Success "type=" json "/> </action> <action path=" pub_comment.do "class=" org . Mybatis.bbs.action.CommentAction "method=" pub_comment "> <result name=" Success "type=" JSON "/> </action > <action path= "verifyimage.do" class= "org.mybatis.bbs.action.ImageAction" > <result name= "Success" type= "None"/> </action> <action path= "register.do" class= "Org.mybatis.bbs.action.UserAction" method= " Register "> <result name=" Success "view=/res/welcome.jsp"/> <result name= "fail" view= "/register.jsp" /> </action> <action path= "Login.do" CLAss= "org.mybatis.bbs.action.UserAction" method= "Login" > <result name= "Success" view= "/res/welcome.jsp"/> <result name= "fail" view= "/login.jsp"/> </action> <action path= "logout.do" class= "Org.mybatis.bbs.act" Ion.  Useraction "method=" logout "> <result name=" Success "view="/res/goodbye.jsp "/> </action> <action Path= "Online.do" class= "org.mybatis.bbs.action.UserAction" method= "online" > <result name= "Success" type= "json "/> </action> </galic>
The root element in the struts2 is struts, and here it is replaced by Galic.

I write a small demo with MyBatis, can download to the source code here

http://download.csdn.net/detail/dyyaries/5720599
Write very humble, hope not to be ridiculed ~ ~.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.