blade中设计中对于HttpResponse的封装处理

HttpResponse封装

对于这个做了很多的处理,比如ViewStrings,处理模板引擎和json转换的工具哦,还有505,404页面的处理,整个设计非常的合适,易于扩展实现自己的json转换和模板工具哦,这些处理是怎么想到的呢?模板工具!

respond

这里response对于HttpServletResponse进行了封装,而且有很多的建筑者模式的风格
用起来比较好玩。

/**
 * HTTP Response
 */
public interface Response {

    HttpServletResponse raw();
    int status();

    /**
     * Setting Response Status
     *
     * @param status status code
     * @return Return Response
     */
    Response status(int status);

    /**
     * @return Setting Response Status is BadRequest and Return Response
     */
    Response badRequest();

    /**
     * @return Setting Response Status is unauthorized and Return Response
     */
    Response unauthorized();

    /**
     * @return Setting Response Status is notFound and Return Response
     */
    Response notFound();

    /**
     * @return Setting Response Status is conflict and Return Response
     */
    Response conflict();

    /**
     * @return Return Response contentType
     */
    String contentType();

    /**
     * Setting Response ContentType
     *
     * @param contentType content type
     * @return Return Response
     */
    Response contentType(String contentType);

    /**
     * Get header
     *
     * @param name Header Name
     * @return Return Response
     */
    String header(String name);

    /**
     * Setting header
     *
     * @param name    Header Name
     * @param value    Header Value
     * @return Return Response
     */
    Response header(String name, String value);

    /**
     * Setting Cookie
     *
     * @param cookie    Cookie Object
     * @return Return Response
     */
    Response cookie(Cookie cookie);

    /**
     * Setting Cookie
     *
     * @param name  Cookie Name
     * @param value Cookie Value
     * @return Return Response
     */
    Response cookie(String name, String value);

    /**
     * Setting Cookie
     *
     * @param name   Cookie Name
     * @param value  Cookie Value
     * @param maxAge Period of validity
     * @return Return Response
     */
    Response cookie(String name, String value, int maxAge);

    /**
     * Setting Cookie
     *
     * @param name    Cookie Name
     * @param value   Cookie Value
     * @param maxAge  Period of validity
     * @param secured Is SSL
     * @return Return Response
     */
    Response cookie(String name, String value, int maxAge, boolean secured);

    /**
     * Setting Cookie
     *
     * @param path    Cookie Domain Path
     * @param name    Cookie Name
     * @param value   Cookie Value
     * @param maxAge  Period of validity
     * @param secured Is SSL
     * @return Return Response
     */
    Response cookie(String path, String name, String value, int maxAge, boolean secured);

    /**
     * Remove Cookie
     *
     * @param cookie    Cookie Object
     * @return Return Response
     */
    Response removeCookie(Cookie cookie);

    /**
     * Rmove Cookie By Name
     *
     * @param name Cookie Name
     * @return Return Response
     */
    Response removeCookie(String name);

    /**
     * Render by text
     *
     * @param text        text content
     * @return Return Response
     */
    Response text(String text);

    /**
     * Render by html
     *
     * @param html html content
     * @return Return Response
     */
    Response html(String html);

    /**
     * Render by json
     *
     * @param json json content
     * @return Return Response
     */
    Response json(String json);

    /**
     * Render by json
     *
     * @param bean
     * @return
     */
    Response json(Object bean);

    /**
     * Render by xml
     *
     * @param xml xml content
     * @return Return Response
     */
    Response xml(String xml);

    /**
     * @return Return OutputStream
     * @throws IOException IOException
     */
    OutputStream outputStream() throws IOException;

    /**
     * @return Return ResponseWriter Stream
     * @throws IOException
     */
    PrintWriter writer() throws IOException;

    /**
     * Render view
     *
     * @param view view page
     * @return Return Response
     */
    Response render(String view);

    /**
     * Render view And Setting Data
     *
     * @param modelAndView    ModelAndView object
     * @return Return Response
     */
    Response render(ModelAndView modelAndView);

    /**
     * Redirect to Path
     *
     * @param path location path
     */
    void redirect(String path);

    /**
     * Go to Path, Under contextpath
     *
     * @param path redirect location
     */
    void go(String path);

    /**
     * @return Return Response is Write
     */
    boolean isWritten();

}

ServletResponse

ServletResponse 不仅仅是对于httprespond的简单的封装,还有处理其他逻辑的变量信息,我们首先来看一看下主要的类结构信息

public class ServletResponse implements Response {

    private HttpServletResponse response;
    private boolean written = false;
    private ViewSettings viewSettings;
    private TemplateEngine templateEngine;
    private JSONParser jsonParser;

    public ServletResponse(HttpServletResponse response) {
        this.response = response;
        this.viewSettings = ViewSettings.$();
        this.templateEngine = viewSettings.templateEngine();
        this.jsonParser = viewSettings.JSONParser();
    }
    .......
}
  • 如上所示,我们的HttpResponse中有个ViewSetings,有个模板的引擎和一个Json的转换类的信息,一个个的看看吧!
  • TemplateEngine,哈哈面向接口编程必须是接口啊!,看英文的注释很好理解这个就是一个啥子,模板引擎,为了更好的呈现数据,呈现数据的方式更加的简单而创建。
