I'm still on the road of learning JSF. I have an IceFaces tree with an IceFaces commandLink to try to download a file. So far this is my xhtml and my backing bean. When I click the commandLink it just prints the two messages and then it does nothing and it does not show any warning any error at all... How to know what's happening? What am I missing?
Cheers
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 xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ice="http://www.icesoft.com/icefaces/component">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<ice:tree id="tree"
value="#{treeBean.model}"
var="item"
hideNavigation="false"
hideRootNode="false"
imageDir="./images/">
<ice:treeNode>
<f:facet name="icon">
<ice:panelGroup style="display: inline">
<h:graphicImage value="#{item.userObject.icon}"/>
</ice:panelGroup>
</f:facet>
<f:facet name="content">
<ice:panelGroup style="display: inline">
<ice:commandLink action="#{treeBean.doDownload(item.userObject.fileAbsolutePath)}">
<ice:outputText value="#{item.userObject.text}"/>
</ice:commandLink>
</ice:panelGroup>
</f:facet>
</ice:treeNode>
</ice:tree>
</h:form>
</h:body>
</html>
BEAN
#ManagedBean
#ViewScoped
public class TreeBean implements Serializable {
private final DefaultTreeModel model;
/** Creates a new instance of TreeBean */
public TreeBean() {
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootObject.setBranchContractedIcon("./images/tree_folder_close.gif");
rootObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
rootObject.setLeafIcon("./images/tree_document.gif");
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method
model = new DefaultTreeModel(rootTreeNode);
// add some child nodes
for (int i = 0; i < 3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
FileSourceUserObject branchObject = new FileSourceUserObject(branchNode);
branchObject.setText("SteveJobs.jpg");
branchObject.setFileAbsolutePath("/Users/BRabbit/Downloads/SteveJobs.jpg");
branchObject.setBranchContractedIcon("./images/tree_folder_close.gif");
branchObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
branchObject.setLeafIcon("./images/tree_document.gif");
branchObject.setLeaf(true);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
}
public DefaultTreeModel getModel() {
return model;
}
public void doDownload(String fileAbsolutePath) {
System.out.println(fileAbsolutePath);
File file = new File(fileAbsolutePath);
if(file.exists())
System.out.println("Yes"); //It exists !
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseHeader("Content-Type", externalContext.getMimeType(file.getName()));
externalContext.setResponseHeader("Content-Length", String.valueOf(file.length()));
externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = externalContext.getResponseOutputStream();
IOUtils.copy(input, output);
} catch (FileNotFoundException ex) {
Logger.getLogger(TreeBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TreeBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
facesContext.responseComplete();
}
}
Bean's object
public class FileSourceUserObject extends IceUserObject{
String fileAbsolutePath;
public FileSourceUserObject(DefaultMutableTreeNode wrapper) {
super(wrapper);
}
public String getFileAbsolutePath(){
return fileAbsolutePath;
}
public void setFileAbsolutePath(String fileAbsolutePath){
this.fileAbsolutePath = fileAbsolutePath;
}
}
Finally I did it!
Here's some code that allows the user to see a tree (of Files) and download them.
XHTML
<ice:tree id="tree"
value="#{treeBean.model}"
var="item"
hideNavigation="false"
hideRootNode="false"
imageDir="./images/">
<ice:treeNode>
<f:facet name="icon">
<ice:panelGroup style="display: inline">
<h:graphicImage value="#{item.userObject.icon}"/>
</ice:panelGroup>
</f:facet>
<f:facet name="content">
<ice:panelGroup style="display: inline-block">
<ice:outputResource resource="#{item.userObject.resource}"
fileName="#{item.userObject.text}"
shared="false"/>
</ice:panelGroup>
</f:facet>
</ice:treeNode>
</ice:tree>
BACKING BEAN
#ManagedBean
#ViewScoped
public class TreeBean implements Serializable {
private final DefaultTreeModel model;
public TreeBean() {
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
FileSourceUserObject rootObject = new FileSourceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootObject.setBranchContractedIcon("./images/tree_folder_close.gif");
rootObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method
model = new DefaultTreeModel(rootTreeNode);
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
// add some child nodes
for (int i = 0; i < 3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
FileSourceUserObject branchObject = new FileSourceUserObject(branchNode);
branchObject.setText("Test.jpg");
branchObject.setResource(new SRCResource("/<filePath>/Test.jpg"));
branchObject.setBranchContractedIcon("./images/tree_folder_close.gif");
branchObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
branchObject.setLeafIcon("./images/tree_document.gif");
branchObject.setLeaf(true);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
}
public DefaultTreeModel getModel() {
return model;
}
}
SRCResource
public class SRCResource implements Resource {
private String fileAbsolutePath;
private final Date lastModified;
public SRCResource(String fileAbsolutePath) {
this.fileAbsolutePath = fileAbsolutePath;
this.lastModified = new Date();
}
#Override
public String calculateDigest() {
return "No lo calcularé jamás !!";
}
#Override
public InputStream open() throws IOException {
return (InputStream)(new FileInputStream(fileAbsolutePath));
}
#Override
public Date lastModified() {
return lastModified;
}
#Override
public void withOptions(Options optns) throws IOException {
}
public String getFileAbsolutePath() {
return fileAbsolutePath;
}
public void setFileAbsolutePath(String fileAbsolutePath) {
this.fileAbsolutePath = fileAbsolutePath;
}
}
Web.xml
Add the following
<servlet>
<servlet-name>Resource Servlet</servlet-name>
<servlet-class>com.icesoft.faces.webapp.CompatResourceServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resource Servlet</servlet-name>
<url-pattern>/xmlhttp/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/icefaces/*</url-pattern>
</servlet-mapping>
And that's it ! Simply adapt the code to your needs !
Cheers !
More info on http://wiki.icefaces.org/display/ICE/Adding+ICEfaces+to+Your+Application
Related
I am using a p:schedule but it won't show up at the first time I entered the page
I have to refresh the page once and then it comes out.
<?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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:form id="form">
<h:outputScript library="js" name="primefaces-locale-zh.js" />
<div class="top-extra-title">
<h:outputText value="#{menu.miMeetingScheduleView}" />
</div>
<p:schedule id="schedule" value="#{meetingScheduleView.meetingSchedule}"
widgetVar="meetingSchedule" timeZone="GMT+8" draggable="false"
locale="zh" >
<p:ajax partialSubmit="true" event="eventSelect" listener="#{meetingScheduleView.onEventSelect}"
update="mform :content" />
</p:schedule>
</h:form>
</ui:composition>
#ManagedBean(name = "meetingScheduleView")
#ViewScoped
public class MeetingScheduleView implements Serializable {
private static final long serialVersionUID = 1L;
SessionUser sessionUser;
private String accountOrgId;
private static final String msgFile = "cyberstar.module.meeting.meeting";
private List<Meeting> meetingList;
private ScheduleModel meetingSchedule;
private ScheduleEvent event;
#ManagedProperty(value = "#{sysAdminPage}")
private SysAdminPage sysAdminPage;
#PostConstruct
public void init() {
sessionUser = JSFUtil.getSessionUser();
if(sessionUser==null){
MsgUtil.showErrorMsg(msgFile, "infSessionUserFail", "infSessionUserFailDetail");
sessionUser.logoff();
}
accountOrgId = sessionUser.getOperator().getOrgId();
meetingList = new ArrayList<Meeting>();
meetingSchedule = new DefaultScheduleModel();
event = new DefaultScheduleEvent();
initialize();
}
public void sendMeetingUnid(){
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
String issueUnid = context.getRequestParameterMap().get("meetingUnid");
LinkedHashMap<String , String> hm = new LinkedHashMap<String , String>();
if (sessionUser.getSendDataMap().get("meetingView") == null) {
hm.put("meetingUnid", issueUnid);
sessionUser.getSendDataMap().put("meetingView", hm);
} else {
hm = sessionUser.getSendDataMap().get("meetingView");
hm.put("meetingUnid", issueUnid);
}
}
public void initialize(){
try {
if (sessionUser.isCyberStar()) {
meetingList = MeetingDAO.getAllMeeting();
} else {
meetingList = MeetingDAO.getMeetingByOrgId(accountOrgId);
}
for (int i = 0; i < meetingList.size(); i++) {
Meeting m = meetingList.get(i);
if (m.getStatus().equals(MeetingStatus.sketch)) {
continue;
}
DefaultScheduleEvent dsEvent = new DefaultScheduleEvent(m.getTitle(), m.getStartTime(), m.getEndTime(),m.getUnid());
if(m.getStatus().equals(MeetingStatus.cancel)){
dsEvent.setStyleClass("redEvent");
}
meetingSchedule.addEvent(dsEvent);
}
} catch (SQLException e) {
MsgUtil.showErrorMsg(msgFile, "infUpdateFail",
"infUpdateFailSQLExceptionDetail");
e.printStackTrace();
}
}
public void onEventSelect(SelectEvent selectEvent) {
event = (ScheduleEvent) selectEvent.getObject();
String issueUnid = String.valueOf(event.getData());
LinkedHashMap<String , String> hm = new LinkedHashMap<String , String>();
if (sessionUser.getSendDataMap().get("meetingView") == null) {
hm.put("meetingUnid", issueUnid);
sessionUser.getSendDataMap().put("meetingView", hm);
} else {
hm = sessionUser.getSendDataMap().get("meetingView");
hm.put("meetingUnid", issueUnid);
}
try {
sysAdminPage.openView("meetingForm");
} catch (IOException e) {
MsgUtil.showErrorMsg(msgFile, "infUpdateFail", "infUpdateFailExceptionDetail");
e.printStackTrace();
}
}
these are the codes of button which direct to the page
<p:menuitem value="#{menu.miMeetingScheduleView}" styleClass="meetingScheduleView"
onclick="highlightme('meetingScheduleView')" action="#{sysAdminPage.menuSelected}"
update="mform :content">
<f:param name="viewname" value="meetingScheduleView" />
</p:menuitem>
my goal is to show the p:schedule just when I enter the page
I'm getting this strange error when I try to use a scrollable TreeTable (but it does not happen using a non-scrollable TreeTable) component.
The component simply does not collapse or expand on click if I add
style="margin-top:0" scrollable="true" scrollHeight="150"
to the p:treeTable component.
If I remove this, it works like a charm.
Tried with both primefaces 4 and 5 community.
Running on tomcat 7, using mojarra 2.2.0. (added by eclipse), Oracle Java 7.
Trying to run on both firefox 30.0, chrome 35 and IE 11.
Looks like some deprecated JQuery method, but why primefaces 4 and 5 would distribute their single jar with the wrong JQuery?
Sounds like I am missing something here. What should I do to fix that?
I've created a Dynamic Web Project using Eclipse Kepler RC1, here goes the configuration info (pretty vanilla)
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>prime</display-name>
<welcome-file-list>
<welcome-file>index.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>*.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>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
faces.config
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
</faces-config>
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 xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h1>Hello World PrimeFaces</h1>
<h:form>
<p:treeTable value="#{tree.root}" var="document" style="margin-top:0" scrollable="true" scrollHeight="150">
<f:facet name="header">
Document Viewer
</f:facet>
<p:column headerText="Name">
<h:outputText value="#{document.name}" />
</p:column>
<p:column headerText="Size">
<h:outputText value="#{document.size}" />
</p:column>
<p:column headerText="Type">
<h:outputText value="#{document.type}" />
</p:column>
</p:treeTable>
</h:form>
</h:body>
</html>
managed bean
package prime;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
#ManagedBean(name = "tree")
#ViewScoped
public class TreeBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private TreeNode root;
#PostConstruct
public void init() {
root = createDocuments();
// root.getChildren().get(0).setExpanded(true);
}
public TreeNode getRoot() {
return root;
}
public TreeNode createDocuments() {
TreeNode root = new DefaultTreeNode(new Document("Files", "-", "Folder"), null);
TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);
for(int i=0;i<100;i++){
new DefaultTreeNode("document", new Document("doc"+i, "40 KB", "Document"), documents);
}
return root;
}
}
entity bean
package prime;
import java.io.Serializable;
public class Document implements Serializable, Comparable<Document> {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String size;
private String type;
public Document(String name, String size, String type) {
this.name = name;
this.size = size;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
//Eclipse Generated hashCode and equals
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((size == null) ? 0 : size.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Document other = (Document) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (size == null) {
if (other.size != null)
return false;
} else if (!size.equals(other.size))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
#Override
public String toString() {
return name;
}
public int compareTo(Document document) {
return this.getName().compareTo(document.getName());
}
}
facets
$.browser is deprecated function in jquery latest. To use the deprecated function, use jquery migrate plugin
The plugin restores deprecated features and behaviors so that older
code will still run properly on jQuery 1.9 and later.
I have to implement I18N based on domain using JSF2.
For example if the domain is
www.bookstore.com --> it should go to english site
www.bookstore.com.cn --> it should go to chinese site
www.bookstore.co.jp --> it should go to japanese site
We have all properties files with proper translation.
When i change my browser language/locale, i could able to see the translated content.
But we don't need that behavior actually.
I am setting the locale based on domain in Filter, It seems not working.
Here is my code, What is wrong in this code, Where is the problem ?
AuthenticationFilter.java
public class AuthenticationFilter implements Filter {
private static Log log = LogFactory.getLog(AuthenticationFilter.class);
#Override
public void init(FilterConfig config) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
FacesContext facesContext = FacesUtil.getFacesContext(httpRequest, httpResponse);
facesContext.getExternalContext().setResponseCharacterEncoding("UTF-8");
Locale requestLocale = LocaleUtil.getLocaleFromDomain(httpRequest);
if(requestLocale == null){
requestLocale = LocaleUtil.getDefault();
}
facesContext.getViewRoot().setLocale(requestLocale);
chain.doFilter(httpRequest, httpResponse);
}
#Override
public void destroy() {
}
}
FacesUtil.java
public class FacesUtil {
public static FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "");
facesContext.setViewRoot(view);
FacesContextWrapper.setCurrentInstance(facesContext);
}
return facesContext;
}
// Wrap the protected FacesContext.setCurrentInstance() in a inner class.
private static abstract class FacesContextWrapper extends FacesContext {
protected static void setCurrentInstance(FacesContext facesContext) {
FacesContext.setCurrentInstance(facesContext);
}
}
}
LocaleUtil.java
public class LocaleUtil {
public static Locale getLocaleFromDomain(HttpServletRequest request){
Locale locale=Locale.getDefault();
String domain = request.getHeader("HOST");
if(domain.contains(".com.cn"))
{
locale = new Locale(Locale.SIMPLIFIED_CHINESE.getLanguage(), Locale.CHINA.getCountry());
}else if(domain.contains(".co.jp"))
{
locale = new Locale(Locale.JAPANESE.getLanguage(), Locale.JAPAN.getCountry());
}else if(domain.contains(".co.kr"))
{
locale = new Locale(Locale.KOREAN.getLanguage(), Locale.KOREA.getCountry());
}else if(domain.contains(".com.tw"))
{
locale = new Locale(Locale.CHINESE.getLanguage(), Locale.TAIWAN.getCountry());
}
return locale;
}
public static Locale getDefault() {
Locale defaultLocale = new Locale("en", "US");
return defaultLocale;
}
}
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.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-facesconfig_2_0.xsd">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>en_US</supported-locale>
<supported-locale>zh</supported-locale>
<supported-locale>zh_CN</supported-locale>
<supported-locale>zh_TW</supported-locale>
<supported-locale>ja</supported-locale>
<supported-locale>ja_JP</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.bookstore.component.BookStoreTextHandler</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
BookStoreTextHandler.java
public class BookStoreTextHandler extends ResourceBundle {
protected static final String BUNDLE_NAME = "/var/app/conf/bookstore";
protected static final String BUNDLE_EXTENSION = "properties";
protected static final Control UTF8_CONTROL = new UTF8Control();
public BookStoreTextHandler() {
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
setParent(ResourceBundle.getBundle(BUNDLE_NAME, locale, UTF8_CONTROL));
}
#Override
protected Object handleGetObject(String key) {
return parent.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
protected static class UTF8Control extends Control {
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, BUNDLE_EXTENSION);
ResourceBundle bundle = null;
InputStreamReader reader = null;
FileInputStream fis = null;
try {
File file = new File(resourceName);
if (file.isFile()) { // Also checks for existance
fis = new FileInputStream(file);
reader = new InputStreamReader(fis, Charset.forName("UTF-8"));
bundle = new PropertyResourceBundle(reader);
}
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(fis);
}
return bundle;
}
}
}
i have bookstore.properties, bookstore_en.properties, bookstore_en_US.properties, bookstore_zh.properties, bookstore_zh_CN.properties, bookstore_zh_TW.properties, bookstore.properties_ja, bookstore_ja_JP.properties, files in /var/app/conf/ location.
introPage.xhtml
<ui:composition lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div class="frame">
<h1>#{msg['bookstore.intro.title']}</h1>
</div>
<div>
<p style="line-height: 1.6em; font-family: Verdana, Arial, sans-serif;">
<h:outputText value="#{msg['bookstore.intro.paragraph.1']}" escape="false"/>
</p>
<p style="line-height: 1.6em; font-family: Verdana, Arial, sans-serif;">
<h:outputText value="#{msg['bookstore.intro.paragraph.2']}" escape="false"/>
</p>
<p style="line-height: 1.6em; font-family: Verdana, Arial, sans-serif; font-weight: bold;">
<h:outputText value="#{msg['bookstore.intro.paragraph.3']}" escape="false"/>
</p>
</div>
</ui:composition>
When i am trying from different domains [ i have changed my host file locally ],
when i debug the filter code, it is giving correct Locale based on domain.
But don't know why always getting english content.
But if i change the browser language, i can see the translated content.
What is wrong in this code ?
I've been searching here for hour now and unfortunately I can't how to display database records to datatable, I'm newbie to JSF and I don't know much on JSF right now but I'm building a simple crud application I already know how to create, delete records using JSF but I'm having problem displaying this records to my datatable. I tried creating arraylist, I tried creating another class for this, To make it more clear here is my code:
This is my index.jsf:
<?xml version='1.0' encoding='windows-1252'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<html xmlns="http://www.w3.org/1999/xhtml">
<h:head></h:head>
<h:body>
Username:
<h:outputText value="#{ backing_index.userName }" id="Username">
<p>
</p>
<p>
</p>
<p>
</p>
</h:outputText>
<p>
RoleI.D:
<h:outputText value="#{backing_index.roleId}" id="RoleID"/>
</p>
Role Description:
<h:outputText value="#{backing_index.roleDesc}" id="Description"/>
<h:dataTable value="#{ backing_index.tableRs }" var="user" rules="rows" cellpadding="7">
<f:facet name="header"></f:facet>
<f:facet name="footer"></f:facet>
<h:column>
<f:facet name="header">ID</f:facet>
#{ user.tableId }
</h:column>
<h:column>
<f:facet name="header">First Name</f:facet>
#{ user.tableFirstName }
</h:column>
<h:column>
<f:facet name="header">Middle Name</f:facet>
#{ user.tableMiddleName }
</h:column>
<h:column>
<f:facet name="header">Last Name</f:facet>
#{ user.tableLastName }
</h:column>
<h:column>
<f:facet name="header">Delete</f:facet>
<h:commandButton action="#{ backing_index.deleteAction }" value="Remove this">
<f:param value="Remove" name="delete" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:body>
</html>
<!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_index-->
</f:view>
Here is my code for the bean:
package view.backing;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.bean.*;
import javax.faces.context.*;
import javax.annotation.*;
import javax.faces.*;
import java.sql.*;
import java.util.*;
#RequestScoped
public class Index {
private Connection con;
private ResultSet rs;
private String userName;
private String roleId;
private String roleDesc;
//Variable of Data Table
private TableUser[] tableRs;
//End of Variable
//Start of getter and setter for Data table
public void setTableRs(Index.TableUser[] tableRs) {
this.tableRs = tableRs;
}
public Index.TableUser[] getTableRs() {
return tableRs;
}
//End of getter and setter
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleId() {
return roleId;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public String getRoleDesc() {
return roleDesc;
}
#PostConstruct
public void init()throws SQLException, ClassNotFoundException{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost/XE", "JEROME", "perbert101");
displayUserInfo();
displayTableRecords();
}
private void displayUserInfo()throws SQLException{
FacesContext context = FacesContext.getCurrentInstance();
userName = (String)context.getExternalContext().getSessionMap().get("userName");
roleId = (String)context.getExternalContext().getSessionMap().get("roleId");
Statement state = con.createStatement();
state.executeQuery("SELECT * FROM ROLES WHERE ID = 2");
rs = state.getResultSet();
while(rs.next()){
roleDesc = rs.getString(3);
}
}
private void displayTableRecords()throws SQLException{
String query = "SELECT * FROM USERS";
PreparedStatement state = con.prepareStatement(query);
state.execute();
rs = state.getResultSet();
while(rs.next()){
tableRs = new TableUser[]{new TableUser(rs.getLong(1), rs.getString(2), rs.getString(7), rs.getString(5))};
}
}
//Table Records Store
public static class TableUser{
long tableId;
String tableFirstName;
String tableMiddleName;
String tableLastName;
public TableUser(long tableId, String tableFirstName, String tableMiddleName, String tableLastName){
this.tableId = tableId;
this.tableFirstName = tableFirstName;
this.tableMiddleName = tableMiddleName;
this.tableLastName = tableLastName;
}
public void setTableId(long tableId) {
this.tableId = tableId;
}
public long getTableId() {
return tableId;
}
public void setTableFirstName(String tableFirstName) {
this.tableFirstName = tableFirstName;
}
public String getTableFirstName() {
return tableFirstName;
}
public void setTableMiddleName(String tableMiddleName) {
this.tableMiddleName = tableMiddleName;
}
public String getTableMiddleName() {
return tableMiddleName;
}
public void setTableLastName(String tableLastName) {
this.tableLastName = tableLastName;
}
public String getTableLastName() {
return tableLastName;
}
}
}
I don't have any error or something and it display only the last records in the database. Guys if you know the easiest ways can you teach me how to do it, and I always go for a nice clean, short code. your help is really much appreciated :)
There is a bug in your displayTableRecords() method. Within while loop you instantiate new TableUser array for each iteration. Actually what you should do is add TableUser object one by one to existing array.
Use ArrayList inseadof array.
private List<TableUser> tableRs = new ArrayList<TableUser>();
public List<TableUser> getTableRs() {
return tableRs;
}
public void setTableRs(List<TableUser> tableRs) {
this.tableRs = tableRs;
}
private void displayTableRecords() {
String query = "SELECT * FROM USERS";
PreparedStatement state = con.prepareStatement(query);
state.execute();
rs = state.getResultSet();
while (rs.next()) {
tableRs.add(new TableUser(rs.getLong(1),
rs.getString(2), rs.getString(7), rs.getString(5)));
}
}
I have a problem with the view in JSP (Java EE)
Only the heading is shown.
My Code:
Entitiy Class (Konto);
#Entity
public class Konto implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable=false)
#NotNull(message="Kontonummer muss angegenben werden")
#Pattern(regexp="[0-9][0-9][0-9][0-9]")
private String kontonummer;
#Column(nullable=false)
#NotNull(message="Kontostand muss angegeben werden")
#DefaultValue(value="0.0")
private Double ktostd;
#Column(nullable=false)
#DecimalMin(value="0", message="Der Zins muss zw. 0 und 10 % liegen")
#DecimalMax(value="0.1", message="Der Zins muss zw. 0 und 10 % liegen")
private Double habenZins;
#ManyToOne
#JoinColumn(nullable=false)
#NotNull(message="Besitzer muss angegeben werden")
private Besitzer besitzer;
public Besitzer getBesitzer() {
return besitzer;
}
public void setBesitzer(Besitzer besitzer) {
this.besitzer = besitzer;
}
public Double getHabenZins() {
return habenZins;
}
public void setHabenZins(Double habenZins) {
this.habenZins = habenZins;
}
public String getKontonummer() {
return kontonummer;
}
public void setKontonummer(String kontonummer) {
this.kontonummer = kontonummer;
}
public Double getKtostd() {
return ktostd;
}
public void setKtostd(Double ktostd) {
this.ktostd = ktostd;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Konto)) {
return false;
}
Konto other = (Konto) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "at.korn.entity.NewEntity[ id=" + id + " ]";
}
}
Kontolist.xhtml:
<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>
<title>Facelet Title</title>
</h:head>
<h:body>
<h1>Kontoliste</h1>
<h:form>
<h:dataTable value="#{kontolist.kontos}" var="konto">
<h:column>
<f:facet name="header">
<h:outputText value="Kontonummer"></h:outputText>
</f:facet>
<h:outputText value="#{konto.kontonummer}"></h:outputText>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
KontoList Controller:
#ManagedBean
#SessionScoped
public class Kontolist {
#EJB
KontoFacadeLocal kontofacade;
private List<Konto> kontos;
/** Creates a new instance of kontolist */
public Kontolist() {
kontos = kontofacade.findAll();
}
public KontoFacadeLocal getKontofacade() {
return kontofacade;
}
public void setKontofacade(KontoFacadeLocal kontofacade) {
this.kontofacade = kontofacade;
}
public List<Konto> getKontos() {
setKontos(kontofacade.findAll());
return kontos;
}
public void setKontos(List<Konto> kontos) {
this.kontos = kontos;
}
}
Problem:
Only the header is shown. In the source from the browser is the same code without html injection (like value="#{konto.kontonummer}")
First of all, that is not a JSP file. That's a Facelets (XHTML) file. JSP is an ancient view technology. Facelets is the successor of JSP.
So, your concrete problem is that the JSF tags are not been parsed? That can happen when the request URL did not match the URL pattern of the FacesServlet as definied in web.xml. If it is for example *.jsf, then you'd need to change the request URL from
http://localhost:8080/contextname/kontolist.xhtml
to
http://localhost:8080/contextname/kontolist.jsf
However, much better is to just change the URL pattern of the FacesServlet to *.xhtml so that you do not need to fiddle with virtual URLs and introduce security constraints to prevent the enduser from accidently or awaringly viewing the raw *.xhtml pages.
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
See also:
What is the difference between creating JSF pages with .jsp or .xhtml or .jsf extension
Unrelated to the concrete problem, you've by the way a NullPointerException bug in your code. Replace
public Kontolist() {
kontos = kontofacade.findAll();
}
by
#PostConstruct
public void init() {
kontos = kontofacade.findAll();
}
Injected dependencies are namely not available during construction. The getter and setter for the kontofacate are also entirely superfluous, I'd remove them to prevent future confusion and abuse.