您的位置:首页 > 编程语言 > Java开发

java web之中,如果Servlet中有耗时较长的计算,该怎么做才好?

2016-03-17 23:28 513 查看
java web之中,如果Servlet中有耗时较长的计算,该怎么做才好?

下面用Thread.sleep(5000)来模拟耗时较长的计算:

public class calcServlet extends HttpServlet {

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

String numa = req.getParameter("numa");
String numb = req.getParameter("numb");
int iNuma=Integer.parseInt(numa);
int iNumb=Integer.parseInt(numb);
int calcResult=calc(iNuma,iNumb);

String strCalcResult=String.valueOf(calcResult);
req.setAttribute("calcResult", strCalcResult);

req.getRequestDispatcher("/showCalcResult.jsp").forward(req, res);
}

private int calc(int iNuma, int iNumb) {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return iNuma+iNumb;
}
/*
public native int calc(int iNuma, int iNumb);
static{
System.out.println(System.getProperty("java.library.path"));
System.out.print("start load!!!");
System.loadLibrary("calc");
System.out.print("end load!!!");
}
*/
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: