Stripes Framework - context returns null - java

Stripes ActionBeanContext is returning null on all pages where I try to call it.
Here's my shortened ActionBean code:
package stripesbook.action;
public class InitialInfoActionBean implements ActionBean {
private ActionBeanContext context;
public void setContext(ActionBeanContext Context) {
this.context = Context;
}
public ActionBeanContext getContext() {
return this.context;
}
#DefaultHandler
public Resolution nextPage() throws Exception {
return new ForwardResolution("/estimate-info.jsp").addParameter("id", id);
}
}
Here's my 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">
<description>Perceptive Calculator</description>
<display-name>Perceptive Calculator</display-name>
<filter>
<display-name>Stripes Filter</display-name>
<filter-name>StripesFilter</filter-name>
<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
<init-param>
<param-name>ActionResolver.Packages</param-name>
<param-value>stripesbook.action</param-value>
</init-param>
<init-param>
<param-name>ActionBeanContext.Class</param-name>
<param-value>stripesbook.action.PerceptiveActionBeanContext</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>StripesFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>StripesFilter</filter-name>
<servlet-name>StripesDispatcher</servlet-name>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>StripesDispatcher</servlet-name>
<servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StripesDispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
I'm not doing anything on my .jsp page except setting the bean with <jsp:useBean id="actionBean" class="stripesbook.action.InitialInfoActionBean" /> and checking for null context with ${ actionBean.context == null }
When posting back to the ActionBean, I'm able to perform various operations but in most cases, setContext never even gets hit.

