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 ...............
Related
I am trying to learn Struts2, I have used a view page that hits action , the action class is using a bean where getter setter methods are written and the action is also using a dao where the connection is written.I want to mention that I am using jboss v5.0 and eclipse, I have added all the jar files.
Now , when I am trying to run this application the welcome jsp page is hitting properly then on clicking submit button the below error is showing:
There is no Action mapped for namespace /controller and action name
I am placing my code and directory structure. I have tried the using namespace="/"
<result name="SUCCESS">/success.jsp</result>, still its is not working
passing
+JAX-WS Web Services
+Deployment Descriptor:Passing
-Java Resources
-src
-controller
-TestAction.java
-TestAction
-execute(HttpServletRequest request , HttpServletResponse response) : String
-model
-TestBean.java
-TestBean
-age
-ocation
-name
-getAge() :String
-getName() :String
-getLocation() :String
-setAge(String) : void
-setName(String) : void
-getlocation(String) : void
-UserDao.java
- UserDao
-Logincheck() :Connection
registration.jsp
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Passing</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>registration.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="sturts-default">
<action name="TestAction" class="controller.TestAction">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center> Welcome, Data successfully inserted</center>
</body>
</html>
registration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# taglib uri="/struts-tags" prefix="s"/%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="TestAction" method="post" >
<s:textfield name="Name" label="Name"/>
<s:textfield name="Age" label="Age"/>
<s:textfield name="Location" label="Location"/>
<s:submit label="Submit"></s:submit>
</s:form>
</body>
</html>
TestAction.java
package controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.TestBean;
import model.UserDao;
import org.apache.struts2.ServletActionContext;
public class TestAction extends ActionSupport{
public String execute(HttpServletRequest request , HttpServletResponse response) throws Exception
{
String Name = request.getParameter("Name");
String Age = request.getParameter("Age");
String Location = request.getParameter("Location");
TestBean bean = new TestBean();
bean.setName(Name);
bean.setAge(Age);
bean.setLocation(Location);
UserDao obj = new UserDao();
Connection x= obj.Logincheck();
if(x!=null)
{
PreparedStatement ps= x.prepareStatement("insert into Registration values(?,?,?)");
ps.setString(1, bean.getName());
ps.setString(2, bean.getAge());
ps.setString(3, bean.getLocation());
int i = ps.executeUpdate();
System.out.println("The value of i =" +i);
if(i>0)
{
return SUCCESS;
}
}
return null;
}
}
TestBean.java
package model;
public class TestBean {
String name;
String age;
String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
UserDao.java
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UserDao {
public Connection Logincheck()
{
Connection con=null;
try
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
con= DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "username", "password");
if(con!=null)
{
return con;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
that's all.
This error
There is no Action mapped for namespace /controller and action name
generally means Struts can't find the action specified in a namespace specified (/controller in this case). BTW in your case you've not specified /controller anywhere and the action name is missing in the error message, so this error could be probably generated by the bunch of other errors you have in your action / JSP / configuration.
you also have two typos, preventing anything to work:
sturts-default instead of struts-default:
<package name="default" extends="struts-default">
"SUCCESS" instead of "success", that is the result mapped to the constant SUCCESS that you are returning from the Action method.
<result name="success">/success.jsp</result>
If using Struts version newer than or equals to 2.1.3, you need the new filter, StrutsPrepareAndExecuteFilter instead of the deprecated FilterDispatcher;
The action method must be a public String something() with no parameters. This:
public String execute(HttpServletRequest request , HttpServletResponse response) throws Exception
is simply wrong, and should be:
public String execute(){}
Here
String Name = request.getParameter("Name");
String Age = request.getParameter("Age");
String Location = request.getParameter("Location");
TestBean bean = new TestBean();
bean.setName(Name);
bean.setAge(Age);
bean.setLocation(Location);
you are reinventing the wheel really badly. Attributes must be private, at class level, with getters and setters, and they'll be populated automatically, with no need to access the request. In your case:
private TestBean bean;
/* GETTER AND SETTER */
public String execute(){
System.out.println(bean.getName());
// ...
}
Unrelated, but Java naming conventions use lower-case names for local variables and instance properties.
In JSP page, you need to access the getter with a starting lowercase character:
<s:textfield name="Name" label="Name"/>
must be
<s:textfield name="name" label="Name"/>
and so the other fields. Also if you point to an object like TestBean, you need to do like this:
<s:textfield name="bean.name" label="Name"/>
This are the main problems... BTW consider start coding after having read a book, or some good tutorial. Starting in the dark like this is not the right way, IMHO.
Following are points which you should notice,
If you are using TestBean class as data carrier, you have to implement ModelDriven Interface.
TestAction.java should present in "Controller" package.
If you want HttpServletRequest and HttpServletResponse in your execute() method, then the simplest way you can get that is to implement ServletRequestAware and ServletResponseAware interfaces and implement respective methods.
And most important if your success.jsp is in Web Content folder, then you dont need to specify
<result name="SUCCESS">/success.jsp</result>
Just make it like
<result name="SUCCESS">success.jsp</result>
And if you have any folder suppose, "Folder1" in Web Content, Then specify like
<result name="SUCCESS">Folder1/success.jsp</result>
i got problem when using rewrite url mod
my problem is when using it, i move to login form for admincp
after enter username and password it appear HTTP 500 Status, but no stacktrace got in tomcat log???
my code
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="admincp" namespace="/admincp" extends="struts-default">
<interceptors>
<interceptor name="login" class="org.dejavu.software.interceptor.LoginInterceptor" />
<interceptor-stack name="stack-with-login">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="stack-with-login"/>
<global-results>
<result name="login">login.jsp</result>
</global-results>
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<interceptor-ref name="defaultStack" />
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
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>dejavuSoft</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>logLevel</param-name>
<param-value>WARN</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
Login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<title>Deja vu! | Login - Admin Control Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<img src="img/loginLogo.png" id="logo"/>
<s:actionerror/>
<s:form action="logincp">
<s:textfield name="username" value="username..." id="txtusername" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;"/>
<s:password name="password" value="password..." id="txtpassword" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;"/><br/>
<s:submit value="Enter Admin Panel" id="btLogin"/>
</s:form>
<img src="img/dejavu.png" id="icon"/>
<div id="forget">
Forget Password | Forget Username
</div>
</body>
<footer>
Footer
</footer>
</html>
Login Action
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.view;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.dejavu.software.dao.UserDAO;
import org.dejavu.software.model.GroupMember;
import org.dejavu.software.model.User;
/**
*
* #author Administrator
*/
public class AdminLoginAction extends ActionSupport {
private static final long serialVersionUID = -1457633455929689099L;
private User user;
private String username, password;
private String role;
private UserDAO userDAO;
private GroupMember group;
public AdminLoginAction() {
userDAO = new UserDAO();
}
#Override
public String execute() {
String result = null;
if (getUsername().length() != 0 && getPassword().length() != 0) {
setUser(userDAO.checkUsernamePassword(getUsername(), getPassword()));
if (getUser() != null) {
for (GroupMember g : getUser().getGroups()) {
boolean admincp = g.getAdminpermission().contains("1");
if (admincp == true) {
Map session = ActionContext.getContext().getSession();
session.put("userLogged", getUsername());
session.put("passwordLogged", getPassword());
result = "success";
} else {
result = "error";
}
}
}
}
return result;
}
#Override
public void validate() {
if (getUsername().length() == 0) {
addFieldError("username", "Username is required");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("Password is required"));
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public GroupMember getGroup() {
return group;
}
public void setGroup(GroupMember group) {
this.group = group;
}
}
web error :
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:501)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.22 logs.
I'm starting my first steps in JSF.
I've already read this link
http://docs.oracle.com/javaee/6/tutorial/doc/bnawq.html#bnaww
in regards to map initialization.
The problem is, I want to populate my map with values residing in a file.
How can I do that?
I've tried not using faces-config.xml and calling a support method in the bean's constructor, but my select list box isn't populated.
My bean class:
#ManagedBean
public class ADGroupListBean {
private static final String WITH_ACCESS = "D:\\workspace\\AccessControl\\permissions.txt";
private static final String WITHOUT_ACCESS = "D:\\workspace\\AccessControl\\noPermissions.txt";
private Map<String,String> withAccess, withoutAccess;
private LDAPQueries queries;
public ADGroupListBean(){
withAccess = new LinkedHashMap<String, String>();
withoutAccess = new LinkedHashMap<String, String>();
queries = new LDAPQueries();
initList(WITH_ACCESS, withAccess);
initList(WITHOUT_ACCESS, withoutAccess);
}
private void initList(String filename, Map<String,String> list) {
File f = new File(filename);
if ( !f.exists() && f.getAbsolutePath().equals(WITHOUT_ACCESS) )
{
queries.queryAllGroups(WITHOUT_ACCESS);
}
try
{
Scanner sc = new Scanner(f);
while (sc.hasNext())
{
String group = sc.nextLine();
list.put(group, group);
}
}catch (IOException e) {
e.printStackTrace();
}
}
// public void populateList() {
//
//
// }
public Map<String,String> getWithAccess() {
return withAccess;
}
public Map<String,String> getWithoutAccess() {
return withoutAccess;
}
public void setWithoutAccess(Map<String,String> withoutAccess) {
this.withoutAccess = withoutAccess;
}
public void setwithAccess(Map<String,String> withAccess) {
this.withAccess = withAccess;
}
public void test() {
System.out.println("workssssssssssssssssss");
}
}
As for my JSF file, it is like this:
<!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">
<h:head><title>Your Title Here</title>
</h:head>
<h:body>
<h1>Your Heading Here</h1>
<h:form>
<h:selectOneMenu value="teste">
<f:selectItem itemLabel="" itemValue="" />
<f:selectItems value="#{ADGroupListBean.withoutAccess}" />
</h:selectOneMenu>
</h:form>
</h:body>
</html>
I've tested the bean's functions in a test application, and everything works fine.
So my guess is the bean isn't instantiated?
Regards,
Nuno.
This is a sample from mkyong.com that I slightly modified. I added an inputtext and command
to send the next offset for paging in mysql. The first page autoloads with an offset of 0 as expected. If I type 5 in the inputtext, it actually works, and the next page displays the next 5 records. However, if I now enter 10, it stops working and page just keeps trying to load. I waited 5 minutes, nothing. Another retry, 0 first on load entered 15 just to test, it worked. But trying to make it work after first use of the commandButton, it just stalls.
In the url is displayed a current sessionid. Is this a session problem, or a configuration problem?
I'm new to jsf, and am trying to learn how to properly send request through to make a page display something. I got the inputText and commandButton idea direct from the javaeetutorial6 on oracles site, the guessnumber/duke example.
package model;
//import java.util.Date;
public class Customer{
public String petid;
public String petname;
public String tmpvar;
private String offset;
//public String address;
//public Date created_date;
//private String searchText;
//public String getSearchText() { return searchText; }
//public void setSearchText(String s) { searchText = s; }
public String getpetid() {
return petid;
}
public void setpetid(String petid) {
this.petid = petid;
}
public String getpetname() {
return petname;
}
public void setpetname(String petname) {
this.petname = petname;
}
/*public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}*/
public String gettmpvar() {
return tmpvar;
}
public void settmpvar(String tmpvar) {
this.tmpvar = tmpvar;
}
}
package cust;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import model.Customer;
#ManagedBean(name="Customer")
//#SessionScoped
public class CustomerBean implements Serializable{
int userNumber;
String offset;
//String SearchText;
//resource injection
#Resource(name="jdbc/petback2")
private DataSource ds;
//if resource injection is not support, you still can get it manually.
/*public CustomerBean(){
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("jdbc/petback2");
} catch (NamingException e) {
}
}*/
//connect to DB and get customer list
public String searchText;
//private String offset;
public String getSearchText() { return searchText; }
public void setSearchText(String s) { searchText = s; }
public List<Customer> getCustomerList() throws SQLException{
int rowsperpage = 5;
//String offset;
//HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//offset = request.getParameter("offset");
//if ( offset == null ? "" == null : offset.equals(""))
//if (offset null ? "" == null : offset.equals("0")
//{
//getoffset();
//String voffset;
//voffset = offset;
if (offset == null)
{
offset = "0";
}
System.out.println(offset);
//}
//int pageno = 0;
//int offset = 5;
//offset = "5";
//offset = CustomerBean.this.searchText;
//offset = getResponse();
if(ds==null)
throw new SQLException("Can't get data source");
//get database connection
Connection con = ds.getConnection();
if(con==null)
throw new SQLException("Can't get database connection");
PreparedStatement ps
= con.prepareStatement(
"select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
//"select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
//get customer data from database
ResultSet result = ps.executeQuery();
List<Customer> list = new ArrayList<Customer>();
//Customer cust2 = new Customer();
while(result.next()){
Customer cust2 = new Customer();
cust2.setpetid(result.getString("petid"));
cust2.setpetname(result.getString("petname"));
//cust2.setAddress(result.getString("address"));
//cust2.setCreated_date(result.getDate("created_date"));
//store all data into a List
list.add(cust2);
}
//List<Customer> list1 = new ArrayList<Customer>();
//Customer cust3 = new Customer();
Customer cust2 = new Customer();
cust2.settmpvar("hello");
list.add(cust2);
return list;
}
public void setoffset(String user_number) {
this.offset = user_number;
System.out.println(offset);
}
public String getoffset() {
return offset;
}
}
newjsf.html
<?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">
<h:head>
<h:outputStylesheet library="css" name="table-style.css" />
<script type="text/javascript" src="include/jquery.js"></script>
<script type="text/javascript" src="include/myjq.js"></script>
</h:head>
<h:body>
<h:form>
<h:dataTable id="myTable" value="#{Customer.customerList}" var="c" border="1"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>
<h:column>
<f:facet name="header">
petid
</f:facet>
#{c.petid}
</h:column>
<h:column>
<f:facet name="header">
petname
</f:facet>
#{c.petname}
</h:column>
</h:dataTable>
<h:inputText
id="userNo"
value="#{Customer.offset}">
</h:inputText>
<h:commandButton id="submit" value="Submit"
action="newjsf.xhtml"/>
</h:form>
</h:body>
</html>
config:
<?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>*.xhtml</url-pattern>
<!--<url-pattern>/faces/*</url-pattern>
<url-pattern>/faces/*</url-pattern>-->
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/newjsf.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Got it working, changed over to ui:repeat, and used the below to send gets
instead of post:
<h:outputLink id="link1" value="newui.xhtml?voffset=#{Customer.offset - 5}">
<h:outputText value="prev" />
</h:outputLink>
<h:outputLink id="link2" value="newui.xhtml?voffset=#{Customer.offset + 5}">
<h:outputText value="next" />
</h:outputLink>
And in the bean:
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
offset = req.getParameter("voffset");
if (offset == null) {
offset = "0";
}
and,
public void setoffset(String voffset) {
this.offset = voffset;
//System.out.println(offset);
}
public String getoffset() {
return offset;
}
I don't know how, but the set/get works without a call to it, probably auto handled.
Anyway now paging works like a champ, and more control than a datatable.
I using JSF 2.0 + Icefaces 2.0 and try to implement spring security 2.06 (not 3.x due to compatible problems with Icefaces 2.0).
I follow this guide (I think it is for JSF 1.x and Icefaces 1.8):
http://facestutorials.icefaces.org/tutorial/spring-security-basic.html
But I have problem to integrate the spring framework. I have added these lines to web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<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>
Then I have a file, applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">
<security:http auto-config="true" access-denied-page="/pages/accessDenied.xhtml">
<security:intercept-url pattern="/secured/**" access="ROLE_ALLACCESS, ROLE_URLACCESS"/>
<security:form-login login-page="/pages/springSecurityLogin.xhtml"
default-target-url="/secured/welcome.xhtml"/>
<security:logout logout-success-url="/pages/logoutSuccess.xhtml"/>
</security:http>
<security:authentication-provider user-service-ref="userDetailsService"/>
<bean id="userDetailsService" class="security.UserDetailsServiceImpl">
<constructor-arg ref="userRepository"/>
</bean>
<bean id="userRepository" class="security.UserDaoImpl"/>
</beans>
The userDetailsService class is implemented according to:
package security;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService {
private UserDAO userDAO;
public UserDetailsServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
AppUser user = userDAO.findUser(username);
if (user == null)
throw new UsernameNotFoundException("User not found: " + username);
else {
return makeUser(user);
}
}
private org.springframework.security.userdetails.User makeUser(AppUser user) {
return new org.springframework.security.userdetails.User(user.getLogin(), user
.getPassword(), true, true, true, true,
makeGrantedAuthorities(user));
}
private GrantedAuthority[] makeGrantedAuthorities(AppUser user) {
GrantedAuthority[] result = new GrantedAuthority[user.getRoles().size()];
int i = 0;
for (String role : user.getRoles()) {
result[i++] = new GrantedAuthorityImpl(role);
}
return result;
}
}
I also has a login bean:
package web.bean.security;
import org.springframework.security.ui.AbstractProcessingFilter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean(name="login")
public class Login {
// properties
private String userId;
private String password;
/**
* default empty constructor
*/
public Login() {
Exception ex = (Exception) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.get(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
if (ex != null)
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
.getMessage(), ex.getMessage()));
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/spring-authentication/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}
}
The problem is when I running a jsf file which using the login bean:
The requested resource () is not available.
I'm using Tomcat 7.
Can you please help me?
Best Regards /kungcc
I think you need to add the webapplication name before the /j_spring_security_check
like /WebAppName/j_spring_security_check that will aply the spring on all what comes after /webAppName
Does omitting /spring-authentication in the login() method of login bean help?
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}