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.
Related
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>
I'm having trouble understanding why a action method on my ConversationScope'd bean doesnt fire. The bean is:
package org.work;
import java.io.Serializable;
import javax.enterprise.context.ConversationScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Named;
#Named
#ConversationScoped
public class NewClass implements Serializable {
private static final long serialVersionUID = 6470665657635110586L;
private boolean b1;
public boolean isB1() {
return b1;
}
public void setB1(boolean b1) {
this.b1 = b1;
}
public void preRenderView(ComponentSystemEvent evt) {
}
public String peformAction() {
return null;
}
}
and my XHTML is:
<?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">
<f:view>
<h:head>
</h:head>
<f:metadata>
<f:viewParam name="b1"
value="#{newClass.b1}" />
<f:event type="preRenderView"
listener="#{newClass.preRenderView}"/>
</f:metadata>
<h:body>
<h:form>
<h:commandLink action="#{newClass.setB1(!newClass.b1)}"
style="background-color: #{newClass.b1 ? 'darkorchid' : 'aquamarine'};"
value="btn3"/>
<h:panelGrid rendered="#{newClass.b1}"
columns="1">
<h:commandLink value="edit"
action="#{newClass.peformAction()}" />
</h:panelGrid>
</h:form>
</h:body>
</f:view>
</html>
The performAction() method is not fired after I press the commandLink that should invert the boolean making the other commandLink rendered. When debugging I can see that the boolean is set to true, but it seems to me the "rendered" attribute is evaluated before the viewparams is set. Is this true?
The example works fine with #ManagedBean and #javax.faces.bean.ViewScoped.
I think that you don't have long-running conversation. You could read more information on this site: http://docs.oracle.com/javaee/6/api/javax/enterprise/context/ConversationScoped.html
If you have transient conversation this bean is recreated after every request
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.
I have a very simple xhtml file where a panelGroup containing a commandButton is added to the page on clicking toggle button but this dynamically added commandButton fails to execute its actionlistener on being clicked.
Complete code below:
<?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:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:panelGroup id="checkDyna">
<h:panelGroup rendered="#{listRetriever.booleanStatus}" >
<h:form>
<p:commandButton value="check" process="#all" actionListener="#{listRetriever.xx()}"/>
</h:form>
</h:panelGroup>
</h:panelGroup>
<h:form>
<p:commandButton value="Toggle" actionListener="#{listRetriever.toggleBooleanStatus()}" update=":checkDyna"/>
</h:form>
</h:body>
</html>
Bean
#ManagedBean(name = "listRetriever")
#RequestScoped
public class ListRetriever implements Serializable {
private boolean booleanStatus;
public void toggleBooleanStatus(){
if (!booleanStatus)
booleanStatus=true;
}
public void xx(){
System.out.println("Invoked***");
}
public boolean isBooleanStatus() {
return booleanStatus;
}
public void setBooleanStatus(boolean booleanStatus) {
this.booleanStatus = booleanStatus;
}
}
On removing rendered="#{listRetriever.booleanStatus}" actionlistener is successfully invoked.
On making the bean ViewScoped too the problem is eliminated but I dont want to make it wider than RequestScoped.
I had this p:commandButton within a conditionally rendered panel whose conditional expression for rendering was evaluating to false while I was trying to execute the actionlistener. This was the cause of actionlistener not getting executed.
Started learning Wicket after ASP.NET MVC and feel a little bit confused about managing its URLs. Here's the code:
Application:
package com.test.wicketapp1;
import org.apache.wicket.protocol.http.WebApplication;
public class WicketApplication extends WebApplication {
public WicketApplication() {
mountPage("/page1", HomePage.class);
mountPage("/page2", Page2.class);
}
#Override public Class<HomePage> getHomePage() {
return HomePage.class;
}
}
HomePage:
package com.test.wicketapp1;
import java.io.IOException;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.WebPage;
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) throws IOException {
BookmarkablePageLink<Page2> bookmarkablePageLink = new BookmarkablePageLink<Page2>("gopage2link", Page2.class);
add(bookmarkablePageLink);
}
}
HomePage markup:
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<title>Apache Wicket Quickstart</title>
</head>
<body>
go page 2
</body>
</html>
What I wanted to have is pretty simple. I expected that there would be 2 urls: "/page1" for HomePage.class and "/page2" for Page2.class, then my HomePage has a link that navigates to Page2 and when HomePage is rendered, that link should have an URL of "/page2".
When I run the application and go to home page, it is rendered like this:
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<title>Apache Wicket Quickstart</title>
</head>
<body>
go page 2
</body>
</html>
I expected to have something like:
go page 2
instead. What did I miss?
The problem is - I should use app's init method instead of ctor to define the mappings.
have a look at this. It might help
https://cwiki.apache.org/WICKET/request-mapping.html