优雅自定义请求&servlet方法调用一体化

2017-09-07 飞鸟

开篇

新入手java开发,在学习servlet的过程中,大家都知道sevlet是请求响应模式,那么一个httpservlet之定义了service(),doget(),dopost()方法,极大的限制开发效率,如何做到网络请求就像调用java中的函数一样轻松?,接下来就该问题简单聊一聊个人想法。

Filter分发请求

过滤器在站点初始化的时候会init,通过在web.xml中的url-pattern配置,所有的该路径下的请求都会最先通过Filter的doFilter方法,那么,我们就可以再该方法中分发我们的请求,前提是,我们要对URL进行处理,在去分发。

@Override
    public void init(FilterConfig filterConfig) throws ServletException {
    //获取web.xml中的init-param参数(扩展性强)
        Log.e("Encoding-start");
        String s = filterConfig.getInitParameter("sqlit");
        if (s==null||s.equals("")){
            sqlit = "!";
        }else sqlit = s;
    }
@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//这里可以强转servletRequest的实质就是HttpServletRequest 对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String[] strs = req.getRequestURI().toString().split(sqlit);
       if (strs.length>1)
         servletRequest.setAttribute("method",strs[1]);
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        Log.e("Encoding-do");
        String context = servletRequest.getServletContext().getContextPath();
        String dispatcherPath = strs[0].replace(context,"");
        servletRequest.getRequestDispatcher(dispatcherPath).forward(servletRequest,servletResponse);
    }

创建Servlet基类BaseAction

该基类我们要处理一件事,就是讲请求分发至方法,不同的请求调用对应的方法。

package com.yzz.java.base;
import com.yzz.java.util.Log;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by yzz on 2017/9/6.
 * mail:yzzstyle@163.com
 */

public class BaseAction extends HttpServlet{
    protected HttpServletRequest req;
    protected HttpServletResponse resp;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req = req;
        this.resp = resp;
        String method = (String) req.getAttribute("method");
        try {
            this.getClass().getMethod(method).invoke(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用

集成BaseAction,然后使用跟普通的java类没有任何区别

package com.yzz.java.action.cookie;

import com.yzz.java.base.BaseAction;
import com.yzz.java.util.Log;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by yzz on 2017/9/6.
 * mail:yzzstyle@163.com
 */

public class CookieServlet extends BaseAction {

    public void setCookie() throws Exception{
        String name = req.getParameter("name");
        Log.e(name);
        Map<String,String[]> map = req.getParameterMap();
        for (Map.Entry<String,String[]> en:map.entrySet()){
            for (String str:en.getValue()) {
                String encodestr = URLEncoder.encode(str,"utf-8");
                Log.e(encodestr);
                Cookie cookie = new Cookie(en.getKey(),encodestr);
                cookie.setPath(getServletContext().getContextPath());
                cookie.setHttpOnly(true);
                cookie.setMaxAge(10);
                resp.addCookie(cookie);
            }
        }
        resp.getWriter().write("已保存cookie");
    }

    public void deleteCookie() throws Exception{
        Cookie[] cookie = req.getCookies();
        for (Cookie c:cookie){
            c.setMaxAge(0);
            resp.addCookie(c);
        }
        resp.getWriter().write("删除成功");
    }
}

总结

本工具尚未实现将body的参数转化为Bean像SpringMVC一样,由于时间问题,我就不做这块了,下次再补充。欢迎交流,各位大佬。


用户评论
开源开发学习小组列表