BaseServlet的最终版设计

 

BaseServlet的最终版设计

其中解决了页面的get方式及post方式的提交、解决了页面的转发和重定向的提交、解决了页面后缀(.jsp)的省略书写

package cn.javabs.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 这里使用的是Servlet的3.0注解式开发!
*/ @WebServlet(urlPatterns = {"/baseServlet"}) public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //--------------------------------------------处理编码-------------------------------------------------       // 如果是以get方式提交,交由GetServlet进行处理! if(req.getMethod().equalsIgnoreCase("get")){ req = new GetServlet(req); }else{
        // 这里则是以Post方式进行提交的结果 req.setCharacterEncoding("utf-8"); }        resp.setCharacterEncoding("utf-8"); resp.setContentType("type=text;charset=utf-8"); //--------------------------------------------------------------------------------------------- // 1. 获取访问地址的uri String uri = req.getRequestURI(); // 2. 获取uri最后一个斜线的位置:找到uri中最后 一个斜线的位置 int currentPosition = uri.lastIndexOf('/'); // 3. 获取方法名称:截取uri中最后一个斜线 之后的单词 注意:substring方法是包含开头、但是不包含结尾,故而在原有的位置之上进行加1操作 String methodName = uri.substring(currentPosition + 1); System.out.println("调用的方法名称是:"+ methodName); // 4. 谁继承BaseServlet、并且调用了BaseServlet,谁就是this Class<? extends BaseServlet> clazz = this.getClass(); try { // 5. 通过反射机制拿到的clazz(调用对象) 进行忽略访问权限进而获取clazz中的方法,参数为方法名称,请求对象、响应对象 Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); // 6. 获取调用的返回值 并且通过invoke方法执行调用业务方法 String dispatcherPage = (String) method.invoke(this, req, resp); // 7. 接受到的转发页面 // System.out.println("接受到的页面字符串为:" + dispatcherPage ); String page ;
        // 判断 转发页面中是否包含 冒号、用于判断继承类中是否写入了 forward或者是redirect ,有冒号,则表示写入了! if(dispatcherPage.contains(":")){ String[] datas = dispatcherPage.split(":"); System.out.println("分隔后第一个数据"+datas[0] + "分隔后第二个数据"+datas[1]); page = datas[1]; if("forward".equals(datas[0])){ // 8. 根据接受到的界面进行转发! req.getRequestDispatcher(page+".jsp").forward(req,resp); }else if("redirect".equals(datas[0])){ resp.sendRedirect(req.getContextPath() + page+".jsp"); } }else{ // 如果没有写入forward:或者是 redirect: 则默认采用转发页面 page = dispatcherPage; System.out.println("page:"+page); if (page == null || page == ""){ resp.sendRedirect(req.getContextPath() +"/500.jsp"); }else { req.getRequestDispatcher(page + ".jsp").forward(req, resp); } } } catch (Exception e) { throw new RuntimeException("BaseServlet有异常!"+e); } } }

  辅助用到的类还有GetServlet

package cn.javabs.web.servlet;

import com.sun.xml.internal.bind.v2.schemagen.xmlschema.TypeHost;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebServlet(name = "GetServlet")
public class GetServlet extends HttpServletRequestWrapper {

    private HttpServletRequest request;


    @Override
    public String getParameter(String name) {

        if(name == null){return  null;}

        String newName = super.getParameter(name);

        try {
            newName =  new String(newName.getBytes("ISO-8859-1"),"utf-8");
            return newName;
        } catch (UnsupportedEncodingException e) {
           throw new RuntimeException("get方式提交的编码异常"+e);
        }

    }

    public GetServlet(HttpServletRequest request) {
        super(request);
        this.request = request;
    }
}

  测试的Servlet是DepartmentServlet

package cn.javabs.web.servlet;

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

@WebServlet(urlPatterns = {"/departmentServlet/*"})
public class DepartmentServlet extends BaseServlet {

  // 用于测试: 请求转发跳转 protected String addDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println("name:"+name); System.out.println("添加部门"); return "forward:/index2"; }
  // 用于测试:重定向跳转 protected String findDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("查询部门"); return "redirect:/main"; }
  // 用于测试:如果不添加转发和重定向的单词怎么解决。 |这里我在BaseServlet做了判断,如果返回值没有写入forward和redirect,会默认以转发请求方式进行跳转 protected String editDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("编辑部门"); return "/main2"; }
  // 用于测试:如果为空字符串怎么解决。 | 这里我在BaseServlet做了判断,如果返回的null或者是空字符串 ,会跳转到500.jsp protected String delDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("删除部门"); return ""; } }

  

上一篇:CookieUitl


下一篇:SpringMVC__自定义简单的拦截器