Javascript alert in JSF - jsf

I have a method called bilgidorumu() in a managed bean class to check input. If there is a match with database (username and password), the application should go to the welcome page anasayfa.xhtml, else, it stays at the same page (index.xhtml). My problem is that I want to show an alert before staying on the same page (index.xhtml). So if there is no match for username/password, it should display an alert first, and stays then at index.xhtml. But I have no idea how to do that because Javascript runs on client side and Java code in server side. I have tried to display the alert with onclick event but it's not working:
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
My input elements to reach via JS function:
<h:inputText id="username" value="#{kntrl.kulad}"
pt:placeholder="username" required="true"
requiredMessage="Kullanıcı adı girilmesi zorunlu"/> <h:inputSecret
id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password"
required="true" requiredMessage="Şifre girilmesi zorunlu"/>
JS function:
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
index.xhtml:
<div class="login-page">
<div class="form">
<h:form class="register-form">
<h:inputText pt:placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</h:form>
<h:form class="login-form">
<h:inputText id="username" value="#{kntrl.kulad}" pt:placeholder="username" required="true" requiredMessage="Kullanıcı adı girilmesi zorunlu"/>
<h:message for="username" style="color: red"></h:message>
<h:inputSecret id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password" required="true" requiredMessage="Şifre girilmesi zorunlu"/>
<h:message for="pw" style="color: red; " ></h:message>
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
<p class="message">Not registered? Create an account</p>
</h:form>
</div>
</div>
<f:verbatim>
<script type="text/javascript">
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
</script>
</f:verbatim>
Managed bean:
#ManagedBean(name = "kntrl")
#RequestScoped
public class kontrolet {
private int id;
private String adsoyad;
private String birim;
private String bolum;
private String unvan;
private int puan;
private String kulad;
private String kulsifre;
public kontrolet() {
}
public String bilgidorumu() throws ScriptException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/akademiktesvik", "root", "");
String query = "Select * from kisiler";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
if (rs.getString("kulad").equals(kulad) && rs.getString("kulsifre").equals(kulsifre)) {
return "anasayfa?faces-redirect=true";
}
}
} catch (Exception e) {
System.out.println("Baglanti kuurulmadı hata var" + e.getMessage());
}
return "index";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdsoyad() {
return adsoyad;
}
public void setAdsoyad(String adsoyad) {
this.adsoyad = adsoyad;
}
public String getBirim() {
return birim;
}
public void setBirim(String birim) {
this.birim = birim;
}
public String getBolum() {
return bolum;
}
public void setBolum(String bolum) {
this.bolum = bolum;
}
public String getUnvan() {
return unvan;
}
public void setUnvan(String unvan) {
this.unvan = unvan;
}
public int getPuan() {
return puan;
}
public void setPuan(int puan) {
this.puan = puan;
}
public String getKulad() {
return kulad;
}
public void setKulad(String kulad) {
this.kulad = kulad;
}
public String getKulsifre() {
return kulsifre;
}
public void setKulsifre(String kulsifre) {
this.kulsifre = kulsifre;
}
}

I would not recommend to use a JavaScript alert to do so. But, if you really want to, your question would be a duplicate of:
Calling a JavaScript function from managed bean
I would suggest to simply set a message when the username and password do not match and indicate that the validation failed:
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Your message",
"Message details");
context.addMessage(null, message);
context.validationFailed();
Note the null in addMessage, this means we don't set a client ID to the message. This makes the message global. To display it on your page, simply use:
<h:messages globalOnly="true"/>
See also:
How to display my application's errors in JSF?

Related

How to get file upload path location for database by setter and getter in jsf

