I am trying to perform the programmatic form based authentication and it seems that
My web.xml:
<web-app>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>confirmauthentication.xhtml</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<security-constraint>
<display-name>Authentication Ex Login</display-name>
<web-resource-collection>
<web-resource-name>SecuredArea</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>mysqldomain</realm-name>
<form-login-config>
<form-login-page>/authentication.xhtml</form-login-page>
<form-error-page>/error.xhtml</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description/>
<role-name>*</role-name>
</security-role>
</web-app>
My jsf page called authentication.xhtml:
<h:form>
<h:panelGrid border="0" columns="2">
<h:outputText value="Username"/>
<h:inputText value="#{beanJSF.userName}" required="true" />
<h:outputText value="Password"/>
<h:inputSecret value="#{beanJSF.password}" required="true" />
<h:commandButton value="Log in" action="#{beanJSF.submit}">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
<h:messages />
</h:panelGrid>
</h:form>
It seems that when I press the “Log in” button, the submit method is not called and I can’t figure out the reason. The server.log doesn’t display anything when I press the button (This message is not displayed “("I am in the login method!!!!!!!!...”).
My ManagedBean:
#URLMappings(mappings={
#URLMapping(id="success", pattern = "/authentication/", viewId = "/confirmauthentication.jsf")})
public class BeanJSF implements Serializable {
private String password;
private String userName;
// User is the Entity
private User loggedUser;
#EJB
UserEJB services;
public String submit() throws IOException {
System.out.println("I am in the login method!!!!!!!! " + getUserName()+ " " + getPassword());
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
request.login(userName, password);
User user = services.authenticationUser(userName, password);
this.setLoggedUser(user);
return "home?faces-redirect-true";
} catch (ServletException e) {
// Handle unknown username/password in request.login().
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Unknown login", null));
return null;
}
}
public void logout() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath() + "/authentication.xhtml");
}
//+ setters and getters for username, password and loggedUser
}
And my EJB is:
#Stateless
public class UserEJB{
#PersistenceContext(unitName = "PyPersistenceUnit")
private EntityManager entityManager;
public UserEJB(){}
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public User authenticationUser(String userName, String password){
try{
User user = entityManager.createNamedQuery(User.FIND_USER,User.class). setParameter("userName", userName).setParameter("password", password).getSingleResult();
return user;
}
catch(NonUniqueResultException ex){
ex.printStackTrace();
return null;
}
catch(NoResultException ex){
ex.printStackTrace();
return null;
}
}
Your bean is not managed by JSF and hence JSF is not able to find the bean anywhere.
Add the JSF bean management annotations to the class.
#ManagedBean
#RequestScoped
public class BeanJSF implements Serializable {
// ...
}
Related
I'm developing an application in JSF 2.0 and also using the Primefaces component library. But, I'm facing problem with p:fileUpload component of the Primefaces Library. I'm basically trying to achieve the following things.
The user uploads the .xls file and after hitting on Upload button
the file should get saved to a temporary location in the disk.
Next, when the submit button is clicked the saved file would be read
line-by-line using Apache POI and saved to the database.
However, the file disappears once the Upload button button is clicked. Being new in JSF/Primefaces, I couldn't exactly figure out where I'm heading towards?
The worst part is no error message is received and I can see that all the phases of JSF-lifecycle is getting executed. Any help would be much appreciated !!! Below is my code
index.html
<h:body>
<h:form prependId="false" enctype="multipart/form-data" id="welcomeForm" style="width:800px">
<h4 style="color:red; font-family:Arial"><h:outputLabel value="Upload your file:" /></h4>
<p:growl id="growl" showDetail="true" />
<p:fileUpload fileUploadListener="#{fileUploadBean.handleFileUpload}"
mode="advanced"
dragDropSupport="false"
sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(xls|xlsx|docx|doc)$/"
update="growl"
/>
<p:separator/>
<p:commandButton value="Submit" actionListener="#{fileUploadBean.growlMessage}" update="growl" />
<h:message for="welcomeForm" />
</h:form>
FileUploadBean.java
public class FileUploadBean implements Serializable {
private static final long serialVersionUID = 1L;
private String message;
private UploadedFile uploadedFile;
private String myFileName;
public FileUploadBean(){
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
public void growlMessage(){
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Your " + myFileName +"was uploaded successfully") ); }
public void handleFileUpload(FileUploadEvent event) throws IOException {
System.out.println("Reached here:::::");
String name = uploadedFile.getFileName();
System.out.println("File name: " + name);
String type = uploadedFile.getContentType();
System.out.println("File type: " + type);
long size = uploadedFile.getSize();
System.out.println("File size: " + size);
Path folder = Paths.get("C:/Windows/Temp");
String filename = FilenameUtils.getBaseName(uploadedFile.getFileName());
String extension = FilenameUtils.getExtension(uploadedFile.getFileName());
Path file = Files.createTempFile(folder, filename + "-", "." + extension);
try (InputStream input = uploadedFile.getInputstream()) {
Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
}
System.out.println("Uploaded file successfully saved in " + file);
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
System.out.println("last line of file upload....");
}
public String save() throws IOException {
System.out.println("Uploaded file value ::::"+uploadedFile);
if(uploadedFile != null) {
FacesMessage message = new FacesMessage("Succesful", uploadedFile.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
else{
/*String filename = FilenameUtils.getName(e.getFile().getFileName());
System.out.println("Filename is :::: " +filename);*/
System.out.println("Uploaded File Name Is :: "+uploadedFile.getFileName()+" :: Uploaded File Size :: "+uploadedFile.getSize());
System.out.println("FAILED !!!!! FAILED !!!!! FAILED !!!!!");
}
return "true";
}
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>file_uploading</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native|commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>51200</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>C:\Windows\Temp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
When i use f:selectItems to display a List<Bean> in a view, does not display the value on itemLabel. Also, doesnt get the id on itemValue.
I want to display only the itemLabel on selectItems.
But, show this :
ID=1, Descricao=Livro
instead of :
Livro
what am I doing wrong? Any ideas?
I have a f:selectItems as follow:
<h:panelGrid columns="2">
<h:outputText value="TIPO:"/>
<p:selectOneMenu value="#{publicacaoMB.publicacao.tipo}">
<f:selectItems value="#{tipoMB.listTipos}" var="tipo"
itemLabel="#{tipo.descricao}" itemValue="#{tipo.tipoId}"/>
</p:selectOneMenu>
</h:panelGrid>
And a ManagedBean :
#ManagedBean
#SessionScoped
public class TipoMB extends ManagedBeanBasico implements Serializable{
private static final long serialVersionUID = 2482494734070978599L;
#ManagedProperty(name = "tipoFacade", value = "#{tipoFacade}")
private TipoFacade tipoFacade;
private List<Tipo> listTipos;
private Tipo tipo;
public List<Tipo> getListTipos() {
try {
listTipos = tipoFacade.getTodosTipos();
} catch (DAOException e) {
e.printStackTrace();
}
return listTipos;
}
And a Facade:
public class TipoFacadeImpl implements TipoFacade, Serializable {
private static final long serialVersionUID = -8560527136998650945L;
#ManagedProperty(name="tipoDAO", value="#{tipoDAO}")
private TipoDAO tipoDAO;
private List<Tipo> listTipos;
public List<Tipo> getTodosTipos() throws DAOException {
if(listTipos == null) {
listTipos = tipoDAO.getTodosTipos();
}
return listTipos;
}
And a DAO:
public class TipoDAOImpl extends NamedParameterJdbcDaoSupport implements TipoDAO, Serializable {
private static final long serialVersionUID = 8698127647660788120L;
private SimpleJdbcInsert sji;
#Value("#{queries.sql03}")
private String sql03;
public List<Tipo> getTodosTipos() throws DAOException {
try {
RowMapper<Tipo> mapper = getRowMapper();
return getJdbcTemplate().query(this.sql03, mapper);
} catch (EmptyResultDataAccessException ex) {
throw new DAOException("Não há registros na tabela de tipos.");
} catch (DataAccessException e) {
throw new DAOException(e.getMessage());
}
}
private RowMapper<Tipo> getRowMapper() {
RowMapper<Tipo> mapper = new RowMapper<Tipo>() {
public Tipo mapRow(ResultSet rs, int rowNum) throws SQLException {
Tipo t = new Tipo();
t.setTipoId(rs.getInt("tipo_id"));
t.setDescricao(rs.getString("descricao"));
return t;
}
};
return mapper;
Also a web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SdiInventario</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_BUFFER_SIZE</param-name>
<param-value>65535</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>smoothness</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
After I integrated spring security into vaadin there of course appeared a need to redirect user after successfull authentication.
I integrated spring security using two servlets - one for vaadin and another - for spring security.
Here my web.xml
<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/pmc-web-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>another-pmc-servlet</servlet-name>
<servlet-class>ru.xpoft.vaadin.SpringVaadinServlet</servlet-class>
<init-param>
<param-name>beanName</param-name>
<param-value>pmcVaadin</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>another-pmc-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<servlet>
<servlet-name>login-pmc-servlet</servlet-name>
<servlet-class>ru.xpoft.vaadin.SpringVaadinServlet</servlet-class>
<init-param>
<param-name>beanName</param-name>
<param-value>loginVaadin</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>login-pmc-servlet</servlet-name>
<url-pattern>/login/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
My security context looks like this
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER"/>
<form-login login-page="/login/" default-target-url="/*" authentication-failure-url="/login/?login_error=true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="pass" authorities="ROLE_USER"/>
<user name="admin" password="admin" authorities="ROLE_ADMIN, ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
On my loginUI(bean name loginVaadin) page there is a login form
public class LoginForm extends Window {
private TextField login;
private TextField password;
private Button enter;
private HorizontalLayout buttonLayout;
private FormLayout formLayout;
private Image facebookIcon;
#Override
public void attach() {
setCaption(StringValues.LOGIN_FORM_CAPTION);
setSizeUndefined();
setResizable(false);
setModal(true);
setContent(createLayout());
super.attach();
}
private FormLayout createLayout() {
login = new TextField("Login");
password = new TextField("Password");
enter = new Button("Enter(close)");
final LoginUi ui = (LoginUi) LoginUi.getCurrent();
enter.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
String loginValue = login.getValue();
String passwordValue = password.getValue();
AuthenticationService authenticationService = ui.getAuthenticationService();
String result = authenticationService.authorize(loginValue, passwordValue);
if (StringUtils.isBlank(result)) {
LoginForm.this.close();
}
ui.getPage().setLocation("localhost:8080/pmc-web/");
}
});
buttonLayout = new HorizontalLayout();
String pathToFile = VaadinService.getCurrent().getBaseDirectory()
.getAbsolutePath() + "\\WEB-INF\\images\\facebook_icon.png";
FileResource resource = new FileResource(new File(pathToFile));
facebookIcon = new Image(null, resource);
facebookIcon.addClickListener(new MouseEvents.ClickListener() {
#Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event) {
try {
ui.getPage().setLocation(ui.getAuthenticationService()
.redirect(ui.getProperty("oauth.application"), ui.getProperty("oauth.callback")));
} catch (Exception e) {
Notification.show(e.getMessage());
}
}
});
buttonLayout.addComponent(facebookIcon);
buttonLayout.addComponent(enter);
buttonLayout.setComponentAlignment(enter, Alignment.BOTTOM_LEFT);
formLayout = new FormLayout(login, password, buttonLayout);
formLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_LEFT);
formLayout.setMargin(true);
return formLayout;
}
}
But how to make it redirect to required me vaadin page with all components(ui bean name pmcVaadin)? Because when I do like this - it's again being intercepted and it shows me loginform again.
First of all shorten and clean up your "createLayout" method. ;)
Try:
ui.getNavigator().navigateTo("pmc-web");
I'm using Netbeans 7.2.1 and GlassFish 3.1.
I created web application using JSF, ejb classes and JDBC data source.
xhtml pages reference backing managed beans, which call local interface functions on ejb classes which run queries through the data source, directly getting connection and executing queries.
The project builds successfully, but when I run the project, browser shows error "No data received", and browser tab title says failed to load. I think maybe I have some missing configurations, cause when I run same project with no reference to managed beans (and hence not to ejb's and database) , there's no such message.
Frankly I got lost in what configuration files are needed for such a project, and what is needed to configure there. I saw numerous explanations, each saying something else, and I'm not clear which one is relevant here. If you could point me to some clear relevant explanation, I'd be grateful.
Do I need to configure for this project somewhere data source? ejb classes? anything else?
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
beans.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
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 lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Movie Tickets Order </title>
</h:head>
<h:body>
<h:panelGrid columns="2" rendered="#{!UserBean.loggedIn}">
<h:outputLabel for="username" value="Username:"></h:outputLabel>
<h:inputText id="username" value="#{UserBean.username}"/>
<h:outputLabel for="password" value="Password: "></h:outputLabel>
<h:inputSecret id="password" value="#{UserBean.password}"/>
</h:panelGrid>
<h:commandButton value="Login" action="#{UserBean.login}" rendered="#{!UserBean.loggedIn}"/>
<h:commandButton value="Logout" action="#{UserBean.logout}" rendered="#{UserBean.loggedIn}"/>
<h:outputLink value="EditMovie" rendered="#{UserBean.isAdmin}"> Add/Edit Movie </h:outputLink>
</h:body>
UserBean
import TicketsEJB.UserejbLocal;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
#Named(value = "UserBean")
#SessionScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 20130908L;
private String username;
private String password;
private String status;
private boolean exist = false;
private boolean loggedIn = false;
private final String statusAdmin = "admin";
private final String statusUser = "user";
#EJB
UserejbLocal userejb;
public boolean isAdmin() {
return status.equals(statusAdmin);
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void login() {
status = userejb.getUser(username, password);
exist = (status == null) ? false : true;
if (exist) {
//render "Hello user"
if (status.equals(statusAdmin)) {
loggedIn=true;
//render admin part:
}
} else {
//render "Sorry, wrong credentials"
}
password = null;
}
....
Userejb class:
#Stateful
#Local(UserejbLocal.class)
public class Userejb implements UserejbLocal {
private Connection connection = null;
private PreparedStatement getUser = null;
private PreparedStatement addUser = null;
private PreparedStatement getUserSalt = null;
private boolean exist;
private String status;
#Resource( name = "jdbc/Movies")
DataSource dataSource;
#PostConstruct
#Override
public void prepareStatements() {
try {
if (dataSource == null) {
throw new SQLException("Unable to obtain DataSource");
}
connection = dataSource.getConnection();
if (connection == null) {
throw new SQLException("Unable to connect to DataSource");
}
try {
getUser = connection.prepareStatement(
"SELECT STATUS "
+ "FROM Users"
+ "WHERE NAMEU= ? and HASHP=?");
addUser = connection.prepareStatement(
"insert into Users values ('?','?','?','?')");
getUserSalt = connection.prepareStatement(
"SELECT SALTP "
+ "FROM Users"
+ "WHERE NAMEU= ? ");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
}
#Override
public void addUser(String name, String password, String status) {
String salt = Security.salt();
try {
addUser.setString(1, name);
addUser.setString(2, Security.hash(password + salt));
addUser.setString(3, salt);
addUser.setString(4, status);
addUser.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Userejb.class.getName()).log(Level.SEVERE, null, ex);
}
}
....
UserejbLocal interface :
public interface UserejbLocal {
void prepareStatements();
void addUser(String name, String password, String status);
public java.lang.String getUser(java.lang.String name, java.lang.String password);
}
Thanks for the help!
The problem was SQLSyntaxErrorException. Just needed to look at server log (output tab , glassfish server tab) to see what was the problem. Fixing SQL syntax rendered the page correctly.
You are missing a space between Users and WHERE in your query. This is causing the query to be parsed as:
SELECT STATUS FROM UsersWHERE NAMEU ...............
I have a JSF 2.1 with Primefaces mobile project which should run on desktop and mobile platforms. I wrote a renderkit handler which provides required renderkit based on the device the web app is running on. I'm having tough time in redirecting a desktop page to a mobile page.
URL used to access : http://localhost:8080
My Application structure is :
root
- WebContent
--desktop
---login.xhtml
--mobile
---login.xhtml
--WEB-INF
---web.xml
---faces-config.xml
--META-INF
faces-config.xml
<application>
<view-handler>com.renderkit.CustomViewHandler</view-handler>
</application>
<navigation-rule>
<display-name>Desktop-Login</display-name>
<from-view-id>/desktop/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>MOBILE</from-outcome>
<to-view-id>/mobile/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>AnalyzerUI</display-name>
<welcome-file-list>
<welcome-file>/desktop/login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
<url-pattern>*.jsf</url-pattern>
<url-pattern>*.faces</url-pattern>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
User class, a Session scoped Managed Bean class for login.xhtml
#ManagedBean
#SessionScoped
public class User implements Serializable
{
private String name;
private String password;
#PostConstruct
public void myPostConstruct()
{
String renderKitId = FacesContext.getCurrentInstance().getViewRoot().getRenderKitId();
System.out.println(" renderKitId >>> " + renderKitId);
if (renderKitId.equalsIgnoreCase("PRIMEFACES_MOBILE"))
{
try
{
FacesContext.getCurrentInstance().getApplication(). getNavigationHandler().handleNavigation(FacesContext.getCurrentInstance(), null , "MOBILE");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//getters and setters
}
CustomViewHandler
public class CustomViewHandler extends ViewHandlerWrapper
{
private ViewHandler wrapped;
public CustomViewHandler(ViewHandler wrapped)
{
this.wrapped = wrapped;
}
#Override
public ViewHandler getWrapped()
{
return this.wrapped;
}
#Override
public String calculateRenderKitId(FacesContext context)
{
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
String userAgent = req.getHeader("user-agent");
String accept = req.getHeader("Accept");
System.out.println("userAgent ::: "+ userAgent+ " accept :: "+accept);
if (userAgent != null && accept != null) {
UAgentInfo agent = new UAgentInfo(userAgent, accept);
if (agent.isMobileDevice()) {
return "PRIMEFACES_MOBILE";
}
}
return this.wrapped.calculateRenderKitId(context);
}
}