Servlet 方法
1.设置字符编码,避免中文乱码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置字符编码,避免中文乱码 response.setContentType("text/html;Charset=utf-8"); PrintWriter out = response.getWriter(); out.println("你好!!!");//写到浏览器 }
2.网页重定向:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 网页重定向 // 设置响应内容类型 response.setContentType("text/html"); // 要重定向的新位置 String site = "http://www.baidu.com"; response.setStatus(response.SC_MOVED_PERMANENTLY);// SC_MOVED_TEMPORARILY response.setHeader("Location", site); }
3.转发:转发的文件根目录是此web项目的根目录。
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { getServletContext().getRequestDispatcher("/success.html").forward(request, response); }
转发与重定向区别:转发浏览器只访问一次服务器:最初的那次请求,重定向访问两次服务器:最初的一次,重定向的那次。
4.延时,自动刷新:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 自动跳转,可以延时,自动刷新 response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setHeader("refresh", "3;http://www.baidu.com"); }
5.包含相应web页面:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //把header.html页面的执行结果包含 req.getRequestDispatcher("/header.html").include(req, resp); //不能使用打印字符流 //PrintWriter out = resp.getWriter(); //out.println("include servet body....."); OutputStream os = resp.getOutputStream(); os.write("include servet body.....".getBytes()); req.getRequestDispatcher("/footer.html").include(req, resp); }