这次把MVC模型的Control分割出来,利用JSP(V)+Servlet(C)+JavaBean(M) 重构上篇的计算器:
JavaBean依然采用上篇的
JSP代码:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<!-- V -->
<jsp:useBean id="cb" class="cn.itcast.web.jsp.CalBean" scope="request"/>
<jsp:getProperty name="cb" property="firstNum"/>
<jsp:getProperty name="cb" property="operator"/>
<jsp:getProperty name="cb" property="secondNum"/>
=
<jsp:getProperty name="cb" property="result"/>
<hr/>
<!-- V -->
<form action="/day10/CalServlet" method="post">
<table border="1" align="center">
<caption>间单计算器</caption>
<tr>
<th>第一个参数:</th>
<td><input
type="text"
name="firstNum"
value='<jsp:getProperty name="cb" property="firstNum"/>'/></td>
</tr>
<tr>
<th>运算符</th>
<td>
<select name="operator">
<option value="-">-</option>
<option value="+" selected>+</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<th>第二个参数:</th>
<td><input
type="text"
name="secondNum"
value='<jsp:getProperty name="cb" property="secondNum"/>'/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input style="width:200px" type="submit" value="计算"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Servlet设计:
import java.io.Exception;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
public class CalServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
Enumeration<String> enums = request.getParameterNames();
CalBean cb = new CalBean();
while(enums.hasMoreElements()){
String key = enums.nextElement();
String[] values = request.getParameterValues(key);
try {
BeanUtils.setProperty(cb,key,values);
} catch (Exception e) {
e.printStackTrace();
}
}
cb.cal();
request.setAttribute("cb",cb);
request.getRequestDispatcher("/cal_2.jsp").forward(request,response);
}
}