Get and Set Session Variables in a Servlet

Last modified: April 1, 2014 Published: March 31, 2008 by NiclasLeave a reply

This code example shows how to set and get variables stored in a session. To get a reference to the session object we call the getSession() method of the HttpServletRequest object.
We send the argument true to the method to tell it to create the session if it doesn’t exist.
Then we try to get the session variable ‘VisitCounter’ from the session by calling the method getAttribute().
It’s supposed to be stored as an Integer object, so we cast it to an Integer directly.
If the parameter is null, we create a new Integer object with the value of one (1) and add it to the session, else we add one to the object retrieved from the session and write it back to the session again. When writing a variable to the session the method setAttribute() is used.
Then we print out the value of the session parameter, which tells how many times this page has been displayed during this particular session.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

importjava.io.*;

importjavax.servlet.*;

importjavax.servlet.http.*;

/**

* Example Servlet

* @author www.javadb.com

*/

publicclassExampleServletextendsHttpServlet{

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.