Java反射的应用

利用java反射机制减少Servlet的个数
编写一个BaseServlet继承HTTPServlet,这是一个通用的Servlet,代码如下:

public class BaseServlet extends HttpServlet{
        //设置字符集
        request.setCharacterEncoding("utf-8");
        doPost(request , response);
    }
    public void doPost(HttpServletRequest request , HttpServletResponse response){
        //设置字符集
        request.setCharacterEncoding("utf-8");
        //接受jap传递的方法名
        String handler = request.getParameter("handler");
        //根据java反射机制通过方法名获取方法
        Method method = this.getDeclaredMethod(handler,HttpServletRequest.class , HttpServletResponse.class);
        //执行此方法
        method.invoke(this,request,response);

    }

}

JSP部分代码如下:

<div align="center">
        <h1>增加学生信息h1>
        <hr>
        
        <form action="stu.dos?handler=add" method="post">
            <table>
                <tr>
                    <td>学号td><td><input type="text" name="stuNo">td>
                tr>
                <tr>
                    <td>姓名td><td><input type="text" name="stuName">td>
                tr>
                <tr>
                    <td>性别td><td><input type="radio" name="gender" value="M"><input type="radio" name="gender" value="F">td>
                tr>
                <tr>
                    <td>电话td><td><input type="text" name="tel">td>
                tr>
                <tr>
                    <td>年龄td><td><input type="text" name="age">td>
                tr>
                <tr>
                    <td>分数td><td><input type="text" name="score">td>
                tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" value="提交">td>
                tr>

            table>
        form>
    div>

再写一个StuServlet继承BaseServlet,代码如下:

public class StuServlet extends BaseServlet{
    public void add(HttpServletRequest request , HttpServletResponse response){

        //通过BaseServlet中的doPost方法即可调用此add方法
        //以此类推,此Servlet中可写增删改查等方法
        System.out.println("添加学生信息");
    }
}

你可能感兴趣的:(java)