BaseServlet

在访问servlet的时候,如果不想每一次都去写doget()和dopost()方法,我们可以写一个基础类,然后servlet可以继承这个基础类,然后去做相应的操作。

  1. import java.io.IOException;  
  2. import java.lang.reflect.Method;  
  3. import javax.servlet.ServletException;  
  4. import javax.servlet.annotation.WebServlet;  
  5. import javax.servlet.http.HttpServlet;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. /** 
  10.  * Servlet implementation class BaseServlet 
  11.  */  
  12. @WebServlet("/BaseServlet")  
  13. public class BaseServlet extends HttpServlet {  
  14.     private static final long serialVersionUID = 1L;  
  15.   
  16.     @Override  
  17.     public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  18.         response.setContentType("text/html;charset=UTF-8");// 处理响应编码  
  19.         request.setCharacterEncoding("UTF-8");  
  20.         // 1. 获取method参数,它是用户想调用的方法  
  21.         String methodName = request.getParameter("method");  
  22.         Method method = null;  
  23.         // 2. 通过方法名称获取Method类的实例对象  
  24.         try {  
  25.             method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);  
  26.         } catch (Exception e) {  
  27.             throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", e);  
  28.         }  
  29.         // 3. 通过method对象的invoke()方法来调用它  
  30.         try {  
  31.             method.invoke(this, request, response);  
  32.         } catch (Exception e) {  
  33.             throw new RuntimeException(e);  
  34.         }  
  35.     }  

操作子类:

mport java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.user.service.UserService;
import cn.itcast.utils.BaseServlet;
public class UserServlet extends BaseServlet {
 private UserService service = new UserService();
 public void login(HttpServletRequest req, HttpServletResponse resp)
      throws Exception{
  //接收信息,实现登录
  String name = req.getParameter("name");
  String pwd = req.getParameter("pwd");
  User u = new User(name,null,pwd);
  //调用查询
  u = service.login(u);
  if(u==null){
   System.err.println("登录不成功.");
   resp.sendRedirect(req.getContextPath()+"/index.jsp?error=1");
  }else{
   req.getSession().setAttribute("user", u);
   //重定向
   resp.sendRedirect(req.getContextPath()+"/servlet/MainServlet");
  }
  
 }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值