- What is session in Java? [duplicate]
- What is session in Java? [duplicate]
- In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
- What is the important of the use of codeigniter database session (ci_session)
- Сессии(Session) в Java
- Http Session Interface
- index.html
- Servlet1.java
- Servlet2.java
- web.xml
What is session in Java? [duplicate]
In java servlets, HTTP sessions are tracked using two mechanisms, HTTP cookie (the most commonly used) or URL rewriting (to support browsers without cookies or with cookies disabled). There is a single HTTP session by visit , as Java session cookies are not stored permanently in the browser.
What is session in Java? [duplicate]
So far I understand Httpsession concepts in Java.
HttpSession ses = req.getSession(true);
will create a session object, according to the request.
setAttribute("String", object);
will, bind the ‘String’, and value with the Session object.
will return an object associated with the string, specified.
What I am not able to understand is: I am creating a session object like HttpSession ses = req.getSession(true); and setting a name for it by calling setAttribute(«String», object); . Here, This code resides inside the server. For every person, when he tries to login the same code in the server will be executed. setAttribute(«String», object); in this method the string value is a constant one. So, each session object created will be binded by the same string which I have provided. When I try to retrieve the string to validate his session or while logout action taken the getAttribute(«String»); ll return the same constant string value(Am I right. Actually I don’t know, I’m just thinking of its logic of execution). Then, how can I be able to invalidate.
I saw this type of illustration in all of the tutorials on the WEB. Is it the actual way to set that attribute? Or, real application developers will give a variable in the «String» field to set it dynamically
(ie. session.setAttribut(userName, userName); //Setting the String Dynamically.. I dono is it right or not.)
WebContext ctx = WebContextFactory.get(); request = ctx.getHttpServletRequest();
What do the two lines above do? What will be stored in ctx & request? HttpSession ses = req.getSession(true); will creates new session means. What value stored in ses.
- You don’t need login/logout mechanisms in order to have sessions.
- In java servlets, HTTP sessions are tracked using two mechanisms, HTTP cookie (the most commonly used) or URL rewriting (to support browsers without cookies or with cookies disabled). Using only cookies is simple, you don’t have to do anything special. For URL re-writing, you need to modify all URLs pointing back to your servlets/filters.
- Each time you call request.getSession(true) , the HttpRequest object will be inspected in order to find a session ID encoded either in a cookie OR/AND in the URL path parameter (what’s following a semi-colon). If the session ID cannot be found, a new session will be created by the servlet container (i.e. the server).
- The session ID is added to the response as a Cookie. If you want to support URL re-writing also, the links in your HTML documents should be modified using the response.encodeURL() method. Calling request.getSession(false) or simply request.getSession() will return null in the event the session ID is not found or the session ID refers to an invalid session.
- There is a single HTTP session by visit , as Java session cookies are not stored permanently in the browser. So sessions object are not shared between clients. Each user has his own private session.
- Sessions are destroyed automatically if not used for a given time. The time-out value can be configured in the web.xml file.
- A given session can be explicitly invalidated using the invalidate() method.
- When people are talking about JSESSIONID , they are referring to the standard name of the HTTP cookie used to do session-tracking in Java.
I suggest you read a tutorial on Java sessions. Each user gets a different HttpSession object, based on a JSESSIONID request/response parameter that the Java web server sends to the browser. So every user can have an attribute with the same name, and the value stored for this attribute will be different for all users.
Also, WebContextFactory and WebContext are DWR classes that provide an easy way to get the servlet parameters.
As I understand it, your concerns are about separation of the different users when storing things in the HttpSession.
The servlet container (for example Tomcat) takes care of this utilizing its JSESSIONID.
- User first logs onto website.
- Servlet container sets a COOKIE on the user’s browser, storing a UNIQUE jsessionId.
- Every time the user hits the website, the JSESSIONID cookie is sent back.
- The servlet container uses this to keep track of who is who.
- Likewise, this is how it keeps track of the separation of data. Every user has their own bucket of objects uniquely identified by the JSESSIONID.
Hopefully that (at least partially) answers your question.
Your basic servlet is going to look like
There is no need to set any attribute names for your session that is already done. As others have suggested in other answers, use cookies or URL re-writing to store the sessionID for you.
When you are dealing with the DWR WebContext, it is simply doing the same thing as above, just normally the Request object isn’t passed into the method, so you use the WebContext to get that request for you
public class DWRClass < public doSomething()< WebContext ctx = WebContextFactory.get(); HttpServletRequest req = ctx.getHttpServletRequest(); HttpSession sess = req.getSession(); //no parameter is the same as passing true //Lets set another attribute for a forward or JSP to use ArrayListflags = new ArrayList(); req.setAttribute("listOfNames", flags); > >
What is wait type UCS_SESSION_REGISTRATION?, On one of my SQL 2012 servers I see this wait type is responsible for very high waits — often as high as 60% of the wall clock time. What exactly does it represent? I can find no documentation on it anywhere. Full SQL version is 11.0.3513. That’s 2012 SP1 with security KB 3045317 applied. Chuck · Often …
In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval . Is there a difference between these two?
If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t) .
You can make a session the default as follows:
t = tf.constant(42.0) sess = tf.Session() with sess.as_default(): # or `with sess:` to close on exit assert sess is tf.get_default_session() assert t.eval() == sess.run(t)
The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:
t = tf.constant(42.0) u = tf.constant(37.0) tu = tf.mul(t, u) ut = tf.mul(u, t) with sess.as_default(): tu.eval() # runs one step ut.eval() # runs one step sess.run([tu, ut]) # evaluates both tensors in a single step
Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable .
The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t is a Tensor object, t.eval() is shorthand for sess.run(t) (where sess is the current default session. The two following snippets of code are equivalent:
sess = tf.Session() c = tf.constant(5.0) print sess.run(c) c = tf.constant(5.0) with tf.Session(): print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run() .
I’d recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
eval() can not handle the list object
tf.reset_default_graph() a = tf.Variable(0.2, name="a") b = tf.Variable(0.3, name="b") z = tf.constant(0.0, name="z0") for i in range(100): z = a * tf.cos(z + i) + z * tf.sin(b - i) grad = tf.gradients(z, [a, b]) init = tf.global_variables_initializer() with tf.Session() as sess: init.run() print("z:", z.eval()) print("grad", grad.eval())
The most important thing to remember:
The only way to get a constant, variable (any result) from TenorFlow is the session.
Knowing this everything else is easy:
Both tf.Session.run() and tf.Tensor.eval() get results from the session where tf.Tensor.eval() is a shortcut for calling tf.get_default_session().run(t)
I would also outline the method tf.Operation.run() as in here:
After the graph has been launched in a session, an Operation can be executed by passing it to tf.Session.run() . op.run() is a shortcut for calling tf.get_default_session().run(op) .
Python — In TensorFlow, what is the difference between, sess = tf.Session() c = tf.constant(5.0) print sess.run(c) c = tf.constant(5.0) with tf.Session(): print c.eval() In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with block.
What is the important of the use of codeigniter database session (ci_session)
I need an answer from someone who have an experience with using codeigniter session. In config file i have to don’t use session database because it cause a conflit in my code :
$config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_expire_on_close'] = TRUE; $config['sess_encrypt_cookie'] = TRUE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300;
I use here session database off :
$config['sess_use_database'] = FALSE;
What’s is the importante of using this? and may i have problems in security if i desactivate it (FALSE) ?
This is from codeigniter you can read more here http://www.codeigniter.com/user_guide/libraries/sessions.html
Arguments to tensorflow session.run(), So using a TensorFlow Session object tf.Session as sess we run the optimizer train_step, which then evaluates the entire Computational Graph. sess.run (train_step, feed_dict=
Сессии(Session) в Java
Сегодня я расскажу вам про Session в Java, и ознакомлю вас с тем, как работает управление сессиями.
Интервал времени, в течение которого две системы (т.е. клиент и сервер) обмениваются данными друг с другом, можно назвать сеансом. Проще говоря, сеанс – это состояние, состоящее из нескольких запросов и ответов между клиентом и сервером.
Это известный факт, что HTTP и веб-серверы не имеют состояния. Следовательно, единственный способ поддерживать состояние пользователя – использовать технологии, которые реализуют отслеживание сеанса. Отслеживание сеансов в сервлетах может быть реализовано несколькими способами, одним из которых являются файлы cookie. Однако у них есть несколько недостатков:
- Только текстовая информация может быть сохранена ими.
- Если файлы cookie отключены пользователем, веб-приложение не сможет их использовать.
- Один файл cookie может содержать не более 4 КБ данных.
- Другой способ реализовать отслеживание сеансов – создание сеансов с уникальными идентификаторами сеансов для каждого пользователя в сервлете Java.
Http Session Interface
Сервлеты в Java предоставляют интерфейс, известный как «HttpSessionInterface». Они состоят из различных методов, некоторые из которых обсуждаются ниже:
- public HttpSession getSession (логическое создание): этот метод получает сеанс, связанный с запросом. Если он недоступен или отсутствует, создается новый сеанс, основанный на указанном логическом аргументе.
- public String getId(): уникальный метод сеанса возвращается этим методом.
- public long getCreationTime(): время, когда был создан сеанс, возвращается этим методом. Измеряется в миллисекундах.
- public long getLastAccessedTime(): время, когда сеанс последний раз был доступен, возвращается этим методом. Измеряется в миллисекундах.
- public void invalidate(): сессия может быть признана недействительной с помощью этого метода.
Пример: в приведенном ниже примере мы использовали методы getAttribute() и setAttribute() интерфейса HttpSession.
index.html
Переходя ко второму примеру
Servlet1.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet1 extends HttpServlet < public void doGet(HttpServletRequest request, HttpServletResponse response)< try< response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Welcome "+name); pwriter.print("Here is your password: "+password); HttpSession session=request.getSession(); session.setAttribute("usname",name); session.setAttribute("uspass",password); pwriter.print("view details"); pwriter.close(); >catch(Exception exp) < System.out.println(exp); >>
Переходя к третьему примеру
Servlet2.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet2 extends HttpServlet < public void doGet(HttpServletRequest request, HttpServletResponse response)< try< response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); HttpSession session=request.getSession(false); String myName=(String)session.getAttribute("usname"); String myPass=(String)session.getAttribute("uspass"); pwriter.print("Name: "+myName+" Pass: "+myPass); pwriter.close(); >catch(Exception exp) < System.out.println(exp); >> >
web.xml
MyServlet1 Servlet1 MyServlet1 /loginform MyServlet2 Servlet2 MyServlet2 /Welcome
У этого интерфейса есть различные преимущества и недостатки, перечисленные ниже:
- Все виды объектов, такие как база данных и текст, могут быть сохранены в сеансе.
- Сессии безопасны.
- Поскольку объект сеанса хранится на сервере, производительность снижается.
- Сериализация и десериализация также приводят к накладным расходам.
Весьма выгодно использовать HttpSessionInterface для отслеживания сеанса.