下面我们来解释为什么Struts1是线程不安全的。1、Struts1Struts1是对Java web servlet接口的直接实现,所以它继承了tomcat对servlet的实现,每一个struts1里面的action都对应的是一个servlet class,所以这里的action在被tomcat实例化之后也是单例的,所以,struts1就产生了多线程问题。例如:你在Action定义了一个 int i = 0;然后在这个Action里面的某一个方法里面对这个i进行操作。向下面代码这样:[java] view plaincopy package web.servlet;
/** * @author Jack Zhang * @version vb1.0 * @Email [email protected] * @Date 2013-4-21 */ public class ServletTest1 extends HttpServlet {
public int i = 0; /** * Constructor of the object. */ public ServletTest1() { super(); }
/** * 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 { i++;
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(" i="+i); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } } 当访问这个servlet的时候,你访问多少次,I的值就是多少。所以:我们在用struts1的时候不能在action里面定义属性。要用到只的话只能在方法里面定义。那至于为什么把属性的定义放到方法里面就不会有多线程的问题了,这个问题希望各位读者去查看有关JMM(java memory model)里面有关java内存模式如何给方法分配内存的内容, 我相信你们会找到答案。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Jack Zhang
* @version vb1.0
* @Email [email protected]
* @Date 2013-4-21
*/
public class ServletTest1 extends HttpServlet
{
public int i = 0;
/**
* Constructor of the object.
*/
public ServletTest1()
{
super();
}
/**
* 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
{
i++;
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(" i="+i);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
当访问这个servlet的时候,你访问多少次,I的值就是多少。所以:我们在用struts1的时候不能在action里面定义属性。要用到只的话只能在方法里面定义。那至于为什么把属性的定义放到方法里面就不会有多线程的问题了,这个问题希望各位读者去查看有关JMM(java memory model)里面有关java内存模式如何给方法分配内存的内容, 我相信你们会找到答案。