aspose file tools*
The moose likes JSP and the fly likes Maintain a variable across jsp pages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Maintain a variable across jsp pages" Watch "Maintain a variable across jsp pages" New topic
Author

Maintain a variable across jsp pages

matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I have multiple jsp pages and I want to count the number of times that the jsp is accessed. How would i do this?
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Welcome to the ranch Matt. :) Do you want to count the number of times a particular JSP is accessed? Your subject line says something else. You usually use a variable in the application scope for it to persist across the JSPs in an application.Read about the scopes of Objects in JSP pages. See if this is what you want.


~ Mansukh
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I have three variables one is the username of the person using the system, another is a score for a test they are taking and the third is a count of ho\w many times a jsp is accessed to a max of 20. Need to be able to access the data from any where in the application how do I do that?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60082
    
  65

You store per-user data in the session.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Did you read about scopes of JSP Objects? Read and follow this simple tutorial. It attempts to do exactly the kind of thing that your use case demands. Let me know in case you run into any issues.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
The username variable is working but how do I use the session attribute with a counter or convert it to a string the IDE says they are incompatible.
Lalit Mehra
Ranch Hand

Joined: Jun 08, 2010
Posts: 383

Hi matthew,

You can use a servlet scope/level variable that is defined in the web.xml to store the number of jsp page views.
Although, I think using some class or an interface could help you out here too.

cheers :-)


http://plainoldjavaobject.blogspot.in
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
Umm i didn't understand that sorry. I'm not very good at jsps/servlets.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

matthew irving wrote:The username variable is working but how do I use the session attribute with a counter or convert it to a string the IDE says they are incompatible.


Can you show me what have you written and where is it at code level that the problem is coming?
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
Here is the example i have two jsps one is for the question and the other is the check the result. The first randomly retrieves a noun and its gender from a database and then displays the noun. I then try to save the noun as a string and then a session variable. I then want the second page to be able to retrieve the variable and compare it and the users answer against the database.


qugenpage.jsp

<%@ page language ="java" import="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*" %>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="teststyle.css">

<title>Noun Gender Question</title>
</head>
<br>
<h1>Noun Gender Question</h1><br>
Welcome <%= session.getAttribute( "userid" ) %>
<br>
<%
try {
String connectionURL = "jdbc:mysql://localhost:3306/language";
// declare a connection by using Connection interface
Connection connection = null;
// Load JBBC driver "com.mysql.jdbc.Driver".
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters of
string type connection url, user name and password to connect to database. */
connection = DriverManager.getConnection(connectionURL, "root", "password");
Statement st = connection.createStatement();// sql query to retrieve values from the specified table.
ResultSet rs = null;
String QueryString = "SELECT * FROM nouns "
+ "ORDER BY RAND() "
+ "LIMIT 1";
rs = st.executeQuery(QueryString);
while (rs.next()) {
%>
The gender of the German noun <%=rs.getString(2)%> is : <br>
<%
String germannoun = rs.getString(2);
application.setAttribute( "german", germannoun );
}

// rs.close();
// st.close();
// connection.close();
} catch (Exception ex) {
%>
<font size="+3" color="red"></b>
<%
out.println("Unable to connect to database.");
}
%>
</font>
<form action="qugen.jsp" method="post">
<table>
<tr>
<td><input type="text" name="noungender" ></td><br>
</tr>
<tr>
<td><input type="submit" name="b3" value="submit"></td>
</tr>
</table>
</form>
<br>
<a href="Mainmenu.html">Return to main menu</a>
</body>
</html>





qugen.jsp



<%@ page language ="java" import="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*" %>
<%
session.getAttribute("german");

String gendernoun = request.getParameter("nounenglish");
String german = request.getParameter("german");
session.putValue("german", german);

try {
String connectionURL = "jdbc:mysql://localhost:3306/language";
// declare a connection by using Connection interface
Connection connection = null;
// Load JBBC driver "com.mysql.jdbc.Driver".
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters of
string type connection url, user name and password to connect to database. */
connection = DriverManager.getConnection(connectionURL, "root", "password");
// check weather connection is established or not by isClosed() method
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select germannoun,gender from nouns");

while (rs.next()) {
String germannoun = rs.getString(1);
String gender = rs.getString(3);
if (german.equals(germannoun) && gendernoun.equals(gender)) {

%>
<jsp:forward page="random.jsp"/>
<%
} else {
out.println("Unable to connect to database.");
%>
<jsp:forward page="random.jsp"/>
<%
}
}

} catch(Exception e) {
throw new RuntimeException("Cannot connect the database!", e);
} finally {
System.out.println("Closing the connection.");
}

%>
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Now tell me where is the IDE throwing an error.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
The code now returns a cannot connect exception and i cant get the value of the germannoun retrieved when the table is randomly searched to convert to a string that can be used in the query in qugen.jsp:

HTTP Status 500 -

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: java.lang.RuntimeException: Cannot connect the database!

root cause

java.lang.RuntimeException: Cannot connect the database!

root cause

