Keep track of games played JSF - java

I was wondering if anyone can help me?
I am creating a simple game using JSF. I have managed to complete the main functionality but I would like to tell the user how many games they have played.
For some reason, the code I have written for it does not work.
Bean:
import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class GameBeans {
private int randomNumber;
private int userGuess;
private int gamesPlayed;
public String getWin() {
if(this.userGuess == this.randomNumber)
{
return "Congratulations! You've Won!";
}
else
{
return "You Lose!";
}
}
/**
*
* #return randomNumber
*/
public int getRandomNumber() {
return randomNumber;
}
/**
* sets the generated random number
* #param randomNumber
*/
private void setRandomNumber(int randomNumber) {
this.randomNumber = randomNumber;
}
/**
*
* #return the guess of the user
*/
public int getUserGuess() {
return userGuess;
}
/**
* Sets the guess of the user into userGuess
* #param userGuess
*/
public void setUserGuess(int userGuess) {
this.userGuess = userGuess;
}
/**
*
* #return number of games played by the user
*/
public int getGamesPlayed()
{
return gamesPlayed;
}
private void setGamesPlayed(int played)
{
this.gamesPlayed=played;
}
/**
* Creates a new instance of GameBeans
* Generates a new random number
*
* Compares random number to user's
* choice
*
* Keeps total of games played
*/
public GameBeans() {
Random number = new Random();
int rNumber = number.nextInt(1000);
setRandomNumber(rNumber);
int played = this.gamesPlayed++;
setGamesPlayed(played);
}
}
First page (play_game.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Guess Numbers Page</title>
</h:head>
<h:body>
<h:form>
<h1>Welcome to Your Game Session</h1>
<p>Number of games played this session: #{gameBeans.gamesPlayed}</p>
<p>Enter your lucky number guess and then click play</p>
<p>Your guess: <h:inputText id="iptxt1" value="#{gameBeans.userGuess}" /></p>
<h:commandButton id="cmdBtn1" value="Play" action="game_result" />
</h:form>
</h:body>
</html>
game_result.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Game Results</title>
</h:head>
<h:body>
<h:form>
<p>Your Guess: <h:outputText id="outText1" value="#{gameBeans.userGuess}"></h:outputText></p>
<p>Random Number: <h:outputText id="outText2" value="#{gameBeans.randomNumber}"></h:outputText></p>
<p><h:outputText id="outText4" value="#{gameBeans.win}"></h:outputText></p>
<p>Number of Games Played: #{gameBeans.gamesPlayed}</p>
<h:commandButton id="cmdBtn1" value="Play Again" action="play_game" />
</h:form>
</h:body>
</html>
I would like to allow the user to play again even if they win or lose, the count (game played) should be kept track of. This is not working currently!
Can anyone help please??
Thanks

#SessionScoped bean is only created once when the client visit your page for the 1st time. It will then live until the end of the session. In other words, the constructor of your #SessionScoped bean is only called once. It's not the place to increment your gamesPlayed.
#ManagedBean
#SessionScoped
public class GameBeans {
private int randomNumber;
private int userGuess;
private int gamesPlayed;
public GameBeans() {
Random number = new Random();
this.randomNumber = number.nextInt(1000);
this.gamesPlayed = 0;
}
public void getWin() {
if (this.userGuess.equals(this.randomNumber))
return "Congratulations! You've Won!";
else return "You Lose!";
}
public void incrementGamesPlayed() {
this.gamePlayed++;
}
// Getters and Setters
}
And this is the play_game.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Guess Numbers Page</title>
</h:head>
<h:body>
<h:form>
<h1>Welcome to Your Game Session</h1>
<p>Number of games played this session: #{gameBeans.gamesPlayed}</p>
<p>Enter your lucky number guess and then click play</p>
<p>Your guess: <h:inputText id="iptxt1" value="#{gameBeans.userGuess}" /></p>
<h:commandButton id="cmdBtn1" value="Play" action="game_result"
actionListener="#{gameBeans.incrementGamesPlayed}" />
</h:form>
</h:body>
</html>

Related

Storing session variables in MVC between servlet and JSPs (error status 500)

When I run my dynamic web page, I get an error "java.lang.NumberFormatException: null" in my console after seeing that I get a status 500 page.
The code is supposed to ask the user to guess a number between 0-1000. If the user guesses incorrectly, it allows the user to guess again using the same session variables (target number and number of guesses are stored). This continues until the user guesses correctly of what the target number is. I am also avoiding using the hidden text option to store the variables.
I've already looked up what the error message means but I couldn't figure out where is it applying to as the status error is very vague.
Any help is appreciated...
Error message from console:
Oct 20, 2018 11:59:12 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controllers.GameServlet] in context with path [/GuessingGame_MVC_Version] threw exception
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at controllers.GameServlet.doPost(GameServlet.java:47)
at controllers.GameServlet.doGet(GameServlet.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
index.jsp (first page) :
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# page import="model.GameNumber" %>
<!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=US-ASCII">
<title>Guessing Game - MVC Version</title>
</head>
<body>
<h1>Guessing Game - MVC Version</h1>
<p>
Welcome to our guessing game!
</p>
<p>
Please guess a number between 0 and 1000.
</p>
<form name="guessForm" action="doGuess" method="get">
<label>
Guess 1:
</label>
<input type="text" name="guess" /><br />
<input type="submit" name="submit" value="Make Guess">
</form>
</body>
</html>
GameServlet.java (servlet):
package controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import model.GameNumber;
/**
* Servlet implementation class GameServlet
*/
#WebServlet(
description = "A servlet to control our simple guessing game",
urlPatterns = {
"/GameServlet",
"/doGuess"
},
initParams = {
#WebInitParam(name = "Guesses", value = "1"),
#WebInitParam(name = "Minimum", value = "0"),
#WebInitParam(name = "Maximum", value = "1000")
})
public class GameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Random rand = new Random();
int target = rand.nextInt(1000);
int guesses=1;
/**
* #see HttpServlet#HttpServlet()
*/
public GameServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get input - guess
GameNumber guess = new GameNumber(Integer.parseInt(request.getParameter("guess")));
// initialize output
String msg = "";
String url = "/guess.jsp";
// compare the guess with the target
if( guess.getValue() == target ){
// winner
msg = "Correct! You got it in " + guesses + " guesses.";
url = "/correct.jsp";
} else {
// next guess
guesses++;
if ( guess.getValue() < target ) {
//low
msg = "Incorrect guess! Guess higher next time.";
} else {
// high
msg = "Incorrect guess! Guess lower next time.";
}
}
//store guesses and target as session attributes
HttpSession session = request.getSession();
session.setAttribute("target", target);
session.setAttribute("guesses", guesses);
// add values to request object to pass to the destination
request.setAttribute("msg", msg);
// send control to the next component
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
RequestDispatcher dispatcherr = getServletContext().getRequestDispatcher(url);
dispatcherr.forward(request, response);
}
}
guess.jsp :
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# page import="model.GameNumber" %>
<%
// get the inputs from the request and session attributes
String msg = (String) request.getAttribute("msg");
Integer targett = (Integer) session.getAttribute("target");
int target = targett.intValue();
Integer guessess = (Integer) session.getAttribute("guesses");
int guesses = guessess.intValue();
// output the form to the client
%>
<!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=US-ASCII">
<title>Guessing Game - MVC Version</title>
</head>
<body>
<h1>Guessing Game - MVC Version</h1>
<p>
<%= msg %>
</p>
<form name="guessForm" action="doGuess" method="get">
<label>
Guess <%= guesses %>:
</label>
<input type="text" name="guess" /><br />
<input type="submit" name="submit" value="Make Guess">
</form>
</body>
</html>
correct.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String msg = (String) request.getAttribute("msg");
%>
<!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>Guessing Game - MVC Version</title>
</head>
<body>
<H1>Guessing Game - MVC Version</h1>
<%= msg %>
<p>
<a href=index.jsp>
Play Again
</a>
</p>
</body>
</html>
GameNumber (model):
package model;
import java.util.Random;
public class GameNumber {
private int value;
/**
*
*/
public GameNumber() {
value = 0;
}
/**
* #param value
*/
public GameNumber(int value) {
if (value < 0) {
this.value = 0;
} else {
this.value = value;
}
}
/**
* #return the value
*/
public int getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(int value) {
if (value < 0) {
this.value = 0;
} else {
this.value = value;
}
}
/**
*
* A simple method that sets value to a random integer between minimum and maximum
* #param minimum the minimum value in the range
* #param maximum the maximum value in the range
*/
public void setRandom(int minimum, int maximum){
Random random = new Random();
this.value = random.nextInt(maximum - minimum) + minimum;
}
/**
* a simple method to adjust the value up 1 unit
*/
public void increment(){
this.value++;
}
}
Try catch at guess (Gives same error) :
GameNumber guess = null;
try {
guess = new GameNumber(Integer.parseInt(request.getParameter("guess")));
} catch (NumberFormatException e) {
System.out.println("Number format Excdption!");
}
When I deployed your application with the mentioned jsp and servlet
It will work fine but I have noticed that there are some error in tomcat console at your GameServlet
since you are forwarding the request twice which is already been done
i.e. java.lang.IllegalStateException: Cannot forward after response has been committed
Hence in your GameServlet java, under doPost
comment the last line (mentioned below)
RequestDispatcher dispatcherr = getServletContext().getRequestDispatcher(url);
dispatcherr.forward(request, response);
and add
return; // not a must but helps in certain situations
about the error message you have mentioned
It will only occur if you pass a string message in the Text box.
Additional check can be applied for the same at runtime.
Your code seems fine and as per your comments it seems you aren't passing the right values to your servlet.
You are right when you say the values are passed as Strings to the servlet. Let's try an understand what a NumberFormatException is. From the docs :
Thrown to indicate that the application has attempted to convert a
string to one of the numeric types, but that the string does not have
the appropriate format.
The below code will work as the String "10" can be converted to an int.
String str = "10";
int i = Integer.parseInt(str);
But this would cause a NumberFormatException
String str = "hi";
int i = Integer.parseInt(str);
In your case you are passing a String which can't be converted to an int, hence it is failing.

Printing the results of a gene search to a HTML tab

I have created a managed bean that searches a gene database currently it only returns the result to the glass fish console. I am wondering if anyone can offer any suggestions on how to get my search results to display into my gene/protein search tab.
My current set of code:
MainPage.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- this allows the page to see the welcomepage style sheet-->
<link rel="stylesheet" type="text/css" href="Group1/welcomepage.css" media="screen"/>
<title>Main Page</title>
<!-- allows the page to see the jquery function see "http://jquery.com/" for description -->
<script src="jquery-1.11.0.min.js" type="text/javascript"></script>
<!-- allows the page to see the js script tabs see file for detailed comments-->
<script type="text/javascript" src = "tabs.js"></script>
</head>
<body>
<!-- the wrapper places everyting in one frame so the objects do not move when browser size is altered-->
<div id ="wrapper">
<div id = "main">
<div id ="header">
<!-- again the logo this one will appear in the header in the top left and when clicked returns you to the home page -->
<a href="index.xhtml">
<img id ="logo1" alt="Group1 logo"/>
</a>
<!-- this is the single search bar and button the "this.select()" function selects all the content in the search box in one click-->
<form name="Search" onsubmit="#{SearchUniprot.query}">
<input type="text" id ="GeneralSearch" name="Search" value="#{SearchUniprot.userSearch}" onclick="this.select();"/>
<input type="submit" id ="subSearch" value="Search" name="GenSearchButton"/>
</form>
</div>
<!-- tab container this created the tabs according the to style set out in the CSS -->
<div id="tab-container">
<ul class="tab-menu">
<li id="Start" class="active">Start</li>
<li id="Genes">Genes/Proteins</li>
<li id="Litrature">Litrature</li>
<li id="Analysis">Analysis</li>
</ul>
<div class="clear"></div>
<!-- each div section below determines what is written in each tab -->
<div class="tab-top-border"></div>
<div id="Start-tab" class="tab-content active">
<h1>Recent Activiy</h1>
<p>Recent files will be shown here</p>
</div>
<div id="Genes-tab" class="tab-content">
<h1>Genes and Proteins</h1>
<p>Results for genes and proteins based on search </p>
</div>
<div id="Litrature-tab" class="tab-content">
<h1>Litrature</h1>
<p>Results of Litrature search will be shown here</p>
</div>
<div id="Analysis-tab" class="tab-content">
<h1>Analysis</h1>
<p>A type of analysis will be shown here</p>
</div>
</div>
</div>
</div>
</body>
</html>
SearchUniProt.java
package TestGeneSearch;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
#ManagedBean (name ="SearchUniprot" )
#RequestScoped
public class SearchUniprot {
String userSearch;
public String getUserSearch() {
return userSearch;
}
public void setUserSearch(String userSearch) {
this.userSearch = userSearch;
}
public SearchUni getQuery() {
// make a new object of the SearchUniProt class and set the search term - obviously we need to read this in from the user in a demo
SearchUni query = new SearchUni("tuna");
//run the RunQuery method in SearchUniprot
query.RunQuery();
return query;
}
public SearchUniprot() {
}
}
SearchUni.java
package TestGeneSearch;
import javax.ejb.Stateful;
import uk.ac.ebi.webservices.axis1.stubs.ebeye.EBISearchService_PortType;
import uk.ac.ebi.webservices.axis1.stubs.ebeye.EBISearchService_Service;
import uk.ac.ebi.webservices.axis1.stubs.ebeye.EBISearchService_ServiceLocator;
#Stateful
public class SearchUni {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
//searchterm = what you want to search for
private String searchterm;
public SearchUni() {
}
//constrcutor
public SearchUni(String s) {
searchterm = s;
}
public String[] RunQuery() {
try {
//set up to connect to the searchservice
EBISearchService_Service service = new EBISearchService_ServiceLocator();
EBISearchService_PortType srvProxy = service.getEBISearchServiceHttpPort();
// Get the number of results for the query - we don;t necessarily need this but it may be useful
int result = srvProxy.getNumberOfResults("uniprot", searchterm);
System.out.println(result);
//get all results IDs - can easily limit it to however many we want
String[] ids = srvProxy.getAllResultsIds("uniprot", searchterm);
for (int i = 0; i + 1 < ids.length; i++) {
System.out.println(ids[i]);
}
//get more fields - the fields we can get depend on the database to be searched.
//a note about protein names in Uniprot - Uniprot contains two sections, reviewed and unreviewd
//the reviewed entries will have a Reccomended Name (descRecName), the unreviewed entries will have
//a Submitted name (descSubName) - so each of our results will have either a descRecName or a descSubName
//but not both.
//gene name (gene_primary_name) may be null
//accession number (acc) is a stable identifier - the id field printed out above is not the same as an
//accession number and shouldn't be assumed to be stable
String fields[] = {"acc", "descRecName", "descSubName", "gene_primary_name", "organism_scientific_name"};
String[][] results = srvProxy.getResults("uniprot", searchterm, fields, 1, 100);
for (int i = 0; i < result; i++) {
for (int j = 0; j < fields.length; j++) {
System.out.println(results[i][j]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
You're only seeing the results in the console because you're just printing the results in this line
System.out.println(ids[i]);
What you need to do is to store this results somewhere, make them available to your managed bean (for example, storing in a managed bean attribute) and make this information available in your xhtml via this attribute getters and setters.
One thing that is not clear to me yet is why do you need a stateful EJB for this task. If the only thing you need is to query the database and show the results, you may prefer to use a stateless EJB instead, which is simpler and probably will perform better too.
I also suggest you to use some JSF frontend library such as primefaces, so you'll have a whole set of rich GUI elements ready to use. In your specific case, since you're dealing with genomic data, some results (I guess) can be quite big and you may want to use some lazy loading features that are trivial to do with primefaces (and not so trivial to do without it)
The logic is like this
xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:body>
<h:form>
<p:inputText id="criteria" value="#{myMB.criteria}"/>
<p:inputText id="result" value="#{myMB.result}"/>
<p:commandButton value="query" action="#{myMB.query}" update="result"/>
</h:form>
</h:body>
</html>
when you hit the query button, myMB.query() method will be called, with the myMB.criteria populated in your managed bean, that may look like this
package mypackage;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MyMB implements Serializable{
private static final long serialVersionUID = 1L;
private String criteria;
private String result;
#EJB
private MyEJB myEJB;
public void query(){
this.result = myEJB.query(this.criteria);
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
notice that I use here a stateless EJB like this
package mypackage;
import javax.ejb.Stateless;
#Stateless
public class MyEJB {
public String query(String criteria) {
//do your query here
return "xyz";
}
}
after the query is done, the result will go to myMB.result, but it will only be shown after the xhtml process the
update="result"
notice that "result" in the line above is not myMB.result, but the xhtml tag with id="result"
I hope it's clearer now.

jsf commandbutton action not working ajax [duplicate]

This question already has answers here:
Rendering other form by ajax causes its view state to be lost, how do I add this back?
(2 answers)
Closed 9 years ago.
I've got this page, I have two forms on. The second form is loaded (rendered) by ajax. The problem is, that when button of the next form is pressed, the page just reloads itself, not actually calling the method specified in 'action'.
XHTML
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./../WEB-INF/employeeTemplate.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns="http://www.w3.org/1999/xhtml">
<ui:define name="content">
finding user ...
<h:form id="mainForm">
<h:inputText id="userId" value="#{eFindUser.userId}" />
<h:commandButton value="Render!" action="#{eFindUser.findUser}" >
<f:ajax event="action" execute="userId" render="#all" />
</h:commandButton>
</h:form>
<h:panelGroup id="result">
<h:panelGroup layout="block" rendered="#{eFindUser.notFound}" style="color:red">
User not found
</h:panelGroup>
<h:form>
<h:panelGroup layout="block" rendered="#{eFindUser.responseRendered}" >
<h:inputHidden value="#{eFindUser.user}" />
<table>
<tr>
<td>Name</td> <td>#{eFindUser.user.name}</td>
</tr>
<tr>
<td>Balance:</td> <td>#{eFindUser.user.account.balance}</td>
</tr>
<tr>
<td><h:commandButton value="update balance" action="#{eFindUser.process()}" /></td>
</tr>
</table>
</h:panelGroup>
</h:form>
</h:panelGroup>
</ui:define>
</ui:composition>
Backing bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package backingbeans;
import entities.User;
import java.io.Serializable;
import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import stateless.EmployeeFacade;
/**
*
* #author Martin
*/
#ManagedBean(name="eFindUser")
#ViewScoped
public class EFindUserManagedBean implements Serializable{
private static final long serialVersionUID = -7106162864352727534L;
private boolean responseRendered = false;
private boolean notFound = false;
#NotNull
private Long userId;
private User user;
#Inject
private EUpdateBalanceManagedBean updateBalance;
#Inject
private EmployeeFacade employeeFacade;
/**
* Creates a new instance of EFindUserManagedBean
*/
public EFindUserManagedBean() {
}
public void findUser() {
if(new Random().nextDouble() < 0.3) {
notFound = true;
responseRendered = false;
} else {
notFound = false;
responseRendered = true;
user = employeeFacade.getUserById(3L);
}
}
public boolean isResponseRendered() {
return responseRendered;
}
public void setResponseRendered(boolean responseRendered) {
this.responseRendered = responseRendered;
}
public boolean isNotFound() {
return notFound;
}
public void setNotFound(boolean notFound) {
this.notFound = notFound;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
System.out.println("blah");
this.userId = userId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
System.out.println("setting user");
this.user = user;
}
public String process() {
updateBalance.setUser(user);
System.out.println("process");
return "/employee/updateBalance.xhtml?faces-redirect=true";
}
}
When I click the first 'Render!'-labeled button, it works like charm. Second form is loaded and ready to work. When I click the next 'update balance'-labeled button, the page just reloads which it shouldn't, of course. It should redirect to "/employee/updateBalance". Or it should at least call the process method.
Thanks a lot
EDIT: #BalusC is right, the answer is in previous question
The culprit can be found in <h:inputHidden> tag of the second form:
<h:form>
<h:panelGroup layout="block" rendered="#{eFindUser.responseRendered}" >
<h:inputHidden value="#{eFindUser.user}" />
</h:panelGroup>
</h:form>
Most probably its bound value, eFindUser.user is of type User and when you submit that form JSF doesn't know how to assign a string representation of user with a User object.
Hence, there is a conversion error, in which case action method is not called, according to JSF lifecycle. Additionally, you would have known that if you had <h:messages> in your view.
What can be done is the following:
Assign converter to your input like <h:inputHidden value="#{eFindUser.user}" converter="userConverter"/> with a #FacesConverter implemented. More details can be found here.
Bind <h:inputHidden> to a String, so that no converter would be needed: <h:inputHidden value="#{eFindUser.user.userNickname}"> or to an Integer in a similar way.
modify
<h:commandButton value="update balance" action="#{eFindUser.process()}" />
to
<h:commandButton value="update balance" action="#{eFindUser.process}" />
el expression can't contain “()”

Ajax is not working with richfaces

I'm trying to use AJAX to change the content of my page and include some other contents, but it just does not work. I tried a lot of different solutions. I need that my menuItem_Cursos call that managed bean changePage and render the component panelGroup_Target. When i try to debug the java it just doesn't get there. Please help.
This is the page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>PenSAE</title>
<f:metadata>
<f:event listener="#{logon.verificaLogon}" type="preRenderView" />
</f:metadata>
<h:outputScript name="common.js" />
</h:head>
<h:body>
<f:view id="view_Principal">
<rich:toolbar id="toolbar_Principal" itemSeparator="">
<rich:menuItem id="menuItem_Cursos" label="Cursos" mode="ajax"
actionListener="#{principalProfessor.changePage}" render="panelGroup_Target"/>
<rich:menuItem id="menuItem_Estudos" label="Estudos de Casos"
value="Estudos de Casos" />
<rich:dropDownMenu id="dropDownMenu_Acompanhamento"
label="Acompanhamento" value="Acompanhamento" mode="ajax">
<rich:menuItem label="Acompanhamento por Estudante" />
<rich:menuItem label="Acompanhamento por Estudo de Caso" />
</rich:dropDownMenu>
<rich:dropDownMenu id="dropDownMenu_Sobre" label="Sobre o Sistema"
value="Sobre o Sistema">
<rich:menuItem label="Mapa do Software" />
<rich:menuItem label="Ajuda" />
</rich:dropDownMenu>
</rich:toolbar>
<h:panelGroup id="panelGroup_Target">
<rich:panel rendered="#{principalProfessor.page == 'listaCursos'}">
<ui:include src="#{principalProfessor.page}" />
</rich:panel>
</h:panelGroup>
</f:view>
</h:body>
</html>
And this is my java code:
package magicBeans.professor;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import classesBasicas.Curso;
import classesBasicas.Pessoa;
import fachada.Fachada;
/**
* #author Jesus
*
*/
#ManagedBean(name="principalProfessor")
#ViewScoped
public class PrincipalProfessorBean {
#SuppressWarnings("unused")
private static Fachada fachada;
private Pessoa usuarioLogado;
private Curso curso;
private String page = "";
public PrincipalProfessorBean(){
fachada = Fachada.getInstance();
}
/**
* #return the usuarioLogado
*/
public Pessoa getUsuarioLogado() {
return usuarioLogado;
}
/**
* #param usuarioLogado the usuarioLogado to set
*/
public void setUsuarioLogado(Pessoa usuarioLogado) {
this.usuarioLogado = usuarioLogado;
}
/**
* #return the curso
*/
public Curso getCurso() {
return curso;
}
/**
* #param curso the curso to set
*/
public void setCurso(Curso curso) {
this.curso = curso;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public void changePage() {
page = "listaCursos.xhtml";
System.out.println("AJAX PEGOU!");
}
}
Thanks to chrome (ctrl+shift+j) on chrome, the console told that it needed a form around anything with ajax to work. =]

Javascript/Javabean: co-operation not working for counter

I have to make a simple webapplication using javascript and javabeans. The actual assignment is a bit different (including dropcoordinates and such), but here's my testing file problem:
Whenever the red square is clicked, it should add 1 to the value in my javabean and output it to a textfield. It shows it correctly, but then it somehow reverts back to its original value. When I debug, it doesn't even go into my method addUp(). Second problem: when I refresh the page, it DOES go into the method, no matter if I've clicked the square or not.
Here is my code:
Website index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<title>Facelet Title</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</h:head>
<h:body>
<form>
<DIV id="move" style="width:150px;height:150px;background-color:pink;border:1px solid #999999"> </DIV>
<input id="test" value="${countController.counter}" />
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#move").click(function(event, ui){
alert(${countController.counter});
});
$("#droppable").click(function(event, ui){
alert(${countController.counter});
${countController.telOp()};
document.getElementById("test").value = ${countController.counter};
alert(${countController.counter});
//window.location.reload();
});
});
</SCRIPT>
<div id="droppable" style="width:150px;height:150px;background-color:red;border:1px solid #999999">Drop here</div>
</form>
</h:body>
</html>
CountController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* #author Laurent
*/
#ManagedBean
#SessionScoped
public class CountController implements Serializable{
/** Creates a new instance of countController */
public CountController() {
}
private int counter = 0;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void telOp(){
counter++;
}
}
You need to add an event listener in your managed bean such as
buttonClicked(ActionEvent event){
}
and then from the ui, you implement a h:commandLink or h:commandButton to invoke the action event.

Categories

Resources