I m having trouble to set value for entity bean. the problem is that when i populate form file will be upload but i need file path to store in data base. In my bean i have used setter of employee entity to set file url but And I think the code is enough to set file path for database but data is storing on database leaving employeePicture as null..
#Named
#RequestScoped
public class EmployeeAddController {
private Employees employees;
private String fileNameForDataBase;
private Part file;
#Inject
private EmployeeUpdateService updateService;
#PostConstruct
public void init() {
employees = new Employees();
}
public Employees getEmployees() {
return employees;
}
public void setEmployees(Employees employees) {
this.employees = employees;
}
public String getFileNameForDataBase() {
return fileNameForDataBase;
}
public void setFileNameForDataBase(String fileNameForDataBase) {
this.fileNameForDataBase = fileNameForDataBase;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
public void upload() throws IOException {
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String realPath = ctx.getRealPath("/");
int random =(int) (Math.random() * 10000 + 1);
String fileString= realPath + File.separator + "resources/image/employee"+random+".jpg";
employees.setEmployeePicture(fileString);
try (InputStream input = file.getInputStream()) {
Files.copy(input, new File(fileString).toPath());
}
}
public String addEmployee() {
try {
this.updateService.add(employees);
return "index?faces-redirect=true";
} catch (Exception e) {
return null;
}
}
}
in My jsf page
"<div class="form-group">
<h:outputText value=" Employee Picture" class="col-sm-3 control-label"/>
<div class="col-sm-9">
<h:inputFile value="#{employeeAddController.file}">
<f:ajax listener="#{employeeAddController.upload()}"/>
</h:inputFile>
<h:outputText value="#{employeeAddController.fileNameForDataBase}"/>
</div>
<div>
<h:message for="fileUpload" class="text-primary"/>
</div>
</div>"***strong text***

action p:command button doesn't set property into managed bean [duplicate]

This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 7 years ago.
I have an issue, I have a carousel, and I load dynamically some data into it, when I press into a carousel object it have to set a value into a manangedbean (CurrentSong) and show a dialog, now the dialog appear but the set property doesn't work. why?
xhtml page:
<h:body style="background: url(../resources/images/knapsack_background_light.jpg); background-attachment:fixed;">
<div id="contentContainer" class="trans3d">
<section id="carouselContainer" class="trans3d">
<ui:repeat value="#{retrieve.mostPopularSongs}" var="carouselSelectedSong">
<figure id="item" class="carouselItem">
<div class="itemInfo">
<h:commandButton id="selectedButton"
action="#{currentSong.setSong(carouselSelectedSong)}"
styleClass="btn"
onclick="parent.showSongDialog();"
style="
background-image: url('#{carouselSelectedSong.coverPath}');
background-size:100%;
width:300px;
height:300px;
border: black;">
<f:ajax render="songDialogContent"/>
</h:commandButton>
</div>
</figure>
</ui:repeat>
</section>
</div>
managed bean #ManagedBean #SessionScoped:
public class CurrentSong implements Serializable {
#EJB
private CustomerManagementLocal customerManagement;
#EJB
private SocialManagementLocal socialManagement;
private Customer customer;
private Song song;
private String textComment;
public CurrentSong() {
}
public Customer getCustomer() {
return customer;
}
public Song getSong() {
return song;
}
public void setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
}
public void putLike () {
putValutation(true);
}
public void putDislike () {
putValutation(false);
}
public String getTextComment() {
return textComment;
}
public void setTextComment(String textComment) {
this.textComment = textComment;
}
public void putComment () {
FacesContext context = FacesContext.getCurrentInstance();
try {
Comment newComment = new Comment(customer, new Date(), textComment, song);
song.getCommentList().add(newComment);
socialManagement.putComment(newComment);
Notifier.notifyInfoMessage(context, Constants.INSERTION_COMMENT_SUCCESSFULLY);
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("clearTextComment();");
} catch (CustomerNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
} catch (SongNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
}
}
private void putValutation (boolean valutation) {
FacesContext context = FacesContext.getCurrentInstance();
try {
socialManagement.putValutation(new LikeValutation(customer, song, valutation, new Date()));
Notifier.notifyInfoMessage(context, Constants.INSERTION_VALUTATION_SUCCESSFULLY);
} catch (CustomerNotFoundException | SongNotFoundException ex) {
Notifier.notifyErrorMessage(context, Constants.INTERNAL_ERROR);
}
}
#PostConstruct
public void init() {
customer = customerManagement.getCurrentCustomer();
}
}
thanks!
Define one selectedSong variable in your managed bean with getters and setters.
Use JSF setPropertyActionListener similar to below code.
Remove the argument from your action method.
<h:commandButton id="selectedButton"
action="#{currentSong.setSong()}"
styleClass="btn"
onclick="parent.showSongDialog();"
style="
background-image: url('#{carouselSelectedSong.coverPath}');
background-size:100%;
width:300px;
height:300px;
border: black;">
<f:ajax render="songDialogContent"/>
<f:setPropertyActionListener target="#{currrentSong.selectedSong}" value="#{carouselSelectedSong}" />
</h:commandButton>
Assign the selectedSong to carouselSelectedSong in your managed bean action class
private Song selectedSong;
//getters and setters for selectedSong
public String setSong() {
System.out.println("----------------------------------------- current song: " + selectedSong.getTitle());
this.song = selectedSong;
return null;
}
I think the method setSong is not executed, that is the problem.
public void setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
}
Normally the action method expects the method should return the String return value. Can you change the method definition like below code then it will work
public String setSong(Song song) {
System.out.println("----------------------------------------- current song: " + song.getTitle());
this.song = song;
return null;
}

