zoukankan      html  css  js  c++  java
  • 利用反射优雅的处理用户请求

    我们使用servlet接收用户请求时,会将不同的请求,发送个不同不同的servlet,这样不够优雅。而且扩展功能的时候,要新建许多servlet。

    比如说,对于用户,我们可能需要  登录、注册、修改密码、注销等。但是它都是用户的操作。我们可以通过反射,来将用户的操作,提交给同一个servlet,然后分发给不同的函数:

    以登录为例

    <div class="form">
    <form action="userServlet" method="post">
        <input type="hidden" name="action" value="login" />
        <label>用户名称:</label>
        <input class="itxt" type="text" placeholder="请输入用户名"
               autocomplete="off" tabindex="1" name="username"
               value="" />
        <br />
        <br />
        <label>用户密码:</label>
        <input class="itxt" type="password" placeholder="请输入密码"
               autocomplete="off" tabindex="1" name="password" />
        <br />
        <br />
        <input type="submit" value="登录" id="sub_btn" />
    </form>
    </div>
    View Code

    我们添加一个  <input type="hidden" name="action" value="login" />  隐藏项。然后在userServlet中,通过反射处理

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //doGet(request, response);
        String action = request.getParameter("action");
        
         try {
            Method m = this.getClass().getDeclaredMethod(action, HttpServletRequest.class,HttpServletResponse.class);
            try {
                m.invoke(this, request,response);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    userServlet

    这样就可以优雅的把一类功能提交给一个servlet。

  • 相关阅读:
    struts2 <s:iterator> 遍历方法
    JSP 基础之 JSTL <c:forEach>用法
    struts2 中 Session的使用简介
    Struts2 工作流程
    Aandroid Error之 新导入工程报Unable to resolve target 'android-18'和R cannot be resolved
    纯Html+Ajax和JSP两者对比的个人理解
    移动互联网App兼容性测试
    【转】【Mac】invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library
    【转】Mac使用apt-get
    有趣网址之家 – 收藏全球最有趣的网站
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12690280.html
Copyright © 2011-2022 走看看