更改printwrite的位置(Servlet)

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=utf-8");
        request.setCharacterEncoding("utf-8");
//        ServletContext context= this.getServletContext();
        String name = request.getParameter("username");
        String password =request.getParameter("password");
        String sex =request.getParameter("sex");


        if (name.equals("admin") && password.equals("123456")){
            request.getRequestDispatcher("/success.html").forward(request,response);
        }else {
            PrintWriter out = response.getWriter();


            out.println("用户名:" + name+"<br>");
            out.println("密码:" + password+"<br>" );
            out.println("性别:" + sex+"<br>");

            String [] hobbys = request.getParameterValues("hobby");
            out.println("爱好:");
            for (int i =0; i<hobbys.length;i++) {
                out.println(hobbys[i]+" ");
            }

            out.println("用户名或密码输入有误...3秒后将自动跳转 <br>");
            response.setHeader("Refresh","3;URL=/error.html");
        }
        }

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

    }
}

NOTE:该乱码原因是因为Print Write不能在forward转发之前,否则会影响下方的forward。
故我将Print Write放在了判断forward后面,先判断forward,如果正确那就没下面什么事了。
反之如果错误,forward并不会影响PrintWrite,且也没有forward什么事情。
此处解决的问题是跳转不到success页面,会卡在Login Servlet页面。