jsp和Servlet的分工:
* JSP:
> 作为请求发起页面,例如显示表单、超链接。
> 作为请求结束页面,例如显示数据。
* Servlet:
> 作为请求中处理数据的环节。
来看一张图:
下边显示一个小Demo,在一个jsp页面中输入两个参数,在另一个页面中将两者相加的结果显示。
AServlet.java
package com.ywq;
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 AServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从form.jsp页面获取参数
String num1=request.getParameter("num1");
String num2=request.getParameter("num2");
//参数类型转换
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int sum=a+b;
//将运算结果保存在request域中
request.setAttribute("result", sum);
//请求转发,使转换到显示结果页面。
RequestDispatcher rd=request.getRequestDispatcher("/add/result.jsp");
rd.forward(request, response);
}
}
form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>这个页面用来输入两个参数</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="/day11_1/AServlet" method="post">
加数1:<input type="text" name="num1"/><br>
加数2:<input type="text" name="num2"/><br>
<input type="submit" value="运算">
</form>
</body>
</html>
result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>运算结果显示页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
Integer sum=(Integer)request.getAttribute("result");
%>
<%=sum %>
</body>
</html>
将Project部署到Tomcat中,启动服务器,在浏览器中输入http://localhost:8080/day11_1/add/form.jsp,则出现下图所示:
输入两个参数,点击按钮,则出现如下所示:
项目工程截图如下: