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 ;-)
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 am upgrading tapestry from 5.2.4 to 5.3.8 and am stuck at re-implementing the URL re-writing part.
In my application a user account can have multiple data stores. User can have same page of different stores active at the same time. Hence I need to put the storeId in page links and event links URLs. So What is done is as follows.
I register MyLinkTransformerClass in AppModule as follows.
#Contribute(PageRenderLinkTransformer.class)
#Primary
public static void provideURLRewriting( OrderedConfiguration<PageRenderLinkTransformer> configuration){
configuration.addInstance(
"Faces", MyLinkTransformer.class);
}
Following is the MyLinkTransformer class which implements PageRenderLinkTransformer
public PageRenderRequestParameters decodePageRenderRequest(
Request request) {
// for incoming requests - remove the store id from URL and
// save into Request as an attribute
String path = request.getPath();
if (path.equals("/")) {
// Redirect to accounts page
return new PageRenderRequestParameters("account", new EmptyEventContext(), false);
}
else {
String start = path.split("/")[1];
if (!ignoredRewriteSet.contains(start) && !start.startsWith("account")) {
String storePath = path.substring(1).substring(path.indexOf("/"));
int idx = storePath.indexOf("/");
if (idx < 0) idx = storePath.length();
String storeId = storePath.substring(0, idx).trim();
RequestHelper.setStoreId(request, storeId);
EventContext urlEventContext = new URLEventContext(contextValueEncoder, new String[]{storeId});
EventContext arrayEventContext = new ArrayEventContext(typeCoercer, "foo");
return new PageRenderRequestParameters(storePath.substring(idx), arrayEventContext, false);
//return new PageRenderRequestParameters(storePath.substring(idx), new EmptyEventContext(), false);
}
}
return null;
}
public Link transformPageRenderLink(
Link defaultLink,
PageRenderRequestParameters parameters) {
// for outgoing requests- This is where I want to access the store Id
// which is stored in Request class of Tapestry as an attribute and
// add it to the URL
return null;
}
So, the idea is to remove storeId from URL in decodePageRenderRequest method and save it in the Request class of Tapestry as an attribute. And while creating outgoing URLs of page link and event link, I want to access the storeId which was saved in Request and inject it to the URL which will be rendered in method transformPageRenderLink.
But I don't know how to pass parameters to transformPageRenderLink method or access Request instance there.
I am following http://blog.tapestry5.de/index.php/2010/09/06/new-url-rewriting-api/ example.
I am new to URL Rewriting, any help with this will be appreciated.
You will probably be interested in the ModeComponentEventLinkEncoder here. It removes a "mode" from the URL and puts it onto the Environment before passing it on to the normal tapestry URL processing.
It's a two way process so the "mode" is included in any links generated on the page.
Note: This is applied as a decorator here
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?
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 : "/");
}
When a user tries to access a page in the administration controllers (mostly CRUD stuff), he is being redirected to the login page. And, if the credentials is correct and he is indeed an administrator, he is begin redirected to the page he wanted to access in the previous request.
Whenever someone tries to access a forbidden page he is being redirected to the following controller:
public static void login(String returnUrl) throws Throwable {
Http.Cookie remember = request.cookies.get("rememberme");
flash.put("url",returnUrl);
if (remember != null && remember.value.indexOf("-") > 0) {
String sign = remember.value.substring(0, remember.value.indexOf("-"));
String username = remember.value.substring(remember.value.indexOf("-") + 1);
if (Crypto.sign(username).equals(sign)) {
session.put("username", username);
redirectToOriginalURL(returnUrl);
}
}
flash.keep();
render();
}
Which executes the authenticte(...) method:
public static void authenticate(#Required String username, String password, boolean remember, String returnUrl) throws Throwable {
// Check tokens
Boolean allowed = false;
// This is the official method name
allowed = (Boolean) Security.invoke("authenticate", username, password);
if (validation.hasErrors() || !allowed) {
flash.keep("url");
flash.error("secure.error");
params.flash();
login(returnUrl);
}
// Mark user as connected
session.put("username", username);
// Remember if needed
if (remember) {
response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
}
// Redirect to the original URL (or /)
flash.keep("url");
redirectToOriginalURL(returnUrl);
}
Note the String returnUrl in the parameter list. This controller is always called in the view with the response.url value.
The redirectToOriginalURL() is a method that receives a returnUrl in the parameter or in the flash scope.
static void redirectToOriginalURL(String returnUrl) throws Throwable {
if(returnUrl==null) returnUrl = flash.get("url");
if (returnUrl == null) {
returnUrl = "/";
}
redirect(returnUrl);
}
This works fine in Firefox and Internet Explorer. But when I try to execute this in Google Chrome, the returnUrl is null. Is this a known issue, or am I doing something terribly wrong?
There are no special requests or anything. The url, when redirected from the unaccessible page (localhost:9000/admin) is http://localhost:9000/account?returnUrl=%2Fadmin. So nothing wrong there...
The error must therefore lie withing the authenticate controller, that seems to be unable to pass arguments to the redirectToOriginalURL method. But, then again, only in Google Chrome.
Suggestions?
I got it working this way:
Make sure that checkAccess method calls login method with current url:
static void checkAccess() throws Throwable {
// Authent
if (!session.contains("username")) {
login(request.method.equals("GET") ? request.url : "/");
}
}
Then in login.html view add the hidden field which is the param you already passed to login method:
#{form #authenticate()}
<input type="hidden" name="returnUrl" value="${params.returnUrl}">
...
#{/form}
Or add returnUrl param directly to form.action:
#{form #authenticate().add("returnUrl", params.returnUrl)}
That's it. And you don't need flash scope.
I noticed this line of code in login:
redirectToOriginalURL();
That calling the method with no arguments, but the redirectToOriginalURL you show has a parameter String. Could it be this is part of the issue?