Passing Parameters from JSF to Applet not working - jsf

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);
}

Related

jsf set errors when i connected to workbench

I'm new to java ee and I'm trying to make my first website using java ee but I find a lot of difficult when i want to connect my jsf to workbench I have also a problem with serialization because i have always to generate the serial of beans manually
this it my beans
Userbean.java
#ManagedBean
#Named /*("userBean")*/
#RequestScoped
public class Userbean implements Serializable{
private static final long serialVersionUID = 1043069413653729199L;
private String iduser="";
private String username="name";
private String password="0000";
private String email="";
private String city="";
private String country="";
public Userbean() {
super();
// TODO Auto-generated constructor stub
}
public Userbean(String iduser, String username, String password, String email, String city, String country) {
super();
this.iduser = iduser;
this.username = username;
this.password = password;
this.email = email;
this.city = city;
this.country = country;
}
public String getIduser() {
return iduser;
}
public void setIduser(String iduser) {
this.iduser = iduser;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String returnAction2() {
PreparedStatement ps;
String query ="INSERT INTO `jee`.`user`( `username`, `email`, `password`, `city`, `country`) VALUES (?,?,?,?,?)";
boolean a=false;
try {
ps= Myconnection.getConnection().prepareStatement(query);
ps.setString(1,username);
ps.setString(2,email);
ps.setString(3,password);
ps.setString(4,city);
ps.setString(5,country);
if(ps.executeUpdate()>0){
a=true;
}
} catch (SQLException ex) {
ex.getStackTrace();
a=false;
}
return a==true ? "success" : "failure";
}
}
this is my view sign up
<!DOCTYPE html>
<html xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<f:view>
<head>
<title>Login screen</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<h1>sign up</h1>
<h:form>
username:
<h:inputText id="username" value="#{userBean.username}" />
<br/>
Password:
<h:inputSecret id="password1" value="#{userBean.password}" />
<br/>
email:
<h:inputSecret id="email" value="#{userBean.email}" />
<br/>
city:
<h:inputSecret id="city" value="#{userBean.city}" />
<br/>
country:
<h:inputSecret id="country" value="#{userBean.country}" />
<br/>
<h:commandButton action="#{userBean.returnAction2}" value="Connect" />
</h:form>
</body>
</f:view>
</html>

Javascript alert in 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?

JSF EL Expressions and Java beans

I have a JSF project and I am trying to create a login page, I have managed to get the username and password from the database and validate them, my project has a Java bean, managed bean and DAO classes, when the user successfully logs in, I would like to print Hello Mr.
< h:outputLabel value="#{mBLogin.user.firstName}" /> the Hello Mr. is printing but the name is not, although when testing my DAO class I'm printing the name to the console without any problem! Can someone advice what I am doing wrong?
My managed bean class:
#ManagedBean
#SessionScoped
public class MBLogin {
User user = new User();
LoginDAO loginDao = new LoginDAO();
public String validteStudent() {
boolean valid = loginDao.validateStudent(user.getUserId(), user.getPassword());
if (valid) {
user.getFirstName();
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
return "admin";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd", "Please enter correct username and Password"));
return "login";
}
}
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
My Java Bean class:
#Table(name = "students_info")
public class User {
#Column(name = "std_record_id")
private int id;
#Column(name = "std_id")
private String userId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "web_password")
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My DAO class :
public class LoginDAO {
static JKPlainDataAccess dataAccess = JKDataSourceFactory.getPlainDataAccess();
User user;
public boolean validateStudent(String userName, String password) {
user = dataAccess.executeQueryAsSingleObject(User.class, "id,userId,firstName,lastName,password",
"SELECT std_record_id, std_id, first_name, family_name, web_password From students_info WHERE std_id=? and web_password=?",
userName, password);
JK.print("getAllEmployeeRecords() : ", user);
if(user != null) {
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
return true;
}
return false;
}
public static void main(String[] args) {
LoginDAO a = new LoginDAO();
a.validateStudent("200663042001", "1234");
}
}
my xhtml page after the login page:
<ui:composition template="/WEB-INF/layouts/default.xhtml">
<ui:define name="content">
WELCOME Mr. <h:outputLabel value="#{mBLogin.user.firstName}" />
AND <h:outputLabel value="#{mBLogin.user.lastName}" />
</ui:define>
</ui:composition>
When validating, you seem to put the user as the session attribute without assigning it to the Managed Bean field:
session.setAttribute("username", user);
So either assign it also to the instance user variable or simply use:
<ui:composition template="/WEB-INF/layouts/default.xhtml">
<ui:define name="content">
WELCOME Mr. <h:outputLabel value="#{username.firstName}" />
AND <h:outputLabel value="#{username.lastName}" />
</ui:define>
</ui:composition>
Update
I would suggest changing your service method to:
public User validateStudent(..)
where you actually return the queried user instead of setting it in the DAO..
And thus you would change the ManagedBean method to:
public String validteStudent() {
User validatedUser = loginDao.validateStudent(user.getUserId(), user.getPassword());
if (validatedUser != null) {
this.user = validatedUser;
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
....

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***

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