配置web.xml里面的servlet的三种方式

发布于:2021-10-17 11:07:57

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

String serlvetPath = req.getServletPath();
String methodName = serlvetPath.substring(serlvetPath.lastIndexOf("/") + 1);
try {
Method method = this.getClass().getDeclaredMethod(methodName,
new Class[] { HttpServletRequest.class, HttpServletResponse.class });
if (method != null) {
method.invoke(this, req, resp);
}
} catch (Exception e) {
e.printStackTrace();
}

}
//后面写具体方法 便可自动识别并执行

/*web.xml中 必须严格按照方法初始化配置*/


StoreUserServlet
com.sts.servlet.StoreUserServlet


StoreUserServlet
/StoreUserServlet/login
/StoreUserServlet/regist


?


方法二


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取method值,
String methodName = request.getParameter("method");


if ("registUI".equals(methodName)) {

registUI(request, response);

}else if ("loginUI".equals(methodName)) {

loginUI(request, response);

}else if ("regist".equals(methodName)) {

regist(request, response);

}else if ("active".equals(methodName)) {

active(request, response);

}else if ("login".equals(methodName)) {

login(request, response);

}else if ("homepage".equals(methodName)) {

homepage(request, response);
}else if ("myfile".equals(methodName)) {

myfile(request, response);
}

}

该方法需要在请求Servlet时指明method


  • 通知

  • 同时web.xml里面配置servlet只需要如下即可



    NoticeServlet
    com.itheima.web.servlet.NoticeServlet


    NoticeServlet
    /notice

    方法三:


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestURI = req.getRequestURI();
    System.out.println(requestURI);

    if (requestURI.endsWith(Protocol.reg_user)) {
    this.registerUser(req, resp);
    } else if (requestURI.endsWith(Protocol.login_user)) {
    this.loginUser(req, resp);

    }
    }

    web.xml如下




    student
    /student/*



    user
    /user/register
    /user/login



    valid
    /valid

    ?

    相关推荐

    最新更新

    猜你喜欢