gpt4 book ai didi

java - 线程安全的 java servlet

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:40 26 4
gpt4 key购买 nike

就线程而言,我需要知道以下代码是否存在任何问题。我一直认为只要不使用类级变量,线程就不是问题。

public class UploadReferralImage extends HttpServlet
{
String CLASS_NAME = "UploadReferralImage";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Not handling Get, service must be invoked via Post.
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String METHOD_NAME = "doPost";
LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Made it to the servlet");
String reply = upload(request);
response.setHeader("Content-Type", "text/xml");
response.getWriter().write(reply);
response.getWriter().flush();
response.getWriter().close();
}

public String upload(HttpServletRequest request)
{

String METHOD_NAME = "upload";
LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Inside upload");
String replyMsg = "Unable to call ImageUpload";

try
{
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
FileBean fBean = (FileBean) inputFromApplet.readObject();

inputFromApplet.close();
LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, fBean.getFileName());

replyMsg = doImageUpload(fBean);

}
catch (IOException e)
{
e.printStackTrace();
replyMsg = "Exception :" + e.toString();

}
catch (ClassNotFoundException e)
{
e.printStackTrace();
replyMsg = "Exception :" + e.toString();
}

return replyMsg;
}

private String doImageUpload(FileBean fBean)
{
//Save the file and return the response
SaveCaseClientAgent saveCaseClientAgent = new SaveCaseClientAgent();
saveCaseClientAgent.save(fBean);
}

最佳答案

你是对的。

只要您不使用类级变量,您的 Servlet 就会是线程安全的。

为了安全起见,不妨让你的类级 String final:

final String CLASS_NAME = "UploadReferralImage";

关于java - 线程安全的 java servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com