目录
一.结果图
二.结构图
(在WebContent目录下创建jsp)
三.代码
1.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form action="dugeServlet" method="post">
<input type="text" name="sum1">
+
<input type="text" name="sum2">
<br>
<input type="submit" value="add">
</form>
</div>
</body>
</html>
2.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%----
String num1=request.getParameter("sum1");
String num2=request.getParameter("sum2");
int result=Integer.parseInt(num1)+Integer.parseInt(num2);
-----%>
<%
int i=(Integer)request.getAttribute("res");
%>
<%=i%>
</body>
</html>
3.Servlet
Servlet:是用Java编写的服务器端程序,其主要功能在于交互式的浏览和修改数据,生成动态Web内容;
狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class dugeServlet
*/
@WebServlet("/dugeServlet")
public class dugeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public dugeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String num1=request.getParameter("sum1");
String num2=request.getParameter("sum2");
int result=Integer.parseInt(num1)+Integer.parseInt(num2);
request.setAttribute("res", result);
//3.页面跳转
RequestDispatcher d=request.getRequestDispatcher("/sad.jsp");
d.forward(request,response);
}
}