Custom struts framework, customstruts

Source: Internet
Author: User

Custom struts framework, customstruts

1. Difference between stucts1 and struts2

Struts1: Servlet used as Controller, you can visit the Servlet directly, code like if --- else if -- else

Struts2: Filter used as Controller, you can only visit passively, though setting the condition like "/*"

 

2. Imitate the core Filter of Struts2 (StrutsPrepareAndExecuterFilter. java)

Version 1.0 (like struts1)

package com.cdv.web.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet Filter implementation class StrutsPreparedAndExecuterFilter */public class StrutsPreparedAndExecuterFilter implements Filter {    /**     * Default constructor.      */    public StrutsPreparedAndExecuterFilter() {        // TODO Auto-generated constructor stub    }    /**     * @see Filter#destroy()     */    public void destroy() {        // TODO Auto-generated method stub    }    /**     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)     */    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) resp;        String uri = request.getRequestURI();        boolean isDo = uri.endsWith(".do");        if(isDo){            //get the operation            String op = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));            if(op.equals("login")){                request.setAttribute("username", "zhangsan");            }else{                //to do something            }        }else{            //            chain.doFilter(request, response);        }    }    /**     * @see Filter#init(FilterConfig)     */    public void init(FilterConfig fConfig) throws ServletException {        // TODO Auto-generated method stub    }}

 

Version 2.0:

We need create the interface, for creating different instance aim at different params condition, and use the map instead of if -- else

package com.cdv.web.action;import javax.servlet.http.HttpServletRequest;public interface Action {    String execute(HttpServletRequest request);}
package com.cdv.web.action;import javax.servlet.http.HttpServletRequest;public class LoginAction implements Action {    @Override    public String execute(HttpServletRequest request) {        String username = request.getParameter("username");        if(username.equals("zhangsan")){            return "ok";        }        return null;    }}
package com.cdv.web.filter;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.cdv.web.action.Action;import com.cdv.web.action.LoginAction;/** * Servlet Filter implementation class StrutsPreparedAndExecuterFilter */public class StrutsPreparedAndExecuterFilter2 implements Filter {    private Map<String, Action> actionMap = new HashMap<String, Action>();    /**     * Default constructor.      */    public StrutsPreparedAndExecuterFilter2() {        // TODO Auto-generated constructor stub    }    /**     * @see Filter#destroy()     */    public void destroy() {        // TODO Auto-generated method stub    }    /**     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)     */    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) resp;        String uri = request.getRequestURI();        boolean isDo = uri.endsWith(".do");        if(isDo){            String op = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));            Action instance = actionMap.get(op);            String result = instance.execute(request);            if(result.equals("ok")){                request.setAttribute("user", "zhangsan");            }        }else{            chain.doFilter(request, response);        }    }    /**     * @see Filter#init(FilterConfig)     */    public void init(FilterConfig fConfig) throws ServletException {        actionMap.put("login", new LoginAction());        //actionMap.put("logout", new LogoutAction());        //...    }    }

 

Version 3.0:

Put the value of instance into xml file, use dom4j to parse it, and use reflect technology to create instance dynamic.

Struts. xml

<?xml version="1.0" encoding="UTF-8"?><package name="mypackage">    <action name="loginAction" class="com.cdv.web.action.LoginAction"></action>    <action name="logoutAction" class="com.cdv.web.action.LogoutAction"></action></package>
Package com. cdv. web. filter; import java. io. IOException; import java. util. hashMap; import java. util. map; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. cdv. web. action. action; import com. cdv. web. action. loginAction;/*** Servlet Filter implementation class StrutsPreparedAndExecuterFilter */public class implements Filter {private Map <String, Action> actionMap = new HashMap <String, Action> (); /*** Default constructor. */public StrutsPreparedAndExecuterFilter3 () {// TODO Auto-generated constructor stub}/*** @ see Filter # destroy () */public void destroy () {// TODO Auto-generated method stub}/*** @ see Filter # doFilter (ServletRequest, ServletResponse, FilterChain) */public void doFilter (ServletRequest req, ServletResponse resp, filterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String uri = request. getRequestURI (); boolean isDo = uri. endsWith (". do "); if (isDo) {String op = uri. substring (uri. lastIndexOf ("/"), uri. lastIndexOf (". "); Action instance = actionMap. get (op); String result = instance.exe cute (request); if (result. equals ("OK") {request. setAttribute ("user", "zhangsan") ;}} else {chain. doFilter (request, response) ;}}/*** @ see Filter # init (FilterConfig) */public void init (FilterConfig fConfig) throws ServletException {// perform dom4j parsing, set struts. retrieve the name and value in xml, // and convert the class value to the object Using Reflection/* Document document = Dom4jUtil. getDocument (); List <Node> list = document. selectNodes ("// action"); for (Node node: list) {// traverses the action node and obtains the String key = Node. valueOf ("@ name"); String value = node. valueOf ("@ class"); actionMap. put (key, (Action) Class. forName (value ). newInstance ());}*/}}

 

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.