如何将response.sendRedirect添加到我的控制器

时间:2017-11-06 14:27:27

标签: java servlets

我已经编写了我的控制器来转发所有请求,这几乎适用于我想要采取的所有操作,但我可能需要使用response.sendRedirect成功登录而不是转发它来尝试实现Tomcat的CSRF预防过滤器。

我已经尝试添加我认为正确的代码,但我一直都会遇到错误,任何人都可以告诉我这是否可行,以及最佳行动是什么。

我当前的控制器登录方法是(没有错误代码)

public void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {
    String requestURI = request.getRequestURI();
    String url = "";
    // Register a new user
    if (requestURI.endsWith("/subscribeToSite")) {
        url = subscribeToSite(request, response);
    }
    // Login
    if(requestURI.endsWith("/logintosite")){
        url = logintosite(request, response);
    }
   //Change AC password
    if(requestURI.endsWith("/changePwd")){
        url = changePassword(request, response);
    }

    getServletContext()
            .getRequestDispatcher(url)
            .forward(request, response);
}

private String logintosite(HttpServletRequest request,
        HttpServletResponse response) {

    String url;        
    String message;
    // get values from form
    String pNum = request.getParameter("phoneNumber");
    String upwd = request.getParameter("password");

    //validate the values to check for empty values in case JS registration check has failed.
    if(pNum.length()==0 ||upwd.length()==0){
        message="You have not filled out the required fields.";
        request.setAttribute("message", message);
        url = "/login.jsp";
        return url;
    }
    //Format the phone number
    String mPNum=UserDB.formatPhoneNumber(pNum);
    //try to  login
    User user = UserDB.loginUser(mPNum, upwd);
    if(user==null){
        url = "/loginerror.jsp";
    }else{
           //HttpSession session = request.getSession();
            HttpSession session = request.getSession();
            session.invalidate();
            session=request.getSession(true);
            session.setAttribute("loggedUsrID", user.getUserID());
            session.setAttribute("loggedUsrFName", user.getFName());
           url="/sched/welcome.jsp";

    }      
    return url;
}//EO user login
}

我需要做的是使用response.sendRedirect(/sched/welcome.jsp),而不是仅为此方法发送URL,因为控制器中的其他方法只能正常使用。

0 个答案:

没有答案