java - 在我的 servlet 中使用 this.variable 访问全局变量的目的是什么?

标签 java jsp oop servlets

这是示例 servlet

public class XYZServlet extends HttpServlet {
 public static final long serialVersionUID = 1L;    
 protected long a = -1;
 protected String str = null;
 protected responseJSON = null;

 public XYZServlet() {
   super();
 }

 protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    //initialization of global variables goes here
    this.a = request.getParameter("serial_number");
    this.str = this.utilMethod();

    //and the rest of the code goes here
    PrintWriter pout = new PrintWriter();
    pout.write("Success!");
 }

 protected String utilMethod () {

    //this returns some string after executiion
 }
}
  1. What advantage we have on declaring the variables as protected here rather than public?
  2. What is the purpose of accessing the variables with this.variable across the servlet?
  3. What is the purpose of creating a non-parameterized constructor invoking parent constructor from it? Is there any specific reason or structural logic behind this?

因为当 servlet 由 Web 服务器初始化时,它会使用默认构造函数进行初始化,该默认构造函数通过调用 super() 来调用其父构造函数(默认情况下与上面所示类似)。

4.Is there any better way to initialize these global variables in the above servlet?

上面 servlet 中的全局变量包含类似的值

  • 请求参数值和

  • 来自此 servlet 内的 util 方法的值

最佳答案

正如已经评论过的,在 servlet 中使用字段是完全错误的;并发访问、servlet 重用等。

一种重用的解决方案是提供一个可以在 servlet 中重用的简单 POJO(普通旧 java 对象)。该对象可以具有这些字段,并在 doPost/doGet 上创建。

<小时/>
class Util {
    long a = -1;
    String str = null;
    responseJSON = null;

    String someMethod();
}

protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    //initialization of pojo goes here
    Util pojo = new Util();
    pojo .a = request.getParameter("serial_number");
    pojo .str = this.utilMethod();
    .... pojo.someMethod();

     //and the rest of the code goes here
     PrintWriter pout = new PrintWriter();
     pout.write("Success!");
 }

 protected String utilMethod () {

     //this returns some string after executiion
 }

关于java - 在我的 servlet 中使用 this.variable 访问全局变量的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590948/

相关文章:

java - 用户注册与电子邮件验证

javascript - 从对象返回函数会破坏 instanceof

c# - 隐藏在 c# 中的方法以及一个有效的例子。为什么在框架中实现?什么是现实世界的优势?

java - 需要创建一个只能从 G 实例化的 A 类

java - catalina.bat 开始不工作

java - MySQLIntegrityConstraintViolationException : Column 'Firstname' cannot be null

java - 如何从 Java 中的文本文件中读取逗号分隔值?

java - 如何在jSTL jsp中调用方法

java - 内存不足错误时的 Elastic Beanstalk 行为

java - 无法将 CSS 文件链接到 JSP