1.新建一个Dynamic Web Project项目,里面新建一个servlet,新建一个jsp,整体的框架结构如下所示:
2.getLengthOrAreaServlet.java文件的代码如下所示:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/getLengthOrAreaServlet")
public class getLengthOrAreaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
String l = request.getParameter("length");
String w = request.getParameter("width");
out.println("<html><body>");
double m = 0;
double n = 0;
try {
m = Double.parseDouble(l);
n = Double.parseDouble(w);
out.println("矩形的周长是:" + (m + n) * 2);
} catch (NumberFormatException e) {
out.println("请输入数字字符!");
}
out.println("</html></body>");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
String l = request.getParameter("length");
String w = request.getParameter("width");
out.println("<html><body>");
double m = 0;
double n = 0;
try {
m = Double.parseDouble(l);
n = Double.parseDouble(w);
out.println("矩形的面积是:" + m * n);
} catch (NumberFormatException e) {
out.println("请输入数字字符!");
}
out.println("</html></body>");
}
}
3.login.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>login.jsp</title>
</head>
<body>
<h2>输入矩形的长和宽,提交给servlet(post方式)求面积:</h2>
<form action="getLengthOrAreaServlet" method="get">
长:<input type="text" name="length"/><br>
宽:<input type="text" name="width"/><br>
<input type="submit" value="提交"/>
</form>
<h2>输入矩形的长和宽,提交给servlet(get方式)求周长:</h2>
<form action="getLengthOrAreaServlet" method="post">
长:<input type="text" name="length"/><br>
宽:<input type="text" name="width"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
4.在浏览器里面输入http://localhost:8080/Servlet/login.jsp运行之后得到的结果如下所示: