How to restrict a JSP hit counter? - java

I am writing a hit counter in JSP, for my coursework. I have write the code, and there is not error and its working, but the problem is that:
if the user have open the website and try to use different page, whenever that the user goes back to the home page the counter still is adding a number, how can I restrict this part? shall restrict it with session?
this is my code :
<jsp:useBean id="counter" scope="application" class="counter.CounterBean" />
The current count for the counter bean is:
<jsp:setProperty name="counter" property="coun" value="1"></jsp:setProperty>
<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
Bean:
package counter;
import java.sql.*;
import java.sql.SQLException;
public class CounterBean implements java.io.Serializable {
int coun = 0;
public CounterBean() {
database.DatabaseManager.getInstance().getDatabaseConnection();
}
public int getCoun() {
return this.coun;
}
public void setCoun(int coun) {
this.coun += coun;
}
public boolean saveCount() {
boolean _save = false;
database.SQLUpdateStatement sqlupdate = new database.SQLUpdateStatement("counter", "hitcounter");
sqlupdate.addColumn("hitcounter", getCoun());
if (sqlupdate.Execute()) {
_save = true;
}
return _save;
}
public int getVisitorsNumber() throws SQLException {
int numberOfVisitors = 0;
if (database.DatabaseManager.getInstance().connectionOK()) {
database.SQLSelectStatement sqlselect = new database.SQLSelectStatement("counter", "hitcounter", "0");
ResultSet _userExist = sqlselect.executeWithNoCondition();
if (_userExist.next()) {
numberOfVisitors = _userExist.getInt("hitcounter");
}
}
return numberOfVisitors;
}
}

Change this part of the code:
<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
To
<%
if (session.isNew()) {
counter.saveCount();
} else {
counter.setCoun(-1);
}
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
Hope this helps.
UPDATE: By the way, it's better to choose better names for the methods of your Counter class. First of all, change setCoun to setCount. Besides, a setter method usually just assigns the value passed to it to its associated field. If you want to increment the value of coun, change the method name to addCount. Then increment the count value like:
<jsp:setProperty name="counter" property="coun" value="${1 + counter.coun}"></jsp:setProperty>

<%#page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
Integer hitsCount=(Integer)application.getAttribute("hitcount");
int m;
if(hitsCount==null)
{
m=1;
hitsCount =Integer.valueOf(m);
application.setAttribute("hitcount", hitsCount);
}
else
{
hitsCount=(Integer)application.getAttribute("hitcount");
m=hitsCount.intValue()+1;
hitsCount= Integer.valueOf(m);
application.setAttribute("hitcount", hitsCount);
}
%>
<center>
<p>Total number of visits:<%=hitsCount.intValue()%> </p>
</center>
</body>
</html>

Related

Java Beans and JSP. Mini Addition Program

I am trying to create a small program that takes two number as input from user via MiniAdd.jsp, adds them and then returns it on the same page. I had to make use of Javabeans in JSP. I'm not really sure what I've done. But right now I am running the code and I get [HTTP Status 500 – Internal Server Error].
org.apache.jasper.JasperException: An exception occurred processing.
Can someone please help me with where I've gone wrong and what do I need to do? Here's my code so far.
SumBeans2.java
package add;
import java.io.Serializable;
public class SumBean2 implements Serializable {
private int num1;
private int num2;
private int sum;
public SumBean2(){
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
MiniAdd.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="add.SumBean2"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sum</title>
</head>
<body>
<form action="MiniAdd.jsp">
<label>Number 1</label><input type="text" name="num1"><br>
<label>Number 2</label><input type="text" name="num2"><br>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
<jsp:useBean id="SumNumber" class="add.SumBean2" scope="session"/>
<jsp:setProperty name="SumNumber" property="num1" value='<%=request.getParameter("num1") %>'/>
<jsp:setProperty name="SumNumber" property="num2" value='<%=request.getParameter("num2") %>'/>
</form>
<%
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("num1"))+Integer.parseInt(request.getParameter("num2"));
} catch(Exception e) {}
%>
<jsp:setProperty name="SumNumber" property="sum" value='<%= request.getParameter("sum") %>'/>
Sum = <jsp:getProperty name="SumNumber" property="sum"/>
</body>
</html>