java.lang.NullPointerException

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.
GlassFish Server Open Source Edition 3.1.2.2

qugenpage.jsp



qugen.jsp

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Was it able to connect to the DB earlier? If yes, then you have changed something which has caused the connection to fail. Or check if the DB service is up and running correctly.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I cannot find any change and the other pages with the same code work fine.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Put print statements after each step and check whether the connection object is being created properly. Do the same for others too. If you know how to use Eclipse debugger, that would help too.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
It reaches the if statement in qugen.jsp and then goes straight to the catch statement.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Print the stack trace using e.printStackTrace() and show it to me.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
Is this it?

matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I have no idea the netbeans ide returns it in the info tab for glassfish
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I can code in both and given enough time i can solve the problem and learn all there is to know about jsps but i don't have enough time.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Well Matt, we hear that a lot here. If you don't have time for yourself, who else will? :D Anyways, do you know how to use the debugger in NetBeans? You can debug and see where is it exactly that the code is failing. Read this page to learn how to use the in built debugger that NetBeans has.
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I'm trying to take the germannoun value from the first jsp using session variables and then convert into a string in the second for validation but i get an error about incompatible types.

HTTP Status 500 -

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 14 in the jsp file: /qugen.jsp
PWC6199: Generated servlet error:
incompatible types
required: java.lang.String
found: void

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.
GlassFish Server Open Source Edition 3.1.2.2




qugenpage.jsp




qugen.jsp

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

What are you doing at line 14:



You are trying to assign a value to the String variable identifier word. Is this how you store a value in a variable? Using the <%= expression%> element? Do you know what expressions are used for in a JSP? What does the error message say? Read it:

PWC6199: Generated servlet error:
incompatible types
required: java.lang.String
found: void


You have String word on the left hand side and you are trying to assign void to it. It will obviously complain. How do you store a value in a variable in Java? Do you ever say :



That is what you are asking the compiler to do. You should say:



That is how you write a scriptlet inside a JSP.


matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I restarted everything but i got the same error
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
I changed line fourteen and got a different error.

HTTP Status 500 -

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 14 in the jsp file: /qugen.jsp
PWC6199: Generated servlet error:
incompatible types
required: java.lang.String
found: java.lang.Object

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.
GlassFish Server Open Source Edition 3.1.2.2


qugen.jsp

matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
The first part is a string type and changing the second part has changed it to an object that can be declared?
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

When faced with such errors / exceptions, read the API documentation. Always keep it open whenever you are developing an application. What do you observe? What is the method return type and what are you doing?
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
The return type is object and the object is the variable type like session or scope?
matthew irving
Ranch Hand

Joined: Apr 28, 2013
Posts: 38
Thank you could we start after 4? I have to be at a meeting soon.
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2713
    
    5

Mansukhdeep Thind wrote: org.apache.jsp.qugen_jsp._jspService(qugen_jsp.java:84)
Where did this Java file come from? And how will you find what is the code at line 84 of that java file that is actually causing the exception?
It is always good to get the fundamentals right first.

Mansukh I am not doubting your fundamentals but for your reference, the .java file is the translated servlet from the JSP. Any IDE like Netbeans allows you to see that file so it can be known what line 84 or any other line is.
matthew irving wrote:I have no idea the netbeans ide returns it in the info tab for glassfish

Matthew it is displayed as a link in the IDE right? Just click the link and it will take you to the exact line where the exception is thrown.

SCJP, SCWCD.
|Asking Good Questions|
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2713
    
    5

matthew irving wrote:The return type is object and the object is the variable type like session or scope?

The return type for session.getAttribute() is Object. You need to type cast it to the appropriate type which was used while session.setAttribute(). In your case this is String.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Amit Ghorpade wrote:
Mansukhdeep Thind wrote: org.apache.jsp.qugen_jsp._jspService(qugen_jsp.java:84)
Where did this Java file come from? And how will you find what is the code at line 84 of that java file that is actually causing the exception?
It is always good to get the fundamentals right first.

Mansukh I am not doubting your fundamentals but for your reference, the .java file is the translated servlet from the JSP. Any IDE like Netbeans allows you to see that file so it can be known what line 84 or any other line is.


Yes Amit. I know that, you know that too. But we are here to ensure that the OP, Matt, understands that. That is why I want him to understand the entire thing, not just solve this issue and then come back with a similar one tomorrow. I believe that you give a man a fish, you feed him for a day. You teach him how to fish, you feed him for a lifetime. :) Moreover, the kind of doubts he is asking gives me the feeling that he does not understand Java completely.

Amit Ghorpade wrote:
matthew irving wrote:I have no idea the netbeans ide returns it in the info tab for glassfish

Matthew it is displayed as a link in the IDE right? Just click the link and it will take you to the exact line where the exception is thrown.


See, you just gave him the fish. Let's teach him how to fish. :wink:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Maintain a variable across jsp pages
 
Similar Threads
unable to do validation for select in struts2
How to include a part of html code in to a jsp page?
inputCalendar - absolute uri problem
JDBC connection for DB2 database
choosing eclipse