Servlet搬砖笔记—反射机制的妙用

最近弄点小东西,由于客户需求,必须用servlet+jsp,知道这个消息我是拒绝的,但砖还要搬


逻辑理好后,如果按一般的servlet的写法,代码会显得异常的臃肿,百度了一下,单Servlet的写法(不怎么玩Servlet,这方式早就有了)


实在是经典!!! 近一年的工作中越来越喜欢 泛型和反射。


下面简单的说一下我项目中如何运用的,以登陆为例


首先是 login.jsp,这里话只截取了部分代码

    <form id="loginForm" action="<%=basePath%>/login?method=userLogin&&callback=<%=callback%>" 
                	class="form_box" method="post" role="form">
                    <div class="form-group">
                        <label for="username" style="color:white;">用户名</label>
                        <input type="text" class="form-control" name="username"
                               placeholder="用户名由6~12的英文数字组合,第一位必须为字母">
                    </div>
                    <div class="form-group">
                        <label for="password" style="color:white;">密码</label>
                        <input type="password" class="form-control" name="password"
                               placeholder="密码由6~12的英文数字组合">
                    </div>
                    <div class="form-group">
                    	<h3 id="errorMsg" class="text-danger text-center"><c:out value="${errorMsg}"/></h3>
                    </div>
                    <div class="form-group">
                        <input type="submit" class="btn btn-primary btn-lg btn-block" value="登录"/>
                        <input type="reset" class="btn btn-info btn-lg btn-block" value="重置"/>
                    </div>
                </form>

我传递了一个参数  method=userLogin


接下来看Servlet

这里我定义了一个 BaseHttpServlet 作为基类

BaseHttpServlet.java

package com.slv.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseHttpServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		execute(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		execute(req, resp);
	}

	
	/**利用反射查找方法
	 * */
	public void execute(HttpServletRequest req, HttpServletResponse resp) {
		//userLogin
		String methodName = req.getParameter("method");
		try {
			Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
					HttpServletResponse.class);
			method.invoke(this, req, resp);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 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();
		}
	}
	
	
	/**
	 * 设置页面调转
	 * */
	protected void goTo(String url,HttpServletRequest req,HttpServletResponse resp){
		try {
			req.getRequestDispatcher(url+".jsp").forward(req, resp);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 重定向
	 * */
	protected void redirect(String url,HttpServletRequest req,HttpServletResponse resp){
		try {
			resp.sendRedirect(req.getContextPath()+url+".jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	


}

可以看到不管是Get 或者Post方法,最终我都会执行 exeute方法

Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
					HttpServletResponse.class);
method.invoke(this, req, resp);

反射的妙用  通过方法名和参数直接获取到 Method 对象 然后  调用  invoke 方法 运行,关于反射机制的学习,我是在慕课网看的,感兴趣的同学自行学习

好了接下来在我的 LoginServlet.java(继承了BaseHttpServlet.java)中定义了登陆的方法

/**
	 * 用户登陆
	 * @throws IOException 
	 * */
	public void userLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException{//.......细节就不展开了}

这样的话我们只用在对应的Servlet中取添加方法就行,不用创建多个Servlet,有种Spring MVC controller的感觉(还是框架好)


以上为本次Servlet的搬砖总结


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值