简体   繁体   中英

What is JSP equivalent of PHP's $_server

This question might sound similar to

JSP or JavaScript equivalent to PHP's $_SERVER["HTTP_HOST"]?

But the answers to that questions are only about finding out HTTP_HOST.

I am wondering if it is possible to create Sever-wide global variables in JSP.

Example:

User 1 computes some user independent function X. It is likely that other users too might visit the application to compute X. One way would be I can save it in mySQL and for subsequent user requests do a db lookup. But I dont want to use any DB and my data should persist only during the lifetime of the server.

In PHP I could simple set $_SERVER['x]=value;

I was wondering if similar thing can be achieved in JSP.

The short answer is that you can use what is called Application Scope. This scope will persist since the application deployment until the container is stopped or the application redeployed.

In Servlets you can use it like this :

ServletContext context = request.getSession().getServletContext();
String value = "test";

// Set value in application scope
context.setAttribute("x",value);

// Get value from application scope
value = (String)context.getAttribute("x");

In Scriplets you can use it like this (using them is a bad practice ) :

// Set value in application scope
application.setAttribute("x",value);

// Get value from application scope
value = (String)application.getAttribute("x");

In EL you can retrive value like this :

${applicationScope['x']}

Comming from a PHP world you will have to know that in that example I've used String object, but you can use any object. You can't use primitive data types.

Not related :

  • If you are working on a new project, you should consider moving to JSF 2.X, JSP is deprecated since 2009.
  • Read some Java EE tutorials

It is HttpServletRequest Interface on - javax.servlet.http.HttpServletRequest

This has most methods. Please check this link and let know if you have any questions.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getHeader%28java.lang.String%29

Thanks.

我认为最简单的方法是使用任何类的静态成员。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM