1、编写一个长方形类,属性有长和宽;方法有计算并返回周长,计算并返回面积。
2、编写一个Servlet,接收长和宽,创建一个长方形对象,给这个对象的长和宽赋值。调用该对象的两个计算方法,并将计算结果保存在session中,最后跳转到显示页面。
3、编写表单页面,显示一个表单,用于输入长方形的长和宽,数据提交给Servlet。
4、编写显示页面,从session中取出周长和面积,并显示
V层 视图层,界面 jsp
C层 控制层 传数据和跳转 servlet
M层 模型层 处理数据 JavaBean
servlet:接受数据保存结果跳转
JavaBean:计算
JavaBean功能函数截图:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="js.do" method="post">
长<input type="text" name="n1"><br>
宽<input type="text" name="n2"><br>
<input type="submit" value="计算">
</form>
</body>
</html>
src包下创建CFX.java
package aa;
public class CFX {
//根据分析,长方形有二个属性(长、宽),二个方法(计算周长,计算面积)
private int chang ;
private int kuan ;
public int jsZhou() {
return (chang+kuan )*2;
}
public int jsMian() {
return chang * kuan ;
}
//在source(源码)中生成getter setter
public int getChang() {
return chang;
}
public void setChang(int chang) {
this.chang = chang;
}
public int getKuan() {
return kuan;
}
public void setKuan(int kuan) {
this.kuan = kuan;
}
}
servlet处理代码
Myservlet.java
package aa;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Myservlet extends HttpServlet {
@Override//重写
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受表单传过来的长和宽
String s1 = req.getParameter("n1");
String s2 = req.getParameter("n2");
//2.字符串转数字
int w1 = Integer.parseInt(s1);
int w2 = Integer.parseInt(s2);
//3.因为我自己不能处理数据,所以将长和宽交给M层去处理
CFX c1 = new CFX();
c1.setChang(w1);
c1.setKuan(w2);
//4.从M层获取处理结果
int zhou = c1.jsZhou();
int mian = c1.jsMian();
//5.因为C层不能显示结果,所以保存结果
req.getSession().setAttribute("qqq",zhou);
req.getSession().setAttribute("hhh",mian);
//6.跳转显示页面结果
resp.sendRedirect("c.jsp");
}
}
Servlet地址配置代码
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JSPDemo1</display-name>
<servlet>
<servlet-name>mm</servlet-name>
<servlet-class>aa.Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mm</servlet-name>
<url-pattern>/js.do</url-pattern>//配置地址
</servlet-mapping>
</web-app>