import com.blade.mvc.view.ModelAndView;
import java.io.Writer;

/**
 * TemplateEngine Interface, For view layer to display data
 */
public interface TemplateEngine {

    void render(ModelAndView modelAndView, Writer writer) throws TemplateException;

}
  • ModelAndView这个更加好理解,SpringMvc用过的就懂了其实就是个Map
/**
 * ModelAndView, Using templates and data 
 *
 * @author    <a href="mailto:biezhi.me@gmail.com" target="_blank">biezhi</a>
 * @since 1.5
 */
public class ModelAndView {

    /**
     * Data object, the object is placed in the attribute httprequest
     */
    private Map<String, Object> model = new HashMap<>(8);

    private String view;

    public ModelAndView() {
    }

    public ModelAndView(String view) {
        super();
        this.model = CollectionKit.newHashMap();
        this.view = view;
    }
    public ModelAndView(Map<String, Object> model, String view) {
        super();
        this.model = model;
        this.view = view;
    }

    public void add(String key, Object value) {
        this.model.put(key, value);
    }
    public void remove(String key) {
        this.model.remove(key);
    }
    public String getView() {
        return view;
    }

    public void setView(String view) {
        this.view = view;
    }
    public Map<String, Object> getModel() {
        return model;
    }

    public void setModel(Map<String, Object> model) {
        this.model = model;
    }
  • JSONParser转换哈哈ObjectClass to jsonObjc
/**
 * Route render json parser
 */
public interface JSONParser {

    String toJSONSting(Object object);

}
  • ViewSettings对象中拥有了Json转换和模板引擎的对应类,估计就是用来设置模板引擎和设置json转换的吧!类的单一原则还是需要比较的清晰的去处理问题的,这个逻辑分的很明显的,估计有默认的实现,我们也可以自己去配置的。还有设置一下错误的界面。我们来看看吧。这个也是一个单例模式哦!
public final class ViewSettings {

    private JSONParser jsonParser = new DefaultJSONParser();
    private TemplateEngine templateEngine = new DefaultEngine();
    private String view404 = "404.html";
    private String view500 = "500.html";
    private ViewSettings() {
    }

    static final class ViewSettingsHolder {
        private static final ViewSettings $ = new ViewSettings();
    }
    public static ViewSettings $() {
        return ViewSettingsHolder.$;
    }

    public ViewSettings JSONParser(JSONParser jsonParser) {
        Assert.notNull(jsonParser);
        this.jsonParser = jsonParser;
        return this;
    }

    public JSONParser JSONParser() {
        return this.jsonParser;
    }

    public String toJSONString(Object object) {
        return jsonParser.toJSONSting(object);
    }

    /**
     * Setting Render Engin, Default is static file render
     *
     */
    public ViewSettings templateEngine(TemplateEngine templateEngine) {
        Assert.notNull(templateEngine);
        this.templateEngine = templateEngine;
        return this;
    }

    /**
     * @return Return Current TemplateEngine
     */
    public TemplateEngine templateEngine() {
        return this.templateEngine;
    }

    public String getView404() {
        return view404;
    }

    public ViewSettings setView404(String view404) {
        this.view404 = view404;
        return this;
    }

    public String getView500() {
        return view500;
    }

    public ViewSettings setView500(String view500) {
        this.view500 = view500;
        return this;
    }

}

默认的json转换和默认的引擎模板,去看看怎么实现的诶!

private JSONParser jsonParser = new DefaultJSONParser();
private TemplateEngine templateEngine = new DefaultEngine();

JSONParser 就是转换为字符串诶

public class DefaultJSONParser implements JSONParser {

    @Override
    public String toJSONSting(Object object) {
        return JSONKit.toJSONString(object);
    }

}

TemplateEngine 就是将所有的模板中字符串打印到浏览器上

public final class DefaultEngine implements TemplateEngine {

    private String templatePath = "/templates/";

    public DefaultEngine() {
    }

    public DefaultEngine(String templatePath) {
        this.templatePath = templatePath;
    }

    @Override
    public void render(ModelAndView modelAndView, Writer writer) throws TemplateException {
        try {
            HttpServletResponse servletResponse = WebContextHolder.response().raw();
            servletResponse.setContentType("text/html;charset=utf-8");
            String realPath = new File(Blade.$().webRoot() + File.separatorChar + templatePath + File.separatorChar + modelAndView.getView()).getPath();
            String content = StreamKit.readText(new BufferedReader(new FileReader(new File(realPath))));
            servletResponse.getWriter().print(content);
        } catch (IOException e) {
            throw new TemplateException(e.getMessage());
        }
    }

}

全部贴出来,封装了ServletResponse怎么样感觉!

public class ServletResponse implements Response {

    private HttpServletResponse response;
    private boolean written = false;
    private ViewSettings viewSettings;
    private TemplateEngine templateEngine;
    private JSONParser jsonParser;

    public ServletResponse(HttpServletResponse response) {
        this.response = response;
        this.viewSettings = ViewSettings.$();
        this.templateEngine = viewSettings.templateEngine();
        this.jsonParser = viewSettings.JSONParser();
    }

    @Override
    public HttpServletResponse raw() {
        return response;
    }

    @Override
    public int status() {
        return response.getStatus();
    }

    @Override
    public Response status(int status) {
        response.setStatus(status);
        return this;
    }

    @Override
    public Response badRequest() {
        response.setStatus(HttpStatus.BAD_REQUEST);
        return this;
    }

    @Override
    public Response unauthorized() {
        response.setStatus(HttpStatus.UNAUTHORIZED);
        return this;
    }

    @Override
    public Response notFound() {
        response.setStatus(HttpStatus.NOT_FOUND);
        return this;
    }

    @Override
    public Response conflict() {
        response.setStatus(HttpStatus.CONFLICT);
        return this;
    }

    @Override
    public String contentType() {
        return response.getContentType();
    }

    @Override
    public Response contentType(String contentType) {
        response.setContentType(contentType);
        return this;
    }

    @Override
    public String header(String name) {
        return response.getHeader(name);
    }

    @Override
    public Response header(String name, String value) {
        response.setHeader(name, value);
        return this;
    }

    @Override
    public Response cookie(Cookie cookie) {
        response.addCookie(cookie);
        return this;
    }

    @Override
    public Response cookie(String name, String value) {
        return cookie(name, value, -1);
    }

    @Override
    public Response cookie(String name, String value, int maxAge) {
        return cookie(name, value, maxAge, false);
    }

    @Override
    public Response cookie(String name, String value, int maxAge, boolean secured) {
        return cookie(null, name, value, maxAge, secured);
    }

    @Override
    public Response cookie(String path, String name, String value, int maxAge, boolean secured) {
        Cookie cookie = new Cookie(name, value);
        if (null != path) {
            cookie.setPath(path);
        }
        cookie.setMaxAge(maxAge);
        cookie.setSecure(secured);
        response.addCookie(cookie);
        return this;
    }

    @Override
    public Response removeCookie(Cookie cookie) {
        cookie.setMaxAge(0);
        response.addCookie(map(cookie));
        return this;
    }

    javax.servlet.http.Cookie map(Cookie cookie) {
        javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
        servletCookie.setMaxAge(cookie.getMaxAge());
        if (null != cookie.getPath()) {
            servletCookie.setPath(cookie.getPath());
        }
        if (null != cookie.getDomain()) {
            servletCookie.setDomain(cookie.getDomain());
        }
        servletCookie.setHttpOnly(cookie.isHttpOnly());
        servletCookie.setSecure(cookie.getSecure());
        return servletCookie;
    }

    @Override
    public Response removeCookie(String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return this;
    }

    @Override
    public Response text(String text) {
        try {
            this.header("Cache-Control", "no-cache");
            this.contentType("text/plain;charset=utf-8");
            DispatchKit.print(text, response.getWriter());
            this.written = true;
            return this;
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public Response html(String html) {
        try {
            this.header("Cache-Control", "no-cache");
            this.contentType("text/html;charset=utf-8");

            DispatchKit.print(html, response.getWriter());
            this.written = true;
            return this;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public Response json(String json) {
        Request request = WebContextHolder.request();
        String userAgent = request.userAgent();
        if (userAgent.contains("MSIE")) {
            this.contentType("text/html;charset=utf-8");
        } else {
            this.contentType("application/json;charset=utf-8");
        }
        try {
            this.header("Cache-Control", "no-cache");
            DispatchKit.print(json, response.getWriter());
            this.written = true;
            return this;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public Response json(Object bean) {
        return this.json(jsonParser.toJSONSting(bean));
    }

    @Override
    public Response xml(String xml) {
        try {
            this.header("Cache-Control", "no-cache");
            this.contentType("text/xml;charset=utf-8");
            DispatchKit.print(xml, response.getWriter());
            this.written = true;
            return this;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public ServletOutputStream outputStream() throws IOException {
        return response.getOutputStream();
    }

    @Override
    public PrintWriter writer() throws IOException {
        return response.getWriter();
    }

    @Override
    public Response render(String view) {
        String viewPath = Path.cleanPath(view);
        ModelAndView modelAndView = new ModelAndView(viewPath);
        try {
            templateEngine.render(modelAndView, response.getWriter());
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return this;
    }

    @Override
    public Response render(ModelAndView modelAndView) {
        Assert.notBlank(modelAndView.getView(), "view not is null");

        String viewPath = Path.cleanPath(modelAndView.getView());
        modelAndView.setView(viewPath);
        try {
            templateEngine.render(modelAndView, response.getWriter());
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return this;
    }

    @Override
    public void redirect(String path) {
        try {
            response.sendRedirect(path);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public void go(String path) {
        try {
            String ctx = WebContextHolder.servletContext().getContextPath();
            String location = Path.fixPath(ctx + path);
            response.sendRedirect(location);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public boolean isWritten() {
        return written;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值