增强HttpServlet实现类似于Struts的配置

wangjianme 10年前

增强HttpServlet实现类似于Struts的配置

       页面的转发和重定向,都必须要在web.xml中进行配置。实现程序的可配置的功能。

       通过反射,在接收到目标servlet的返回的字符串以后。如果不是null。则决定是转发还是重定向到目标页面。

以下是完整源代码:

package cn.itcast.pubs;

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;

/**

 * 用户继承此类,处理多方法,接收用户的返回值转发或是重定向到其他资源<br/>

 * 如果是重定向可以向request中设置名称为param的属性,<br/>

 * request.setAttribute("param","name=Jack");<br/>

 * 默认为转发<br/>

 * 如果不希望此工具类为你转发,则可以返回null

 * @author <a href="wangjian_me@126.com">王健</a>

 */

public abstract class Base3Servlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override

    public void doGet(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException {

       doPost(req, resp);

    }

    @Override

    public void doPost(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException {

       req.setCharacterEncoding("UTF-8");//此处应该通过过虑器(Filter)设置编码

       String cmd = req.getParameter("cmd");

       if(cmd==null || cmd.trim().equals("")){

           cmd = "execute";

       }

       try{

           Method m = this.getClass().getMethod(cmd,HttpServletRequest.class,HttpServletResponse.class);

           String result = (String) m.invoke(this,req,resp);

           if(result!=null){

              if(result.startsWith("redirect:")){

                  result = result.substring(result.lastIndexOf(":")+1);       //截取redirect后面的值

                  String page = getPage(result);

                  //获取参数,最后结果为some.jsp?name=Jack&...

                  String param=(String) req.getAttribute("param");

                  if(param!=null){

                     page = page+"?"+param;

                  }

                  System.err.println("page is :"+page);

                  if(page.startsWith("http")){

                     resp.sendRedirect(page);//重定向到外部网站

                  }else{

                     resp.sendRedirect(req.getContextPath()+page);//重定向到本网内的网页

                  }

              }else{

                  String page = getPage(result);

                  req.getRequestDispatcher(page).forward(req, resp);

              }

           }

       }catch(NoSuchMethodException e){

           throw new RuntimeException("没有此方法:"+e.getMessage(),e);

       }catch(Exception e){

           throw new RuntimeException(e.getMessage(),e);

       }

    }

    /**

     * 先在此Servlet中查找,如果没有则到Context中查找配置

     */

    private String getPage(String result){

       String page = getInitParameter(result);                     //获取配置页面,先在此Servlet中找,如果没有则再找

       if(page==null){

           page = getServletContext().getInitParameter(result); //如果在servlet配置到找不到则找Context范围

       }

       return page;

    }

    /**

     * 要求返回一个String,根据String串获取配置的初始化参数<br/>

     * 转发或是重新定向到目标页面<br/>

     * redirect:前缀为重定向,即return "redirect:page";<br/>

     * 默认为转发

     */

    public abstract String execute(HttpServletRequest req,HttpServletResponse resp) throws Exception;

}

以下是使用示例:

配置示例如下

<context-param>

       <param-name>back</param-name>

       <param-value>/jsps/result.jsp</param-value>

</context-param>

<servlet>

       <servlet-name>back</servlet-name>

       //以下BackStringServlet类,它继承了Base3Servlet工具类

       <servlet-class>cn.itcast.servlet.BackStringServlet</servlet-class>

       <init-param>

           //先在这儿查找back,如果这儿没有,再查找Context的配置

           <param-name>back</param-name>

           <param-value>/jsps/result.jsp</param-value>

       </init-param>

</servlet>

BackStringServlet.java源代码如下:

package cn.itcast.servlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import cn.itcast.pubs.Base3Servlet;

public class BackStringServlet extends Base3Servlet{

    @Override

    public String execute(HttpServletRequest req, HttpServletResponse resp)

           throws Exception {

       req.setAttribute("name", "Jack");

       return "back";

       //也可以按以下方式返回,redirect决定为重定向

       //return "redirect:back";

    }

}