如何更改任意java类中会话变量的值
我有一个Javaservlet,它设置一个会话变量并调用一个启动一个线程类如何更改任意java类中会话变量的值,java,servlets,session-variables,Java,Servlets,Session Variables,我有一个Javaservlet,它设置一个会话变量并调用一个启动一个线程类 @WebServlet("/ExportLogs") public class ExportLogs extends HttpServlet { public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException,IOException { Integer
@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException,IOException
{
Integer completePercent = new Integer(10);
request.getSession().setAttribute("CompletionStatus" , completePercent);
LogExportingProcess export = new LogExportingProcess();
export.start();
}
}
我有一个thread类,它执行一个长过程,如下所示:
class LogExportingProcess extends Thread
{
public void run()
{
//i want to change the value of the percent complete variable in here.
}
}
现在我想更改LogExportingProcess类中completePercent值的值。如何实现它。在创建
LogExportingProcess时,您必须传递会话
对象
class LogExportingProcess extends Thread
{
private HttpSession session;
public LogExportingProcess(HttpSession session) {
this.session = session;
}
public void run()
{
session.setAttribute("CompletionStatus" , completePercent);
}
}
以及ExportLogs
类中的一个更改
LogExportingProcess export = new LogExportingProcess(request.getSession());
整数是不可变的。原子整数将是一个很好的替代品
@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
public void doGet( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException,IOException
{
final AtomicInteger completePercent = new AtomicInteger(10);
request.getSession().setAttribute("CompletionStatus" , completePercent);
final LogExportingProcess export = new LogExportingProcess( completePercent );
export.start();
}
}
class LogExportingProcess extends Thread
{
final AtomicInteger completePercent;
public LogExportingProcess( final AtomicInteger completePercent )
{
this.completePercent = completePercent;
}
public void run()
{
completePercent.set( 80 ); //80% complete, substitute with real code
}
}
正如Yogesh Badke所建议的那样,这比保留对HttpSession对象的引用更可取,因为HttpSession可以在超时时正常进行垃圾收集,AtomicInteger通过只共享一个百分比而不是整个会话信息来增加封装。,会话可能同时已关闭,这可能导致已关闭会话上出现意外的属性设置。我建议使用存储在会话中的中间对象,该对象将包含异步线程可以更改的所有属性。@Yogesh Badke非常感谢我所希望的be@Serge巴列斯塔谢谢你的建议我会做的我会回应塞尔日·巴列斯塔所说的。我有一个下面的答案,它结合了约格什·巴德克的建议和谢尔盖·巴列斯塔的建议,使用了原子整数。