23

I am able to set session attribute in scriptlet but when I am trying to set session attribute inside java class it shows error like "session cannot be resolved". So how to set session in java?

<%String username = (String)request.getAttribute("un");
session.setAttribute("UserName", username);%>
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
sujoy
  • 299
  • 1
  • 2
  • 8

5 Answers5

51

By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods

public void doGet(HttpServletRequest request, HttpServletResponse response) {

    HttpSession session = request.getSession();
    String username = (String)request.getAttribute("un");
    session.setAttribute("UserName", username);
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
oks16
  • 1,294
  • 11
  • 16
3

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

Sheo
  • 1,034
  • 12
  • 24
-2

Try this.

<%@page language="java" session="true" %>
Raghuram
  • 51,854
  • 11
  • 110
  • 122
erimerturk
  • 4,230
  • 25
  • 25
-3

I am try to catch your point.I hope it is helpful.....

if (session.isNew()){
     title = "Welcome to my website";
     session.setAttribute(userIDKey, userID);
KOUSIK daniel
  • 305
  • 1
  • 3
  • 11
-7

Java file : Jclass.java

package Jclasspackage

public class Jclass {

    public String uname ;
    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }

    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }

    public Jclass() {
        this.uname = null;
    }

    public static void main(String[] args) {

    }
}

JSP file: sample.jsp

    <%@ page language="java"
    import="java.util.*,java.io.*"
    pageEncoding="ISO-8859-1"%>

<jsp:directive.page import="Jclasspackage.Jclass.java" />   
<% Jclass jc = new Jclass();
String username = (String)request.getAttribute("un")
jc.setUname(username);
%>

-----------------

In this way you can access the username in the java file using "this.username" in the class

Pawan Kumar Jha
  • 118
  • 1
  • 11