importjava.io.*;importjava.util.*;importjavax.servlet.*;importjavax.servlet.http.*;/***点击开始仿真时SimulationServlet类从浏览器获得一个POST请求*InresponsetoaPOSTrequest,...
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* 点击开始仿真时SimulationServlet类从浏览器获得一个POST请求
*In response to a POST request,
* the SimulationServlet object creates living being objects and sends an HTML *representation of the lake to the browser.
* @author 张
*/
public class SimulationServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* Total time blocks to simulate */
int totalTimeBlocksToSimulate = 0;
/* Create a session,a object of HttpSession */
HttpSession session = request.getSession();
/**
* 内容格式 (如, text/html),
* 通过响应返回
*/
response.setContentType("text/html");//设置输出格式
/* 收到输出流用于将数据发送到客户端 */
PrintWriter out = response.getWriter();
/* 从form中收到用户输入信息 */
String numTimeBlocks = request.getParameter("numTimeBlocks");
/* 创建 Simulation 对象 */
Simulation simulation;
/* 建立HTML响应 : 从header开始 */
if(numTimeBlocks != null) {
totalTimeBlocksToSimulate = Integer.parseInt(numTimeBlocks);
simulation = new Simulation(0, 0, 9, 9);
Map allParams = request.getParameterMap();
Set allKeys = allParams.keySet();
for(Iterator it = allKeys.iterator(); it.hasNext();) {
String key = (String)it.next();
if(!key.equals("Submit") && !key.equals("numTimeBlocks")) {
String value[] = (String[])allParams.get(key);
for(int i = 0; i < value.length; i++)
LivingBeing.createLivingBeing(simulation, key, value[i]);
}
}
if(totalTimeBlocksToSimulate > 0)
response.setHeader("Refresh", "1");
out.print(SimulationView.getHtml(simulation));
session.setAttribute("simulation", simulation);
session.setAttribute("totalTimeBlocksToSimulate", numTimeBlocks);
}
simulation = (Simulation)session.getAttribute("simulation");
String totalTimeBlocksInSession = (String)session.getAttribute("totalTimeBlocksToSimulate");
if(totalTimeBlocksInSession != null)
totalTimeBlocksToSimulate = Integer.parseInt(totalTimeBlocksInSession);
if(simulation.getTime() < totalTimeBlocksToSimulate - 1)
response.setHeader("Refresh", "1");
simulation.simulateATimeBlock();
out.print(SimulationView.getHtml(simulation));
}
}
展开