Passing Parameters from JSF to Applet not working

I am working on a project where I am trying to pass parameters to an applet from JSF. The values (username and roleid) which are being passed as parameters, are fetched from the managed been(loginform). I have an issue with passing these parameters since I get no values in the applet but when I output the values in my web page (for testing purposes), I can clearly see these values. When I hard code the parameter values, I can successfully get the values in the applet, but when I use the values from the manged bean, I get an empty string from the applet. How is this caused and how can I solve it?
View:
<p:idleMonitor onidle="#{loginform.loggout()}" timeout="60000" />
<div id="header">
<div class="pull-left">
Welcome: #{loginform.uname} My Role Id:#{loginform.roleid}
<span style="margin-left:200px;line-height: 10px;">
<h:outputLabel value= "Welcome: #{loginform.uname}" /></span>
</div>
<div class="pull-right">
<h:form>
<h:commandButton class="btn btn-inverse" value="Log Out" action="#
{loginform.loggout()}"/>
</h:form>
</div>
</div>
<APPLET height="900" width="100%" codebase="."
code="finatriall.safe.pro.FinalJApplet.class"
archive="FinalJapplet.jar" >
<param name="username" value="#{loginform.uname}"/>
<param name="role_id" value="loginform.roleid" />
</APPLET>
<!--The section Welcome: #{loginform.uname} My Role Id:#
{loginform.roleid} is used for checking whether values are
successfully returned from the bean-->
Model:
#ManagedBean(name="loginform", eager = true)
#SessionScoped
public class Login {
boolean isLoggedIn;
DBConnection dbcon=new DBConnection();
String username, password;
ArrayList<String> details;
String uname, pwd, message,roleid;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public String userLogin(){
String path="";
details=dbcon.loginFunction(username, password);
if(details!=null){
FacesContext.getCurrentInstance().addMessage(null, new
FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", "Login
successful."));
uname=details.get(0);
roleid=details.get(2);
System.out.println("username "+uname);
System.out.println("roleid "+roleid);
path= "/main.xhtml?faces-redirect=true";//Path to launch the
main.xhtml that
contains <>Applet tag>
isLoggedIn=true;
System.out.println("Welcome");
}
else{
System.out.println("Wrong details");
FacesContext.getCurrentInstance().addMessage(null, new
FacesMessage(FacesMessage.SEVERITY_ERROR, "Wrong Credentials",
"User not found."));
path="";
}
return path;
}
public String loggout()
{
FacesContext ctx=FacesContext.getCurrentInstance();
HttpSession sess=
(HttpSession)ctx.getExternalContext().getSession(false);
sess.invalidate();
isLoggedIn=false;
return "/index.xhtml?faces-redirect=true";
}
Applet:
public void init() {
// changeTheme();
jDesktopPane1 = new JDesktopPane();
jDesktopPane1.setBackground(Color.white);
String username=getParameter("separate_jvm");
String roleid = getParameter("role_id");
System.out.println("Role Id: "+roleid);
System.out.println("Username: "+username);
}

apply request phase not being called

I am running the duke guess number example , I don't see the life cycle executing as expected. I have an inputText which expects a number. We also have a converter and a validator. Once I submit the <h:form> the validator is called. It should check the input if it is an integer. The value is not getting updated on the managed bean property. Please explain, below is the code snippet.
<h:inputText id="userNo" label="User Number" value="#{UserNumberBean.userNumber}"
converterMessage="#{ErrMsg.userNoConvert}" validator="#{UserNumberBean.validate}">
<f:valueChangeListener type="#{UserNumberBean.valueChange()}"></f:valueChangeListener>
<f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" />
</h:inputText>
here the validator method is set in inputText component.
Once I submit the <h:form>, the validate method is called, below is the method
public String validate(javax.faces.context.FacesContext fc, javax.faces.component.UIComponent ui, java.lang.Object o){
System.out.println("in my own validation method");
if(userNumber ==8){
return "validation";
}
return "validation";
}
here userNumber is the backing bean property of the class
public class UserNumberBean {
public Integer userNumber = null;
public void setUserNumber(Integer user_number) {
System.out.println("setting userName" + user_number);
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
}
it has getters and setter but still userNumber value is not set. I get NullPointerException in validator method when accessing userNumber. Please let me know what is wrong. Below is the code snippet
<HTML xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<HEAD> <title>Hello</title> </HEAD>
<%# page contentType="application/xhtml+xml" %>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<body bgcolor="white">
<f:view>
<h:form id="helloForm" >
<h2>Hi. My name is Duke. I'm thinking of a number Man from
<h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to
<h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess
it?</h2>
<h:graphicImage id="waveImg" url="/wave.med.gif" alt="Duke waving" />
<h:inputText id="userNo" label="User Number" value="#{UserNumberBean.userNumber}"
converterMessage="#{ErrMsg.userNoConvert}" validator="#{UserNumberBean.validate}">
<f:valueChangeListener type="#{UserNumberBean.valueChange()}"></f:valueChangeListener>
<f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" />
</h:inputText>
<h:commandButton id="submit" action="success" value="Submit" />
<p>
<h:message style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
</p>
</h:form>
</f:view>
</body>
</HTML>
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.LongRangeValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.util.Random;
public class UserNumberBean {
Integer randomInt = null;
public Integer userNumber = null;
String response = null;
private boolean maximumSet = false;
private boolean minimumSet = false;
private long maximum = 0;
private long minimum = 0;
public UserNumberBean() {
System.out.println(" in constructor");
Random randomGR = new Random();
randomInt = new Integer(randomGR.nextInt(10));
System.out.println("Duke's number: " + randomInt);
}
public void setUserNumber(Integer user_number) {
System.out.println("setting userName" + user_number);
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
public String getResponse() {
System.out.println(" in getResponse");
if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0)) {
return "Yay! You got it!";
} else {
return "Sorry, " + userNumber + " is incorrect.";
}
}
public long getMaximum() {
return (this.maximum);
}
public void setMaximum(long maximum) {
this.maximum = maximum;
this.maximumSet = true;
}
public long getMinimum() {
return (this.minimum);
}
public void setMinimum(long minimum) {
this.minimum = minimum;
this.minimumSet = true;
}
public String validate(javax.faces.context.FacesContext fc, javax.faces.component.UIComponent ui, java.lang.Object o){
System.out.println("in my own validation method");
if(userNumber ==8){
return "validation";
}
return "validation";
}
public void valueChange(){
System.out.println(" in value change");
}
}
What actually is the Apply Request phase? What happens in Apply Request phase? How different is it from Update Model Values phase
Your validator is broken in 2 ways:
Wrong method signature. It should return void. On validation faliures, you should be throwing a ValidatorException. On success you should just be returning and doing nothing additional.
You should be validating the value provided as 3rd argument, not the model value (which isn't been set at that point at all).
So, this should do:
public void validate(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return; // Ignore it. Let required="true" handle.
}
if (value != 8) {
// Assuming that 8 is the guess number?
throw new ValidatorException(new FacesMessage("Wrong guess, try again."));
}
}
Your NullPointerException is caused because you're attempting to compare the model value userNumber to a primitive integer 8. This causes autoboxing to try to unbox userNumber to a primitive, however that fails if the userNumber itself is null which cannot be represented in any primitive form.
As to the phases, the apply request values phase is definitely called, the validations phase is otherwise never called. You seem to expect that the apply request values phase updates the model values. This is not true, it applies the request parameters on JSF input component's submittedValue.
See also:
Difference between Apply Request Values and Update Model Values
Debug JSF lifecycle

Passing parameters between managedbeans primefaces

I have a problem with my managedbeans. I cannot manage to pass parameters between them. Here is an XHTML snippet. It is basically a form for login. It just sends the parameters to back bean.
<h:outputLabel for="username" value="Kullanıcı Adı: *" />
<p:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Kullanıcı adı giriniz.">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="username" display="icon"/>
<h:outputLabel for="password" value="Şifre: *" />
<p:inputText id="password" value="#{loginBean.password}" required="true" requiredMessage="Şifreyi giriniz!" type="password">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="password" id="msgPass" display="icon"/>
<f:facet name="footer">
<center>
<p:commandButton id="submit" value="Giriş" icon="ui-icon-check" action="#{loginBean.check}" style="margin:0" update="grid"/>
</center>
</f:facet>
In my backing bean, I am checking whether the user input matches with the database record. If so then I let him enter the system. At the same time, I am taking his full name.
My backbean:
#ManagedBean
#RequestScoped
public class LoginBean {
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMgs() {
return mgs;
}
public void setMgs(String mgs) {
this.mgs = mgs;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getOriginalURL() {
return originalURL;
}
public void setOriginalURL(String originalURL) {
this.originalURL = originalURL;
}
private String username;
private String password;
private String mgs;
private String fullname;
private String originalURL;
private static Logger log = Logger.getLogger(LoginBean.class.getName());
public String check() throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/projetakip", "root", "");
Statement stmt = con.createStatement();
String md5Pass = md5(password);
String SQL = "select * from users where username='" + username + "' and password='" + md5Pass + "'";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
if (username.matches(rs.getString("username")) && md5Pass.matches(rs.getString("password"))) {
this.fullname = rs.getString("ad") + " " + rs.getString("soyad");
return "panel?faces-redirect=true";
} else {
FacesMessage msg = new FacesMessage("Yanlış kullanıcı adı/şifre.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "index?faces-redirect=true";
}
}
return "index?faces-redirect=true";
}
public void getProductSetupData(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Data data = context.getApplication().evaluateExpressionGet(context, "#{data}", Data.class);
}
What I want is to pass fullName to other beans (or pages). How can I pass this variable between my beans?
Thanks in advance.
BalusC wrote a whole blog post about communication in JSF 2.0, it is truly worthy of your time. Reading it, you will discover that there are more than one way of doing it, one of them being injecting the property itself, in your other beans:
#ManagedProperty("#{loginBean.fullName}")
private String fullName;
And another, perhaps more appropriate, could be to inject the bean itself:
#ManagedProperty("#{loginBean}")
private LoginBean loginBean;

Resources