RequestContext

package util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RequestContext
{
    private ServletContext servletContext;

    private HttpSession session;

    private HttpServletRequest request;

    private HttpServletResponse response;

    private final static ThreadLocal<RequestContext> context = new ThreadLocal<RequestContext>();

    protected static RequestContext begin(ServletContext servletContext, HttpServletRequest req, HttpServletResponse res)
            throws UnsupportedEncodingException
    {
        RequestContext rc = new RequestContext();
        rc.servletContext = servletContext;
        req.setCharacterEncoding("UTF-8");
        rc.request = req;
        rc.response = res;
        rc.session = req.getSession();
        context.set(rc);
        return rc;
    }

    protected void end()
    {
        this.servletContext = null;
        this.request = null;
        this.response = null;
        this.session = null;
        context.remove();
    }

    protected static ServletContext getServletContext()
    {
        return context.get().servletContext;
    }

    protected static HttpSession getSession()
    {
        return context.get().session;
    }

    protected static HttpServletRequest getRequest()
    {
        return context.get().request;
    }

    protected static HttpServletResponse getResponse()
    {
        return context.get().response;
    }

    protected static void redirect(String url)
    {
        try
        {
            HttpServletRequest request = getRequest();
            String basePath = getRequest().getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + "/";
            context.get().response.sendRedirect(basePath + url);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    protected static void forward(String url)
    {
        RequestDispatcher rd = getRequest().getRequestDispatcher(url);
        try
        {
            rd.forward(getRequest(), getResponse());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    protected static void invalidate()
    {
        RequestContext.getSession().invalidate();
    }
}

 

你可能感兴趣的:(request)