While displaying the items from the cart class in a a jsp file the values are overriding previous one (SESSION)

I'm working on adding multiple dish id, quantity and food description.
Cart.java
package com.hotelordering;
public class Cart{
int quantity;
int menuid;
String fooddesc;
public void setQuantity(int quantity){
this.quantity=quantity;
}
public int getQuantity(){
return quantity;
}
public void setMenuId(int menuid){
this.menuid=menuid;
}
public int getMenuId(){
return menuid;
}
public void setFoodDesc(String fooddesc){
this.fooddesc=fooddesc;
}
public String getFoodDesc(){
return fooddesc;
}
}
AddToCart.jsp (Getting paramater values from submission page)
<%#page import="java.sql.*" %>
<%#page import="java.util.*" %>
<html>
<body>
<form method="post" action="checkCart.jsp">
<%
ArrayList<Cart> list= new ArrayList<Cart>();
Cart cart = new Cart();
Enumeration<String> parameters=request.getParameterNames();
while(parameters.hasMoreElements())
{
String value=parameters.nextElement();
if(value.equals("quantity"))
{
try{
String[] q=request.getParameterValues(value);
for(String quant: q)
{
int quantity=Integer.parseInt(quant);
cart.setQuantity(quantity);
list.add(cart);
session.setAttribute("quantity",list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if(value.equals("menuid"))
{
try{
String[] m=request.getParameterValues(value);
for(String menu: m)
{
int menuid=Integer.parseInt(menu);
cart.setMenuId(menuid);
list.add(cart);
session.setAttribute("menuid",list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try{
String[] fooddesc=request.getParameterValues(value);
for(String food: fooddesc)
{
cart.setFoodDesc(food);
list.add(cart);
session.setAttribute("fooddesc",list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
out.println("Added to cart !");
%>
<input type="submit" value="Check cart"><br>
</form>
<form action="displayCategory.jsp" method="post">
<input type="submit" value="Add more item"><br>
</form>
</body>
</html>
checkCart.jsp
Displaying quantity, menuid and description from ArrayList but it is overriding previous value and repeating the last entered values again
<%#page import="java.sql.*,java.util.*" %>
<form action="test.jsp" method="post">
<%
Cart cart=new Cart();
ArrayList<Cart> list = (ArrayList<Cart>)session.getAttribute("quantity");
for(Cart c:list)
{
out.println("Quantity" + c.getQuantity() + "<Br>");
out.println("Menu id: " + c.getMenuId() + "<Br>");
out.println("Food description: " + c.getFoodDesc() + "<Br>");
}
%>
<input type="submit" value="submit">
</form>
OUTPUT
The list value setting(session.setAttribute) should be outside for loop in the code above.
Similarly for other cases .
Since you are setting list value inside for loop itself final value alone getting added. And you also need to have new Cart object initialized for each object inside for loop. Your new Cart initialization should be inside for loop
for(String quant: q) {
cart=new Cart();
int quantity=Integer.parseInt(quant);
cart.setQuantity(quantity);
list.add(cart);
}
session.setAttribute("quantity",list);

my bean class is not been able to get identified by jsp engine

I am new to jsp and beans.I tried to make a small bean example but getting a jsp compile time error as follows:
Student.jsp:1:1: Needed class "find_record.StudentBean" is not found.
^
Student.jsp:4:34: The bean type "find_record.StudentBean" was not found.
<jsp:useBean id="findbean" class="find_record.StudentBean" scope="session" />
^-----------------------^
Student.jsp:5:23: This bean name does not exist.
<jsp:setProperty name="findbean" property="rollno" />
i have a Student.jsp to call StudentBean.java but getting that error
following are the code:
Student.jsp
<html>
<body >
<jsp:useBean id="findbean" class="find_record.StudentBean" scope="session" />
<jsp:setProperty name="findbean" property="rollno" />
<%
String status=findbean.findRecord();
if(status.equals("success"));
%>
<jsp:include page="Success.jsp" />
<% else %>
<jsp:include page="Error.jsp" />
</body>
</html>
StudentBean.java
//StudentBean,java
package find_record;
import java.sql.*;
public class StudentBean{
String name ,rollno,grade;
int marks;
public StudentBean(){}
public void setName(String name){
this.name=name;
}
public void setRollno(String rollno){
this.rollno=rollno;
}
public void setMarks(int marks){
this.marks=marks;
}
public void setGrade(String grade){
this.grade=grade;
}
public String getName(){
return(name);
}
public String getRollno(){
return(rollno);
}
public int getMarks(){
return(marks);
}
public String getGrade(){
return(grade);
}
public String findRecord(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","user","password");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select * from student where rollno="+rollno);
int c=0;
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));
c++;
}
if(c>0)
{
System.out.println("success");
return("success");
}
conn.close();
throw new Exception("record not found");
}catch(Exception e){
System.out.println(e.getMessage());
return("no record found");
}
}
}
Please refer to this post here which describes how to create a JavaBean. Your classes must implement Serializable in order for it to be a JavaBean (and have a serialVersionUID assigned). This allows the bean to be "flattened" and reconstructed where necessary.
Let me know if this doesn't solve the problem entirely. You also need to make sure that bean is getting placed in the session through the use of a servlet (or scriptlet in the JSP page).
Above did not solve it.
Try this:
<jsp:useBean id="findbean" class="find_record.StudentBean" scope="session">
<jsp:setProperty name="findbean" property="rollno"/>
</jsp:useBean>
The only thing I can tell about your code is that you should not end the IF sentence with ";", or event left it without brackets... Your code as it is, I was not able to run it, but this way I could, try this:
<%
String status = findbean.findRecord();
if (status.equals("success")) {
%>
<jsp:include page="Success.jsp" />
<% } else { %>
<jsp:include page="Error.jsp" />
<% } %>
For everything else, you are doing it ok for the first times. Good luck!

How To Access An Array In A NetBeans Class From A JSP Page?

I have a Java class that has an array in it. I need to iterate over the array in the JSP page. How is that done?
The class is:
package beans;
import java.io.Serializable;
public class voteDB implements Serializable{
private static final long serialVersionUID = 1L;
public sesion[] Users = new sesion[4];{
Users[0] = new sesion("John", 1234);
Users[1] = new sesion("Paul", 2345);
Users[2] = new sesion("Ringo", 3456);
Users[3] = new sesion("George", 4567);
}
}
and the JSP page is:
<%#page import="beans.voteDB"%>
<%#page import="beans.sesion"%>
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>Bienvenido!</h1>
<%
String UsuarioIn="", ContrasenaIn="";
if (request.getParameter("usuario") != null){
UsuarioIn = request.getParameter("usuario");
}
if (request.getParameter("contrsena") != null){
ContrasenaIn = request.getParameter("contrsena");
}
%>
<jsp:useBean id="sesionActual" class="beans.sesion" scope="session"/>
<jsp:setProperty name="sesionActual" property="usuario" value="<%=UsuarioIn %>"/>
<jsp:setProperty name="sesionActual" property="contrasena" value="<%=ContrasenaIn %>"/>
<table>
<tr><td>Nombre: </td><td><jsp:getProperty property="usuario" name="sesionActual"/></td></tr>
<tr><td>Contrseña: </td><td><jsp:getProperty property="contrasena" name="sesionActual"/></td></tr>
</table>
</body>
</html>
Though it still compiles, one is recommended to always follow the Java coding (naming) conventions (full versions here).
I'd be surprised if the voteDB class survived in any way: be it in the IDE w/o showing up any error or even compiles at all; my guess is you might have a background w/ another programming language.
Here comes the productive words for the question asked: using Java Collections Framework should do the tricks, please refer to this tutorial!
Here's my example, w/ a few adjustments to the code you provided:
package beans;
import java.util.ArrayList;
import java.util.List;
public class VoteDB {
private List<Sesion> sesions;
public VoteDB() {
this.sesions = new ArrayList<>(); // Forgot the definition (class initialization) the first time I typed this answer, which would throw NullPointerException
this.sesions.add(new Sesion("John", 1234));
this.sesions.add(new Sesion("Paul", 2345));
this.sesions.add(new Sesion("Ringo", 3456));
this.sesions.add(new Sesion("George", 4567));
}
public List<Sesion> getSesions() {
return sesions;
}
public void setSesions(List<Sesion> sesions) {
this.sesions = sesions;
}
}
Assuming the Sesion class is in the same package like the VoteDB class:
package beans;
public class Sesion {
private String key;
private Integer value;
public Sesion(String key, Integer value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
And in the .jsp:
<%#page import="beans.*" pageEncoding="UTF-8"%><%
VoteDB voteDB = new VoteDB();
for (Sesion sesion : voteDB.getSesions()) {
out.println(sesion.getKey() + ":" + sesion.getValue());
}
%>
There are certainly other ways to archive your goals/needs, mine is just one of those while trying to solve it in a more Java-like fashion.

Populate html table data based on dropdown list using jQuery and Java

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<jsp:include page="checkLogin.jsp" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Allocate Tans</title>
<script type="javascript" src="jquery-1.7.js"></script>
<sj:head jqueryui="true" jquerytheme="cupertino" />
</head>
<script type="text/javascript">
$(document).ready(function()
{
$('#batchID').change(function(event) {
var batch=$('#batchID').val();
$.ajax({
url : "doShowAllocationStatus.action",
data : "batch="+batch,
success : function(html) {
$('#table').html(html);
},
error : function(html) {
alert("error");
}
});
});
});
</script>
<body>
<div id=table>
<s:form action="doAllocate" name="allocate" executeResult="true">
<s:actionerror />
<s:actionmessage />
<s:select label="Select Batch" headerKey="-1"
headerValue="Select a Batch..." list="%{#session.Batchs}"
Value="batch" name="batch" id="batchID" />
<s:select label="Select User" headerKey="-1"
headerValue="Select an User..." list="%{#session.users}" name="user"
value="user" />
<s:radio list="#{'Curator':'Curator','QC':'QC'}" name="user_work_as" />
<s:submit value="Allocate" id="AllocateID" />
<table align="center" border="2" width="800">
<tr>
<th>TAN</th>
<th>Curator</th>
<th>Curator Status</th>
<th>QC</th>
<th>QC Status</th>
</tr>
<s:iterator value="allocationList" var="tableID">
<tr>
<td><s:checkbox name="Tans" fieldValue="%{#tableID.tan}"
theme="simple" />
<s:property value="tan" /></td>
<td><s:property value="curator" /></td>
<td><s:property value="curator_status" /></td>
<td><s:property value="qc" /></td>
<td><s:property value="qc_status" /></td>
</tr>
</s:iterator>
</table>
</s:form>
</div>
</body>
</html>
In this when I use the for all content inside the dropdown select works fine as i expected for dropdown list and table but it react different I mean the table is appended with same rows once again when I submit and if I select some thing in batch dropdown list then the table comes to it correct list. If I used only for table, it prints the full page once again. I can understand what had happen, but could not find solution to achieve what I need.
My aim is to display the table based on the batch selected and the submit should do what it actually has to do.
server side code...
package controller;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import model.BatchInfo;
import model.CationDAO;
//import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class AllocateTAN extends ActionSupport {
//Fields that hold data...
private List<BatchInfo> allocationList =new ArrayList<BatchInfo>();
private String batch;
private List<String> batchs = new ArrayList<String>();
private String TAN;
private String Tans[];
private String user;
private List<String> users = new ArrayList<String>();
private String user_work_as;
//getters and setters....
public List<BatchInfo> getAllocationList() {
return allocationList;
}
public void setAllocationList(List<BatchInfo> allocationList) {
this.allocationList = allocationList;
}
//#RequiredStringValidator(message = "Batch Not Selected")
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public List<String> getBatchs() {
return batchs;
}
public void setBatchs(List<String> batchs) {
this.batchs = batchs;
}
//#RequiredStringValidator(message = "TAN Not Selected")
public String getTAN() {
return TAN;
}
public void setTAN(String tAN) {
TAN = tAN;
}
public String[] getTans() {
return Tans;
}
public void setTans(String[] tans) {
Tans = tans;
}
//#RequiredStringValidator(message = "Worker Not Selected")
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
//#RequiredStringValidator(message = "Select Any One")
public String getUser_work_as() {
return user_work_as;
}
public void setUser_work_as(String user_work_as) {
this.user_work_as = user_work_as;
}
//variable used to access DataBase...
CationDAO dao1 = new CationDAO() ;
//flow 1.: making all details available for the allocate TAN page...when page page is loaded 1st time
public String AllocatingTANpageDetails() throws SQLException{
Map<String, Object>session=ActionContext.getContext().getSession();
this.batchs=dao1.Batch_List();
session.put("Batchs", batchs);
//Tans=dao1.Tan_list(getBatch());
this.users=dao1.Users_List();
session.put("users", users);
return SUCCESS;
}
/*TAN list
private void showTANlist(String Batch1) throws SQLException{
Map<String, Object>session=ActionContext.getContext().getSession();
Tans=dao1.Tan_list(Batch1);
session.put("Tans", Tans);
}*/
//flow 2.: showing Allocation Status in Table form...in same page
public String showAllocationStatus() throws SQLException {
System.out.println("Inside Show Allocation Status");
if(batch==null||"-1".equals(batch)){
addActionMessage("Please!... Select a Batch");
return ERROR;
}
Map<String, Object>session=ActionContext.getContext().getSession();
//setBatch(batch_value);
String bth=getBatch();
if (bth==null || bth=="-1"){
System.out.println("batch is empty "+bth);
}
System.out.println(bth);
session.put("Batch",bth);
// showTANlist(bth);
System.out.println("Processing Allocation List... ");
this.allocationList=(List<BatchInfo>)dao1.status(bth);
System.out.println(allocationList);
session.put("AllocationList",allocationList);
System.out.println("Finished...");
return SUCCESS;
}
//execute method form allocating a TAN for a user...
public String execute(){
String statusTable=null;
String er = null;
if(Tans==null||"-1".equals(Tans)){
addActionError("Please!... Select a TAN"); er="er";
}
if (user==null||"-1".equals(user)){
addActionError("Please!... Select an Worker");er="er";
}
if (user_work_as==null||user_work_as==""||"-1".equals(user_work_as)){
addActionError("Please!... Select either Curation or QC");er="er";
}
try {
statusTable=showAllocationStatus();
} catch (SQLException e) {
e.printStackTrace();
}
if(!"er".equals(er)&& "success".equals(statusTable)){
System.out.println("inside Execute metho of AllocateTAN.java");
if ("QC".equalsIgnoreCase(user_work_as)){
try {
if(!"Complete".equalsIgnoreCase(dao1.CheckCurator(batch,Tans))){
addActionMessage("Curation Not yet completed");
return ERROR;
}
dao1.AllocateTANforUser( batch, Tans, user, user_work_as);
this.allocationList=(List<BatchInfo>)dao1.status(getBatch());
return SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
}
}else if("Curator".equalsIgnoreCase(user_work_as)){
try {
dao1.AllocateTANforUser( batch, Tans, user, user_work_as);
} catch (SQLException e) {
e.printStackTrace();
}
this.allocationList=(List<BatchInfo>)dao1.status(getBatch());
return SUCCESS;
}
}
return ERROR;
}
}
First, I would suggest that you change your structure as you are using AJAX hardly at all (you only use one on load and that's it, and that is not different than passing all those values from the very beginning from the action). As you only have 3 values to pass, is fairly easy to capture them with jQuery("#myid").val() and pass them with jQuery.ajax. something like
<s:button value="Allocate Me!!!" onclick="allocating_you()"/>
and then
function allocationg_you(){
var val1 = jQuery("#value1").val();
var val2 = jQuery("#value2").val();
var val3 = jQuery("#value3").val();
jQuery.ajax({
url: "allocator",
data: "val1=" + val1 +"&val2=" + val2 + "&val3=" + val3 + "&r=" //dont forget to add a random number
success: function(data){
jQuery("#mytable").html(data).load();
}
});
}
finally, you should reduce the ajax refreshment to the minimun necessary, as it will be easier to mantain and to give aesthetics. so for example your template should be divided like this
<your form>
<your table header>
<div id="mytable">
with this template you would only have to refresh the actual content and everything else will remain intact (true AJAX), so in your JSP response for your AJAX call there should be only the iterator part. you will even be able to create the table with a scrollbar and a static header, only needing to put some matching sizes in your ajax cells along with the table tag.
Hope this helps you. If you manage to crack this you will be able to do wonders. jQuery + Struts2 + (seems that you are not using Hbernate, but oh well) it's a monstrous combination.

Categories