

1 package cn.itcast.response; 2 3 import java.io.IOException; 4 import java.util.Random; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class ResponseDemo extends HttpServlet { 12 13 public void doGet(HttpServletRequest request, HttpServletResponse response) 14 throws ServletException, IOException { 15 16 //实现的自动跳转技术 17 String message = "<meta http-equiv='refresh' content='3;url=http://localhost:8080/ServletDemo/index.jsp'>恭喜你,登录成功,奔浏览器将在3秒后,跳到首页,如果没有跳,请点击<a href=''>超链接</a>"; 18 19 this.getServletContext().setAttribute("message", message); 20 this.getServletContext().getRequestDispatcher("/MyJsp.jsp").forward(request, response); 21 22 } 23 24 25 26 private void test2(HttpServletResponse response) throws IOException { 27 // 假设这是一个用于处理登录的Servlet 28 29 // 假设程序运行到此,用户登录成功 30 response.setCharacterEncoding("UTF-8"); 31 response.setContentType("text/html;charset=UTF-8"); 32 33 response.setHeader("refresh", 34 "3;url='http://localhost:8080/ServletDemo/index.jsp'"); 35 response.getWriter().write( 36 "恭喜你,登录成功,奔浏览器将在3秒后,跳到首页,如果没有跳,请点击<a href=''>超链接</a>"); 37 38 } 39 40 private void test1(HttpServletResponse response) throws IOException { 41 response.setHeader("refresh", "3"); 42 43 String data = new Random().nextInt(100000) + ""; 44 response.getWriter().write(data); 45 } 46 47 public void doPost(HttpServletRequest request, HttpServletResponse response) 48 throws ServletException, IOException { 49 50 } 51 52 }


1 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'MyJsp.jsp' starting page</title> 13 14 15 </head> 16 17 <body> 18 <% 19 String message = (String)application.getAttribute("message"); 20 out.write(message); 21 %> 22 </body> 23 </html>