Java Web之BaseServlet的抽取

YungFan發表於2017-12-13

在Java Web學習的初期,開發的小專案幾乎都是JSP+Servlet+JDBC,長期開發下來,會發現當業務邏輯設計的介面一多的時候,充當控制器的Servlet也會越來越多,但是處理的業務邏輯相對單一。後來學習Struts2或者SpringMVC,發現它們處理起來優雅得多,但是配置起來也比純的Servlet要繁瑣,對於經常做小專案的我來說有點大材小用了,於是我根據前人的經驗抽離了一個BaseServlet,用反射的機制來處理請求,這樣處理業務邏輯的Servlet要相對簡單的多,廢話不說,把自己使用的一套拿出來曬曬。

BaseServlet

由於伺服器端經常是用JSON與Android和iOS客戶端進行互動,所以這裡返回的就是JSON資料

//這個抽象類,BaseServlet類不需要在web.xml中進行配置
public abstract class BaseServlet extends HttpServlet {

    // final 防子類複寫
    public final void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    public final void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1、獲得執行的方法名
        String methodName = request.getParameter("method");
        // 預設方法
        if (methodName == null) {
            methodName = "execute";
        }

        System.out.println("BaseServlet : " + this + " , " + methodName);

        try {
            // 2、通過反射獲得當前執行類中指定方法,形式引數
            Method executeMethod = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 3、反射執行方法
            String result = (String)executeMethod.invoke(this, request, response);
            // 4、將json資料返回
            response.getWriter().write(result);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("請求的方法[" + methodName + "]不存在");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("伺服器異常", e);
        }
    }

    /**
     * 此方法用於複寫,方便子類程式設計,預設執行方法
     */
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}
複製程式碼

真正處理業務邏輯的Servlet

需要做的就是繼承上面的BaseServlet,然後根據業務需求寫自己的方法即可,乍一看像SpringMVC,但是要注意這裡的方法名和返回值,方法名決定了請求時的method引數的值,返回值由於是JSON,所以用的是String。

public class UserServlet extends BaseServlet {

    public String users(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<User> users = new ArrayList<User>();
        for (int i = 0; i < 10; i++) {
            User user = new User(i, "zhangsan" + i, i + 10, "wukong" + i);
            users.add(user);
        }
        Gson gson = new Gson();
        return gson.toJson(users);
    }
}

==========================================================
//自定義的一個PO
public class User {

    private int id;
    private String name;
    private int age;
    private String nickname;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public User(int id, String name, int age, String nickname) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.nickname = nickname;
    }
}
複製程式碼

部署Servlet

將自己的業務UserServlet部署到web.xml,如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>test.app.api.UserServlet</servlet-class>
    </servlet>
    
    
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/UserServlet</url-pattern>
    </servlet-mapping>

</web-app>
複製程式碼

訪問Servlet

部署並啟動tomcat以後,開啟瀏覽器訪問:http://localhost/AppTestAPI/UserServlet?method=users 結果如下:

返回JSON結果.png

相關文章