I have a web site where I have a login form. If the login is successfull I put the object user into the session and I go in another page (in which I need the session attributes) in this way:
-Java Servlet-
request.getSession(true).setAttribute("utente", u);
request.getSession(true).setAttribute("abbonamento", a);
request.getRequestDispatcher("HomeUtente.jsp").forward(request, response);
-Jsp page-
<%
Utente u = null;
Abbonamento a = null;
try {
u = (Utente) session.getAttribute("utente");
a = (Abbonamento) session.getAttribute("abbonamento");
} catch (Exception e) {
a = null;
u = null;
e.printStackTrace();
}
%>
Now, If I do this once it's ok, but If I refresh the page it seems that the session will be deleted.
I guess this because when I refresh the page (in debug mode) a and u will be both null.
Any idea?
Java Session -
HttpSession getSession(boolean create) -
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
So in your program as you are using -
request.getSession(true) -
it is always returning a new session and previous session variables are deleted.
also you can view the following link for better understanding -
How to check if session exists or not?
Related
Im trying to select 1 user from this code:
public static User getUserById(Long id) {
try {
String query = "SELECT u FROM User u WHERE u.id = " + id;
//bbddgestor is a class that provides utilites to build SessionFactory and configure Hibernate.
Session sesion = bbddgestor.SessionFactory.getSession().getCurrentSession();
sesion.beginTransaction();
Query sentence = sesion.createQuery(query);
List<User> users = sentence.getResultList();
sesion.getTransaction().commit();
return users.get(0);
} catch (Exception excp) {
...
return fakeUser;
}
}
I have also a check method to insert a new User into my DB:
public static void createUserFake (User userPar){
//This method just creates a valid user. In this case, we dont use userPar, we create and persist one directly, just to check.
User user = main.Main.createFakeUser();
Session sesion = bbddgestor.SessionFactory.getSession().getCurrentSession();
sesion.beginTransaction();
user.setLog("CREATED");
sesion.persist(user);
sesion.getTransaction().commit();
}
I call both methods from a JSP script, as you can see here. As you can see, I call first the creator method, and then the select one in order to obtain the user with ID = 1:
<%# page import="bbddgestor.BBDDController" %>
<%# page import="webtest.User" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
try {
BBDDController.createUserFake(null);
User user = BBDDController.getUserById(1L);
out.print(user.getJSONObj()); //Ignore this line, the error is on the previous line
} catch (Exception excp) {
//Ignore this exception handling
out.println("Error JSON: " + excp);
out.println("Cause: " + excp.getCause().getMessage());
}
%>
Both methods are coded in the same class, both static. This class is part of utilities library coded in a separate project. JSP is part of a WebApp project that uses the mentioned project as part of its libraries.
Hibernate configuration code is part of a class SessionFactory. Variable sessionFactory is a Factory reusable in any part of code:
public class SessionFactory {
//Inicializes session
static {
createSession();
}
static org.hibernate.SessionFactory sessionFactory;
private static void createSession() {
...
Configuration configurationAux = new Configuration();
//configurationAux.configure();
configurationAux.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configurationAux.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/pruebas?zeroDateTimeBehavior=convertToNull");
configurationAux.setProperty("hibernate.connection.username", "root");
configurationAux.setProperty("hibernate.connection.password", "toor");
configurationAux.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
configurationAux.setProperty("hibernate.show_sql", "true");
configurationAux.setProperty("hibernate.hbm2ddl.auto", "update");
configurationAux.setProperty("hibernate.current_session_context_class", "thread");
try {
configurationAux
.addAnnotatedClass(webtest.Category.class)
.addAnnotatedClass(webtest.Question.class)
.addAnnotatedClass(webtest.Test.class)
.addAnnotatedClass(webtest.User.class)
.addAnnotatedClass(webtest.Answer.class)
.addAnnotatedClass(webtest.TryTest.class)
.addAnnotatedClass(webtest.TupleQuestion.class)
.addAnnotatedClass(webtest.TupleToAnswer.class);
configuration = new StandardServiceRegistryBuilder()
.applySettings(configurationAux.getProperties())
.build();
SessionFactory.sessionFactory = configurationAux.buildSessionFactory(configuration);
return;
//Done this exception.
} catch (HibernateException excpi) {
...
}
Well then, the problem:
Second method (createUserFake) works fine no matter where you call it from. If you call from the JSP shown, it works. If you call it
from a desktop library, it works fine as well.
First method (getUserById) only works from a desktop or console app. When I call it from JSP script throws an
InvocationTargetException, even if createUserFake(null) has worked
fine before in the same JSP script.
What should I be doing wrong?
I have basic login-logout session management problem.
When i click login button, this function below gets triggered.After LDAP authentication, it moves to index.html where I display their name.
function validate()
{
var pageTitle=$(document).attr('title');
var un=document.getElementById('username').value;
var pwd=document.getElementById('pass').value;
$.ajax({
'url':'/analytics_1/validate',
'data':'userName='+un+'&password='+pwd,
'type':'GET',
'success':function(response)
{
if(response==1)
{
$.ajax({
'url':'/analytics_1/LogButton',
'type':'POST',
'data':'userName='+un+'&buttonId=VIKALPLoginButton&pageTitle='+pageTitle,
'success':function()
{
window.open("index.html","_self");
}
});
}
else
{
alert("Invalid Credentials");
}
}
});
}
I create the Session in LogButton.java after checking if it's new
if(session.isNew())
{
System.out.println("session is not set, lets create the name");
associate=req.getParameter("userName");
session.setAttribute("Associate",associate);
}
else
{
System.out.println("session is already set, lets get the name");
associate=(String)session.getAttribute("Associate");
}
I get their name from the session I created after successful login
And I do some actions and logout,
$('#logout').on('click',function()
{
var pageTitle=$(document).attr('title');
$.ajax({
'url':'/analytics_1/LogButton',
'data':'buttonId=VIKALPLogoutButton&pageTitle='+pageTitle,
'type':'POST',
'success':function()
{
window.open('Login.html',"_self");
},
'error':function(err)
{
alert("haha:"+err.response);
}
});
});
In LogButton.java, I check if button is VIKALPLogoutButton, if true, i proceed to invalidate the session and remove Attribute
if(button.equals("VIKALPLogoutButton"))
{
System.out.println("deleting the session cuz of logout");
session.removeAttribute("Associate");
session.invalidate();
//System.out.println("what happens to the session? " +session.isNew());
}
All these happen as per required. Now comes the security use case : What should happen if I go to index.html without logging in?
So I started checking if session is set or not when index.html loads,
$(document).ready(function () {
$.ajax({
'url':'/analytics_1/GetAssocId',
'type':'POST',
'success':function(response)
{
if(response!="null")
{}
else
{
window.open("Login.html","_self");
}
$('#name').text(response);
}
});
.....
.....
}
GetAssocId.java:
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
HttpSession session=req.getSession();
PrintWriter out=res.getWriter();
out.print(session.getAttribute("Associate"));
}
This also works fine, i.e it redirects me to Login.html if the session isn't created.
Now the thing is, I cannot Login, even after providing valid credentials, somehow the "Associate" attribute is set to null,
Below is the System.out.println output that I get in cmd
Above white line: Login,Logout action (notice the session invalidate output that I've given)
Below white line: Go directly to index.html, it redirects to Login.html, and you Login with your valid credentials,
Now this is my problem, It invalidates the session, yet still it says session is already existing . Even more confusing is, session is existing, but the value is null.
How do I overcome this problem? Please help
P.S:Other than the snippets I've provided for LogButton.java are not significant for this problem
HttpSession session=req.getSession();
If you look at the docs of getSession method
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
You are calling req.getSession() method which gives you a new session. Probably to get the existing session you need to use
HttpSession session=req.getSession(false);
As you already invalidate the session, this gives you session as null .
Your other question
Now this is my problem, It invalidates the session, yet still it says session is already existing . Even more confusing is, session is existing, but the value is null.
It's because you created a new session, there are no attributes in it and that is the reason you getting null
I am fetching username from database when a user is logging in by his userid. so if userid is let's say mat is logging then I am displaying the name as Mathews in userhome.jsp.
I have 5 jsp pages and in each page instead of writing a sql query (to fetch username from database by their id) I am defining a class Username.java and want to return userName to each jsp page. But this error is coming:
`HttpSession session1 = request.getSession(false);`
The error tells me to define a request class. How can I solve it?
public class Username {
public String getUserName(Long userId) {
HttpSession session1 = request.getSession(false);// error is coming here for request
String userid = (String)session1.getAttribute("userid");
// I want to fetch user name from database by the userid above
String userName = "";
//all my sql code here
return userName;
}
}
I am writing the following code in the jsp:
Username uName = new Username ();
uName.getUserName (userId);
The implicit object 'request' is only available in your JSP page. For the class that you are defining, the object is not present. You will have to define it explicitly.
One solution would be to get the Session in the JSP page and pass it as an argument (may be to a constructor) to your class.
For eg, You could define a constructor in the class like this:-
public class Username {
private HttpSession session;
Username(HttpSession session){
this.session = session;
}
public String getUserName(Long userId) {
/* remove the following line */
//HttpSession session1 = request.getSession(false);// error is coming here for request
String userid = (String)session.getAttribute("userid");
// i want to fetch user name from database by the userid above
String userName = "";
//all my sql code here
return userName;
}
}
Then modify the code in JSP page like:-
Username uName = new Username(request.getSession());
uName.getUserName(userId);
In the servlet:
User yourUser = new User (1,"Mathews");
request.setAttribute("userMegaUserOrWhateverYouCall", yourUser); //
In the jsp scriptlet:
<% User u = (User) request.getAttribute("userMegaUserOrWhateverYouCall"); // may need casting %>
some html code
<%= u.getUserName() %>
UPDATE: judging from your class, you need to go through tutorials. You have to use HttpServlet class.
Examples on servlets: http://www.servlets.com/jservlet2/examples/
Also consider using your TA help, they are specifically out there to help you for you ;-)
In my play! app,I have coded the controllers.Security as
class Security extends controllers.Secure.Security {
...
static void onDisconnected() {
Application.index();
}
static void onAuthenticated() {
User user = User.find("byEmail",Security.connected()).first();
if(user.isAdmin()) {
Admin.index();
}else {
System.out.println("onAuthenticated()::user not admin");
}
}
I have set the routes as
GET /admin/? Admin.index
* /admin module:crud
GET / Application.index
When I am on a page say pageX and click on the login link,the login form appears and I am able to login.If I login as admin ,it takes me to the Admin.index() and thereby to Admin/index.html view.So far so good
But,when I am on pageX,and click on login link,I expect to come back to pageX.Instead ,the Application.index() method is called and I am taken to the Application.index.html..
Is this the expected behaviour?
What do I have to do to get to pageX after login?
update:
I tried storing the url in flash using the #Before in Security controller
class Security extends controllers.Secure.Security {
#Before
static void storeCurrentUrl() {
System.out.println("storeCurrentUrl()");
flash.put("url", "GET".equals(request.method) ? request.url : "/");
}
static boolean authenticate(String username, String password) {
...
}
static void onAuthenticated() {
...
String url = flash.get("url");
System.out.println("url="+url);
if(!user.isAdmin()) {
if(url!=null) {
System.out.println("url not null");
redirect(url);
}else {
System.out.println("url null ..go to /");
redirect("/");
}
}
}
When I login,I get these terminal output
url=null
url null ..go to /
index()
I have put the login/logout links in main.html template which is inherited by all other pages
<div id="main">
<div class="auth">
Go to Admin Area<br/><br/>
Login<br/><br/>
Log out
</div>
In you controller, before calling 'login()' put the 'url' into flash something like:
flash.put("url", "GET".equals(request.method) ? request.url : "/");
Once successfully logged in, get the 'url' and redirect.
String url = flash.get("url");
redirect(url); //you may redirect to "/" if url is null
This will be the expected behaviour as this is the way your routing is setup. Click on login and get redirected to Application.index or Admin.index if admin user.
If you want to retrieve the page which you clicked the login link from you could add the current action to the login link and once authenticated redirect to this action.
ie. login link: GET /login?action=Application.something --> takes you to login page
then save action as a hidden field in your login form. When you authenticate the user render the action.
Play already do redirection to original url when you try to access a protected page while not logged in.
If you want to reuse this, you ca put your url in flash scope in the "onAuthenticated" method. In the source code, play call "redirectToOriginalURL" just after that based on the value of the "url" value.
static void onAuthenticated() {
flash.put("url", "GET".equals(request.method) ? request.url : "/");
}
I'm creating my application and i want integrate it with google account and I have following problems:
I want to authorize the user and get back to this pages and after share some data from google calendar.
So this is my code snippet to create the login url (index.jsp)
boolean b= true;
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if(user!=null){
%>
<p>Hello, <%= user.getNickname() %> </p>
<%
}
try
{singleUseToken AuthSubUtil.getTokenFromReply(request.getQueryString());
}catch (NullPointerException e)
{
String nextUrl = Settings.SERVER_ADDRESS;
String scope ="http://www.google.com/calendar/feeds/";
String login=AuthSubUtil.getRequestUrl(nextUrl, scope, false, true);
%>
<p>"App needs access to your Google Calendar account to read your Calendar feed. To authorize MyApp to access your account
log in to your account.)</p>
<%
b=false;
}
if (b== true){
CalendarService myService=null;
try{
sessionToken = AuthSubUtil.exchangeForSessionToken(URLDecoder.decode(singleUseToken, "UTF-8"), null);
}
catch(NullPointerException e)
{
%>
<p><%=e %> </p>
<%
}
CalendarService myService = new CalendarService("google-ExampleApp-v1.0");
myService.setAuthSubToken(sessionToken);
...
And I create the authSubUrl and pass it to the UserService to create the second redirect, but UserService.getCurrentUser() returns null although I'm logged.
The second problems it's lost session - when I go to the other .jsp pages I'm log out from my account.
Please help
Make sure you have configured the sessions-enabled property in your application's appengine-web.xml
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>myapp</application>
<version>01</version>
<ssl-enabled>true</ssl-enabled>
<sessions-enabled>true</sessions-enabled> <!- <<<< Make sure you have this ->
</appengine-web-app>