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。

  • 相关阅读:
    Android Studio 生成Jar包时遇到的gradlew下载问题
    未解决问题
    Android -- android.os.Parcelable[] cannot be cast to ...
    vulkan gpu limits in mali
    Why GPU Program is expensive in CPU
    iOS native plugin 的代码sample
    USC-- compute shader ps vs
    zprepass 之后再base pass为什么用equal不用lessequal
    memory management Vulkan
    hlslcc
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12690280.html
Copyright © 2011-2022 走看看