This is my login page
<h:outputText value="ENTER USERNAME" ></h:outputText>
<p:inputText value="#{treeBean.username}" id="user"></p:inputText>
<h:outputText value="ENTER PASSWORD" ></h:outputText>
<p:inputText value="#{treeBean.userpass}" id="pass"></p:inputText>
<p:commandButton value="GO" action="#{treeBean.checkuser}" onclick="redirect()"></p:commandButton>
<script type="text/javascript">
function redirect()
{
window.location="/arcpage/arc.jsf";
}
</script>
this is my treeBean.checkuser function
public void checkuser()
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "root");
try
{
st.executeUpdate("USE ARCPAGE");
String update="SELECT * FROM USER WHERE USER_NAME=? AND USER_PASS=?";
PreparedStatement prest=con.prepareStatement(update);
prest.setString(1,username);
prest.setString(2,userpass);
ResultSet rs=prest.executeQuery();
if(rs.next()==false)
{
check="false";
}
else
{
check="true";
}
}}}
This is My main page:
<script type="text/javascript">
if(check!="true")
{
window.location="/arcpage/login.jsf";
}
</script>
<Main Page Content>
If I type the correct username-pass combination I am redirected to the login page instead of the main page. If I enter the correct combination again I am redirected to the main page. Even if I enter a wrong combination the second time I am redirected to the main page. I think the main page is being executed first and then the checkuser() is being executed so the value of check is not updated before the main page is displayed.
Why is this happening?
That’s because you added some JavaScript function to the
onclickwhich does the redirect. This is invoked when the user clicks the button. This in turn causes the JSF action being completely skipped. You also seem to be thinking that JSF and JavaScript runs in sync somehow. This is untrue. It are two completely distinct languages. JSF runs in webserver only, produces HTML/CSS/JS code and sends it to webbrowser. JS runs in webbrowser and intercepts on HTML DOM tree only.To fix the problem, just remove the
onclickand do the navigation in JSF action method. So:with