1、sendForward.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Verify" method="post">
请输入一个实数:<input type="text" name="number">
<input type="submit" value="确定">
</form>
</body>
</html>
如图所示:
2、servlet类:Verify.java
package servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Verify extends HttpServlet { public Verify() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String number=request.getParameter("number");
double n=Double.parseDouble(number); //上面是String,把String类型转为double类型
if(n>6000||n<-6000){
response.sendRedirect("sendForward.jsp");
}else{
//转发到另一个servlet文件
request.getRequestDispatcher("ShowMessage").forward(request, response); }
} public void init() throws ServletException { } }
两种重定向方式:
(1)重定向: response.sendRedirect("sendForward.jsp");
(2)请求转发:request.getRequestDispatcher("ShowMessage").forward(request, response);
3、servlet类:ShowMessage.java
package servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ShowMessage extends HttpServlet { public ShowMessage() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter(); String number=request.getParameter("number");
double n=Double.parseDouble(number);
out.println(number+"的平方:"+(n*n));
} public void init() throws ServletException {
} }