Figured this out. Instead of
<jsp:useBean id="actionBean" class="stripesbook.action.InitialInfoActionBean" />`
I needed to be using
<stripes:useActionBean beanclass="stripesbook.action.InitialInfoActionBean" executeResolution="false" event="populate" var="actionBean" />
Apparently the regular useBean tag doesn't populate the context.

Related

Spring #Autowired gives new instance instead of initialized session scoped bean

I am developing application using Spring and I need to initialize Ticket object in session and then get it from another controller.
I have two controllers, so there are two xml contexts.
web.xml
<web-app id="WebApp_ID" 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>Spring Web MVC Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/index-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
rest-context.xml
<beans ...>
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="menu.MenuController"/>
</beans>
index-context.xml
<beans ...>
<mvc:annotation-driven/>
<mvc:resources mapping="/**" location="/"/>
<context:annotation-config/>
<bean class="auth.IndexWebController" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
In the spring-context I have my Ticket bean:
<bean id="tickerProvider" class="TicketProviderImpl" scope="session">
<aop:scoped-proxy/>
together with the other beans.
This are what my controllers look like:
IndexWebController.java
#Controller
#SessionAttributes("user")
public class IndexWebController {
private static Logger logger = LoggerFactory.getLogger(IndexWebController.class);
#Autowired
private TicketProviderImpl ticketProvider;
#ModelAttribute("user")
public User populateUser() {
return new User();
}
#RequestMapping(value = "/", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView printIndex(#ModelAttribute("user") User user,
#RequestParam(value = "iv-user", required = false) String login,
#RequestParam(value = "iv-groups", required = false) String groups) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index.html");
<...>
ticketProvider.setLogin(login);
logger.info("Пользователь установлен в " + login);
<...>
MenuController.java
#Controller
public class MenuController {
#Autowired
private TicketProviderImpl ticketProvider;
#ResponseBody
#RequestMapping("/getMenuList")
public MenuListDTO getMenuList(
#RequestParam(value = "menuId", required = true, defaultValue = "-1") long menuId,
#RequestParam(value = "parentId", required = true, defaultValue = "0") long parentId) {
<...>
System.out.println(ticketProvider.getLogin());
<...>
}
}
The problem is that when I autowire ticketProvider bean in the MenuController I get a new instance of it, not those that has been initialized in the IndexWebController. Actually I get null, but waiting for the login.
Where is the mistake or some misunderstanding of using session scoped beans?
According to this you will need another listener to expose your session to the application.
Hence adding <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> should do the trick.

Configure Jackson for Google App Engine

Is there any way to configure Jackson (ConfiguredObjectMapper) which is used for serializing servlet responses?
#Api(name = "rates",
version = "v1",
title = "Rates API")
public class RatesApi {
static Logger LOG = Logger.getLogger(RatesApi.class.getSimpleName());
#ApiMethod(name = "getLatestRates",
path = "latest",
httpMethod = HttpMethod.GET)
public RatesEnvelope getLatestRates(#Named("base") String base) throws BadRequestException,
InternalServerErrorException {
try {
RatesInfo ratesInfo = DatabaseUtils.getLatestRates(base);
return new RatesEnvelope(ratesInfo.getDate(), base, ratesInfo.getTimestamp(), ratesInfo.getRates());
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
} catch (com.googlecode.objectify.NotFoundException e) {
throw new InternalServerErrorException("no available rates");
}
}
}
My problem is RatesEnvelope class contains BigDecimal fields which should be configured with mapper.enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN); to avoid E notation.
web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<servlet>
<servlet-name>CurrencyWebserviceServlet</servlet-name>
<servlet-class>PACKAGE_NAME.backend.servlet.OpenExchangeRatesWebserviceServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>SystemServiceServlet</servlet-name>
<servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value>PACKAGE_NAME.backend.spi.RatesApi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CurrencyWebserviceServlet</servlet-name>
<url-pattern>/cron/fetchlatest</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SystemServiceServlet</servlet-name>
<url-pattern>/_ah/spi/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>all</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<filter>
<filter-name>ObjectifyFilter</filter-name>
<filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ObjectifyFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- Next three lines are for request dispatcher actions -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
Create an instance of Jackson ObjectMapper. Configure as needed by enabling or disabling features you need. Modify your Spring configuration to use it instead of default one. Java configuration would look something like this:
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
It looks like you're using Cloud Endpoints Frameworks, which doesn't use Jackson annotations. In your case, you'd use an ApiTransformer to achieve what you want. As an example:
#ApiTransformer(RatesEnvelopeTransformer.class)
public class RatesEnvelope {
private BigDecimal someBigDecimalField;
// ...
}
public class RatesEnvelopeTransformer implements Transformer<BigDecimal, String> {
public String transformTo(BigDecimal in) {
return in.toPlainString();
}
public BigDecimal transformFrom(String in) {
return new BigDecimal(in);
}
}

After Spring Security authentication get HTTP Status 404 error

while processing injection of spring security to my web app i get problem HTTP Status 404 error. When i try to get access for my pages first of all i get login page which is auto config, after typing login and password which is correct i get HTTP Status 404 error. Code below
web.xml
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml, /WEB-INF/application-security.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
application-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/main/**" access="hasRole('ROLE_USER')" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="adminpassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user" password="userpassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller
#Controller
#RequestMapping(value = "/main")
public class MainController {
#Autowired
DeputesAppealService deputesAppealService;
#Autowired
DeputesAppealDao deputesAppealDao;
#RequestMapping(value = "/mainFrame", method = RequestMethod.GET)
public String getMainPage(){
return "mainPage";
}
#RequestMapping(value = "/resultOfSearching", method = RequestMethod.GET)
public String getSearchResult(Model model, #ModelAttribute("searchChar")String searchResult) {
List<DeputesAppeal> deputesAppeals = deputesAppealService.abstractSearch(searchResult);
model.addAttribute("ListOfAppeals", deputesAppeals);
return "searchingResultPage";
}
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String getAddNewAppealPage(){
return "addPage";
}
#RequestMapping(value = "/new", method = RequestMethod.POST)
public String addNewAppeal(#ModelAttribute("Appeal")DeputesAppeal deputesAppeal) {
deputesAppealService.add(deputesAppeal);
return "mainPage";
}
#RequestMapping(value = "/deleted", method = RequestMethod.GET)
public String deleteAppeal(#RequestParam(value = "id", required = true) Long id, Model model){
deputesAppealService.delete(id);
model.addAttribute("id", id);
return "deletedPage";
}
#RequestMapping(value = "/editPage", method = RequestMethod.GET)
public String GetEdit(#RequestParam(value = "id", required = true) Long id, Model model){
model.addAttribute("editedAppeal", deputesAppealService.getById(id));
return "editPage";
}
#RequestMapping(value = "/editPage", method = RequestMethod.POST)
public String editCurrentAppeal(#ModelAttribute("userAttribute") DeputesAppeal deputesAppeal,
#RequestParam(value = "id", required = true)Integer id, Model model) {
deputesAppeal.setNumber(id);
deputesAppealService.edit(deputesAppeal);
model.addAttribute("id", id);
return "editedPage";
}
}
Just see if you have springSecurityFilterChain defined in your web.xml
<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>
You also need to change Login URL as well
<c:url value="/j_spring_security_check" var="loginUrl" />
and use this in your form action:
<form action="${loginUrl}" method="post">

Why do I get static text/html when returning a 404 Response with Java / Jersey?

I'm working with Java, Jetty and Jersey 2.18 (latest for now) hosted on a Google App Engine.
Let say I have a service such that
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/{userId}")
public Response getUser(#PathParam("userId") String userId)
{
...
}
When I do:
return Response.ok()
.entity(user)
.build();
I correctly receive an application/json content-type and body.
But when I do:
return Response
.status(404)
.entity(new ResponseModel(100, "user not found"))
.build();
same as for returning any 4XX or 5XX status, I receive a text/html content-type along with this HTML body:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404 Not Found</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Not Found</h1>
</body>
</html>
and not the object I put in .entity()
Edit: Here is my web.xml
<?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>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.mypackage.services;org.codehaus.jackson.jaxrs</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
org.glassfish.jersey.server.gae.GaeFeature;
org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
org.glassfish.jersey.media.multipart.MultiPartFeature;
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.feature.Trace</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattytern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>ObjectifyFilter</filter-name>
<filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ObjectifyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring Security Filter -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml </param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>GlobalResponseFilter</filter-name>
<filter-class>com.mypackage.GlobalResponseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GlobalResponseFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-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>
<security-constraint>
<web-resource-collection>
<web-resource-name>everything</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- ** -->
<!-- ** General session timeout in minutes -->
<!-- ** -->
<session-config>
<session-timeout>1440</session-timeout>
</session-config>
</web-app>
ResponseModel is just a basic serializable java class :
import java.io.Serializable;
public class ResponseModel implements Serializable
{
private static final long serialVersionUID = 1L;
private int code;
private Serializable data;
public ResponseModel()
{
}
public ResponseModel(int code, Serializable data)
{
System.err.println("Code " + code + " : " + data);
this.code = code;
this.data = data;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public Serializable getData()
{
return data;
}
public void setData(Serializable data)
{
this.data = data;
}
}
Can you try again with the following configuration:
<servlet>
<servlet-name>API</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
...
<init-param>
<param-name>jersey.config.server.response.setStatusOverSendError</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
This flag defines if Jersey - when sending a 4xx or 5xx response status - uses ServletResponse.sendError(flag is false) or ServletResponse.setStatus (flag is true).
Calling ServletResponse.sendError usually resets the response entity and headers and returns a (text/html) error page for the status code.
Since you want to return an own custom error entity, you need to set this flag to true.

I can't map my Servlet with my JSP

I have a problem for mapping my servlet with my Java Server Page, using the JSF framework and especially the commandLink tag.
When I click on the commandLink it only reload the same productList.jsp.
Here is my map web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.4">
<display-name>Epimarket</display-name>
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>com.epimarket.controller.EpimarketServlet</servlet-class>
<init-param>
<param-name>listURL</param-name>
<param-value>productList.jsp</param-value>
</init-param>
<init-param>
<param-name>editURL</param-name>
<param-value>productEdit.jsp</param-value>
</init-param>
<init-param>
<param-name>errorsURL</param-name>
<param-value>errors.jsp</param-value>
</init-param>
</servlet>
<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
<init-param>
<param-name>maxFileSize</param-name>
<param-value>20m</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.PRETTY_HTML</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
<param-value>true</param-value>
</context-param>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>/do/*</url-pattern>
</servlet-mapping>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Here is the faces-config.xml
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<application>
<locale-config>
<default-locale>fr</default-locale>
</locale-config>
</application>
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>productList</from-outcome>
<to-view-id>/productList.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>productEdit</from-outcome>
<to-view-id>/productEdit.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>chart</from-outcome>
<to-view-id>/chart.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Here is my link to create a new Product (access editProduct.jsp page)
<h:commandLink id="createProductLink" value="Ajouter un produit" action="/do/edit"/>
Prefix h is for
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
And finally my doGet and doEditProduct methods in my Servlet :
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
if (initErrors.size() != 0)
{
req.setAttribute("erreurs", initErrors);
getServletContext().getRequestDispatcher(urlErrors).forward(req, res);
return ;
}
String reqType = req.getMethod().toLowerCase();
String action = req.getPathInfo();
if (action == null)
action = "/list";
if (reqType.equals("get") && action.equals("/list"))
{
doProductList(req, res);
return ;
}
if (reqType.equals("get") && action.equals("/delete"))
{
doDeleteProduct(req, res);
return ;
}
if (reqType.equals("get") && action.equals("/edit"))
{
doEditProduct(req, res);
return ;
}
if (reqType.equals("post") && action.equals("/validate"))
{
doValidateProduct(req, res);
return ;
}
doProductList(req, res);
}
private void doEditProduct(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
int id = Integer.parseInt(req.getParameter("id"));
Product product = null;
if (id != -1)
product = service.getProduct(id);
else
{
product = new Product();
product.setId(new BigDecimal(-1));
}
req.setAttribute("editError", "");
req.setAttribute("id", product.getId());
req.setAttribute("name", product.getName());
req.setAttribute("description", product.getDescription());
req.setAttribute("price", product.getPrice());
getServletContext().getRequestDispatcher((String)params.get("editURL")).forward(req, res);
}
Thank you for your help
With JSF you must not used servlets. You use managed beans.
In order to fix the above code, you should provide an action method, and invoke that method from your command button. In order to get more into the spirit of JSF, I'd suggest starting with a tutorial and/or a sample JSF probject.

Categories