I'm new to JSF and have trouble with sorting in a DataTable. I use Tomcat 7 and Jetty 9 (Jetty for testing) and PrimeFaces 5.1 with JSF-2.2.
I display some results on a page in a DataTable. I want to have this sortable, and with my code, the columns display sorting arrows, but clicking on them does not sort the table, it just changes the sort-indicator arrow in the column header.
I'm aware of the question , but the solution in that does not work and contradicts the code in the PrimeFaces showcase.
I made a small sample to demonstrate the problem:
table.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://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form>
<p:dataTable value="#{tableTest.list}" var="token">
<p:column headerText="Fisch" sortBy="#{token}">
<h:outputText value="#{token}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
Backing bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.util.Arrays;
import java.util.List;
#ManagedBean(name = "tableTest")
#RequestScoped
public class TableTest {
public List<String> getList() {
return Arrays.asList("Aal","Zander","Barsch","Brasse","Wels","Feldchen");
}
}
The servlet mapping in web.xml:
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
<!-- Production -->
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!-- HTML comments become components unless they're stripped -->
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
When I inspect the newtork with firefox's debug mode, I see the following response for clicking on sort:
<?xml version='1.0' encoding='UTF-8'?>
<partial-response id="j_id1">
<changes>
<update id="j_idt4:j_idt5">
<![CDATA[
<tr data-ri="0" class="ui-widget-content ui-datatable-even" role="row">
<td role="gridcell">Aal</td>
</tr><tr data-ri="1" class="ui-widget-content ui-datatable-odd" role="row">
<td role="gridcell">Zander</td>
</tr>
<tr data-ri="2" class="ui-widget-content ui-datatable-even" role="row">
<td role="gridcell">Barsch</td>
</tr>
<tr data-ri="3" class="ui-widget-content ui-datatable-odd" role="row">
<td role="gridcell">Brasse</td>
</tr>
<tr data-ri="4" class="ui-widget-content ui-datatable-even" role="row">
<td role="gridcell">Wels</td>
</tr><tr data-ri="5" class="ui-widget-content ui-datatable-odd" role="row">
<td role="gridcell">Feldchen</td>
</tr>]]>
</update>
<update id="j_id1:javax.faces.ViewState:0">
<![CDATA[5844788699585149238:6667543622103173254]]>
</update>
</changes>
</partial-response>
I'm new to JSF and have no more clues how to get the sorting to work. Can somebody help me to get the sorting function working?
You might want to view scope your backing bean and add a list property like this:
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.util.Arrays;
import java.util.List;
#ManagedBean(name = "tableTest")
#ViewScoped
public class TableTest {
private List<String> fishList;
#PostConstruct
public void init() {
this.fishList = Arrays.asList("Aal","Zander","Barsch","Brasse","Wels","Feldchen");
}
public List<String> getFishList() {
return this.fishList;
}
}
To be exact: the view-scope is optional, but you need a real property.
So this example would also work, although i do not recommend it:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.util.Arrays;
import java.util.List;
#ManagedBean(name = "tableTest")
#RequestScoped
public class TableTest {
private List<String> list = Arrays.asList("Aal","Zander","Barsch","Brasse","Wels","Feldchen");
public List<String> getList() {
return list;
}
}
The reason for this behaviour is, that the property (the list) is accessed multiple times during the request.
And in your example you always return a new list (Arrays.asList creates a new list with a new id) on every access to the property.
Yet, it seems that list-sorting only works when the list object stays the same during the request.
Related
how to render xhtml page , in springboot...,where should i put xhtml file
this is my project structure..what url should i hit for getting xhtml file.
how to call xhtml page
this is my xhtml page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<body>
<form>
<p:panel header="Login Page">
<h:outputText value="id" />
<h:inputText id="id" value="#{a.id}" required="true"></h:inputText>
<h:message for="id" style="color:blue"></h:message>
<br></br>
<br></br>
<h:outputText value="name" />
<h:inputText id="name" value="#{a.name}" required="true"></h:inputText>
<h:message for="name" style="color:blue"></h:message>
<p:commandButton
action="#{a.validate()}"
value="login"></p:commandButton>
</p:panel>
<br></br>
<br></br>
</form>
</body>
</html>
even http:localhost:8080/hello url does not render and give index page
package login.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#Controller
#ComponentScan
public class UserController {
#RequestMapping("/hello")
#ResponseBody
public String sayhii() {
return "index";
}
#Autowired
UserService userService;
#GetMapping("login-register/index")
public String index() {
return "index";
}
#GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
#GetMapping("/user/{id}")
private User getUser(#PathVariable("id") long id) {
return userService.getUserById(id);
}
#DeleteMapping("/user/{id}")
public void deleteUser(#PathVariable("id") long id) {
userService.delete(id);
}
#PostMapping("/users")
public long saveUser(#RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
#PutMapping("/users")
public User Update(#RequestBody User users) {
userService.saveOrUpdate(users);
return users;
}
}
this is usercontroller class,
how to work with this
i have added this in springboot main class
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
return new ServletRegistrationBean(servlet, "*.xhtml");
}
added this in web.xml
<servlet>
<servlet-name>facesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>*.xhtml</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>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
and this in my index.xhtml file
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
now,it is working
and using this url http://localhost:8080/index.xhtml
I have Spring project, now I want to add few JSF (Primefaces) xhtml pages, but I get null pointer exception in my #ManagedBean on #PostConstruct method when i try get data from existing services?
Do You know how to properly import AuctionViewService to my #ManagedBean? I think that's the problem but I dont know how to fix it :)
Below java classes there's my stacktrace with null pointer (also i mark line with NPE in SalesBean.java)
This is my xhtml page:
<?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://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/main.css"></link>
<script src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js" type=""></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type=""></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/common/main.js"></script>
<title>Sales</title>
</h:head>
<h:body>
<div id="wrapper">
<div id="navigationMenuPlaceholder"></div>
<!-- Page Content -->
<div id="page-content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<p:panelGrid columns="2">
<h:outputText value="#{SalesBean.firstName}"/>
<h:outputText value="#{SalesBean.lastName}" />
</p:panelGrid>
<p:dataTable var="property" value="#{SalesBean.userProperty}">
<p:column headerText="PropertyId">
<h:outputText value="#{property.propertyId}" />
</p:column>
<p:column headerText="UserId">
<h:outputText value="#{property.userId}" />
</p:column>
<p:column headerText="Street">
<h:outputText value="#{property.street}" />
</p:column>
<p:column headerText="House no">
<h:outputText value="#{property.homeNumber}" />
</p:column>
<p:column headerText="Local no">
<h:outputText value="#{property.localNumber}" />
</p:column>
<p:column headerText="Post code">
<h:outputText value="#{property.postCode}" />
</p:column>
<p:column headerText="City">
<h:outputText value="#{property.city}" />
</p:column>
<p:column headerText="Price">
<h:outputText value="#{property.price}" />
</p:column>
<p:column headerText="Size">
<h:outputText value="#{property.size}" />
</p:column>
</p:dataTable>
</div>
</div>
</div>
</div>
<div id="footerPlaceholder">
</div>
<!-- /#page-content-wrapper -->
</div>
</h:body>
</html>
SalesBean:
package application.beans;
import application.model.views.AuctionView;
import application.service.AuctionViewService;
import lombok.Getter;
import lombok.Setter;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.List;
#Setter
#Getter
#ViewScoped
#ManagedBean(name="SalesBean")
public class SalesBean {
#ManagedProperty("#{auctionViewService}")
private AuctionViewService auctionViewService;
//private String userName = SecurityContextHolder.getContext().getAuthentication().getName();
private String userName = "seller#seller.com";
private String firstName = "first";
private String lastName = "last";
private List<AuctionView> userProperty = new ArrayList<>();
#PostConstruct
public void init() { userProperty = auctionViewService.findByEmail(userName); //NULL POINTER EXCEPTION in this line
}
}
AuctionViewServiceImpl:
package application.service;
import application.dao.*;
import application.model.views.AuctionView;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.util.List;
#Service("auctionViewService")
public class AuctionViewServiceImpl implements AuctionViewService {
final static Logger LOGGER = Logger.getLogger(AuctionViewServiceImpl.class.getName());
private final AuctionViewDAO auctionViewDAO;
public AuctionViewServiceImpl(AuctionViewDAO auctionViewDAO) {
this.auctionViewDAO = auctionViewDAO;
}
#Override
public List<AuctionView> findAll() {
return auctionViewDAO.findAll();
}
#Override
public ResponseEntity<Object> findByType(String propertyType) {
return new ResponseEntity<>(auctionViewDAO.findByType(propertyType), HttpStatus.OK);
}
#Override
public List<AuctionView> findByEmail(String email) {
return auctionViewDAO.findByEmail(email);
}
}
faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config 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_1.xsd"
version="2.1">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>khn</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</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>
stacktrace: https://pastebin.com/iaBHUupQ
If needed i can attach more files and whole project structure, but problem is in importing AuctionViewService to SalesBean, or maybe in mixing JSF and Spring annotations
Ok, I changed #ManagedBean annotation to #Component, link AuctionViewService with #Autowire, and it works for me :) but how can I explain this situation?
package application.beans;
import application.model.views.AuctionView;
import application.service.AuctionViewService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Setter
#Getter
#ViewScoped
#Component
//#ManagedBean(name="SalesBean")
public class SalesBean implements Serializable {
#Autowired
private AuctionViewService auctionViewService;
//private String userName = SecurityContextHolder.getContext().getAuthentication().getName();
private String userName = "seller#seller.com";
private String firstName = "first";
private String lastName = "last";
private List<AuctionView> userProperty = new ArrayList<>();
#PostConstruct
public void init() { userProperty = auctionViewService.findByEmail(userName);
}
}
I use JSF with Spring Boot.
My problem is, that if I use the #javax.faces.bean.ManagedBean annotation I receive
javax.el.PropertyNotFoundException: Target Unreachable, identifier
[numberTest] resolved to null
I resolved the issue with put also the #Component annotation on the managed bean.
The other way was to put the Java classes in the WEB-INF.
My question is: both above-mentioned way seems to be bad and I think that they will cause trouble. What would be the solution to this problem?
I Googled a lot and tried every solution found.
(An additional fact, is that with #javax.annotation.ManagedBean the core JSP functions work (I didn't receive the error) but for example EL doesn't.)
Here is the code, in which with I receive the PropertyNotFoundException:
Configuration.java
import javax.faces.webapp.FacesServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication
#EnableAutoConfiguration
#EnableTransactionManagement
#EnableWebMvc
#Configuration
#EnableJpaRepositories(basePackageClasses = {})
#ComponentScan(basePackageClasses = { CLASSES_ARE_HERE })
public class Configuration {
public static void main(String[] args) {
SpringApplication.run(Configuration.class, args);
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.xhtml");
return servletRegistrationBean;
}
}
The managed bean:
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean
#ApplicationScoped
public class NumberTest {
private int theNumber=0;
public NumberTest() {
}
public void addOne() {
theNumber++;
}
public void addN(int n) {
theNumber+=n;
}
public int getTheNumber() {
return theNumber;
}
public void setTheNumber(int theNumber) {
this.theNumber = theNumber;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- Time in seconds that facelets should be checked for changes since last
request. A value of -1 disables refresh checking. -->
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>
<!-- Set the project stage to "Development", "UnitTest", "SystemTest", or
"Production". -->
<!-- An optional parameter that makes troubleshooting errors much easier. -->
<!-- You should remove this context parameter before deploying to production! -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>
faces-config.xml
<?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">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
The .xhtml
<!DOCTYPE html>
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui" encoding="UTF-8">
<html>
<h:head>
</h:head>
<h:body>
<h1>Szám</h1>
<h3>#{numberTest.theNumber}</h3>
<h:form>
<br></br>
<h:commandButton action="#{numberTest.addOne()}" value="Add one"></h:commandButton>
</h:form>
<h:form>
<br></br>
<h:inputText binding="#{input1}" />
<h:commandButton value="Add N" action="#{numberTest.addN(input1.value)}" />
</h:form>
</h:body>
</html>
</f:view>
I'm new to JSF development and do already have some troubles with the bean validation I can't get to worK:
As a Servlet container, I am using Tomcat 8.0.22 together with JSF 2.2 (Mojarra 2.2).
The problem is that the validation annotations in the code aren't being triggered.
For example, I've got a class customer with an attribute name, which is supposed to be filled by an <h:inputText>.
The input is passed problemless to the entity, but the annotated validations aren't triggered.
Neither #NotNull nor #Size or anything else is triggered, so I guess it's a problem with Tomcat rather than JSF.
I've got the following Jars:
bval-core-0.5.jar
bval-jsr303-0.5.jar
validation-api-1.0.0.GA.jar
in the WEB-INF/lib Folder of my WebApp and in the lib folder of Tomcat. Of course they're in the apps classpath as well.
I already tried it with the hibernate validator as well but can't get it running either.
I don't know what I'm not getting here and am thankful for any help!
Thanks in advance!
Benedikt
Here the code:
User.java:
package com.example;
import java.io.Serializable;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
#Size(min = 1, message = "Please enter username")
private String username;
#NotNull(message = "Please enter password")
private String password;
#NotNull(message = "Please enter email")
private String email;
private Date birthdate;
...
}
Register.java:
package com.example;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ViewScoped
public class Register implements Serializable {
private static final long serialVersionUID = 1L;
private User user;
#PostConstruct
public void init() {
user = new User();
}
public void submit() {
FacesMessage message = new FacesMessage("Registration succesful for: "
+ user.getUsername() + ", Username is null: " + (user.getUsername() == null));
FacesContext.getCurrentInstance().addMessage(null, message);
}
public User getUser() {
return user;
}
}
register.xhtml:
<!DOCTYPE html>
<html 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:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form id="Form">
<h:panelGrid columns="3">
<h:outputLabel for="username">Username</h:outputLabel>
<h:inputText id="username" value="#{register.user.username}">
<f:ajax event="blur" render="usernameMessage" />
</h:inputText>
<h:message id="usernameMessage" for="username" />
<h:outputLabel for="password">Password</h:outputLabel>
<h:inputSecret id="password" value="#{register.user.password}" redisplay="true">
<f:ajax event="blur" render="passwordMessage" />
</h:inputSecret>
<h:message id="passwordMessage" for="password" />
<h:outputLabel for="email">Email</h:outputLabel>
<h:inputText id="email" value="#{register.user.email}">
<f:ajax event="blur" render="emailMessage" />
</h:inputText>
<h:message id="emailMessage" for="email" />
<h:outputLabel for="birthdate">Birthdate (yyyy-MM-dd)</h:outputLabel>
<h:inputText id="birthdate" value="#{register.user.birthdate}">
<f:convertDateTime pattern="yyyy-MM-dd" />
<f:ajax event="blur" render="birthdateMessage" />
</h:inputText>
<h:message id="birthdateMessage" for="birthdate" />
<h:panelGroup />
<h:commandButton value="Register" action="#{register.submit}">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
<h:messages globalOnly="true" layout="table" />
</h:panelGrid>
</h:form>
</h:body>
</html>
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"
version="3.0">
<display-name>JSFFaceletsTutorial</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>*.jsf</url-pattern>
</servlet-mapping>
<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>
<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.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
What I have done to solve this problem is that I downloaded the Hibernate api for validation from hibernate-validator.
It comes with the required dependencies in the folder lib/required. I copied the hibernate validator jars and the required jars into the lib folder of Apache Tomcat 8.
You should not put those jars in the WEB-INF/lib of your application. I tried to put them there to see what would happen, but I had errors while deploying the app.
You might say that dropping libraries in the lib folder of Tomcat is not a good practice, but if you deploy your application that uses bean validation in Glassfish you won't have to do all this work because they come built in the JEEServer. This means that it is ok to have these libraries in your Apache Tomcat server.
I'm new in JSP and Servlets,
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<servlet>
<servlet-name>LoginPage</servlet-name>
<servlet-class>com.planner.servlet.LoginPage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginPage</servlet-name>
<url-pattern>/LoginPage</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContextBL.xml</param-value>
</context-param>
</web-app>
index.jsp file
<%# 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>
<form method="POST" action="/LoginPage">
<table border="1">
<tr>
<td>Login</td>
<td><input type="text" name="login" />
</td>
</tr>
<tr>
<td>Senha:</td>
<td><input type="password" name="pass" /></td>
</tr>
<tr>
<input type="submit" value="Entrar" />
</tr>
</table>
</form>
</body>
</html>
LoginPage.java
package com.planner.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* Servlet implementation class LoginPage
*/
public class LoginPage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginPage() {
super();
}
#Override
public void init() throws ServletException {
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
AutowireCapableBeanFactory bf = ctx.getAutowireCapableBeanFactory();
// bf.autowireBean(this);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> TESTE </title>");
out.println("</head>");
out.println("<body>");
out.println("Hello World!");
out.println("</body>");
out.println("</html>");
}
}
PROBLEM:
When I click on the submit button, it shows me the error:
**type Status report
message /Apontador_Web/LoginPage
description The requested resource is not available.**
And When I remove the tags "listener" and "context-param"
it loads the servlet.
What can be happening?
go to glashfish server output and look for an some exception
Tell me the name off exception
print all
You will need to add #WebServlet(urlPatterns={"/LoginPage"}) above your class name i.e public class LoginPage extends HttpServlet {