Saturday, January 28, 2017

Model value ${} is not displayed in the JSP

The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used with XML or annotation-based Spring configurations. Sometimes, it will make you to scratch your head, when things not working. Recently i encountered a wired problem while working on the Spring MVC project, me trying to set a value into a model, and display the value in JSP via EL, e.g ${name}, but it just outputs the result as it is – ${name}, not the “value” stored in the model.

Controller

 @Controller  
 public class HelloController {  
      @RequestMapping("/hello")  
      public String hello(Model model) {  
           model.addAttribute("name", "John Doe");  
           return "welcome";  
      }  
 }  

JSP File

 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Home Page</title>  
      <link rel='stylesheet' href='<c:url value="/resources/css/style.css" />' type='text/css' media='all' />   
 </head>  
 <body>  
      <h2>Hello World, Spring MVC</h2>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
 </body>  
 </html>  

Everything looks good in the above, then what makes the jsp page just to dump the EL script as it is. Actually the issue is caused by the old JSP 1.2 descriptor. If you are using the old JSP 1.2 descriptor, defined by DTD ,for example web.xml. The EL is disabled or ignored by default, you have to enable it manually, so that it will outputs the value store in the "name" model.

JSP 1.2 web.xml
 <!DOCTYPE web-app PUBLIC  
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
 <web-app>  
  <display-name>Archetype Created Web Application</display-name>  
 </web-app>  

So you just add the following tag <%@ page isELIgnored="false" %> , this will resolve the issue.

JSP 2.0
If you are using the standard JSP 2.0 descriptor, defined by w3c schema ,for example web.xml. The EL is enabled by default, and you should see the value stored in the "name" model, which is "John Doe".

 <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">  
 //...  
 </web-app>  

Happy Programming...!!!

Sunday, October 9, 2016

Maven cannot find richfaces 3.3.X artifact

As part of our technology upgrade, we just changed our deployment process to use Maven from Ant. As part of that while configuring the RichFaces 3.3.3.Final, i was getting artifact missing error in the pom.xml. When i looked into the details, it seems to that RichFaces related jar was not located in the central maven repository, it was maintained in the JBoss Maven repository. So you have to update your maven settings.xml to look into the JBoss Maven repository to download the jar and its dependencies.

There are two locations where a maven settings.xml file may live:

The directory where you have installed the maven: ${maven.home}/conf/settings.xml
The user specific directory: ${user.home}/.m2/settings.xml

If you haven't installed specifically the .m2 will not have setting.xml, in that case, what you have to do is copy the settings.xml into the user specific .m2 directory. And update the configuration details provided in the below link Maven to use JBoss Repository. After updating the settings, just update your project, the rich faces and its dependent jar will get downloaded from the JBoss Maven repository.

Happy Programming...!!!

Tuesday, July 19, 2016

java.lang.StackOverflowError at javax.servlet.http.HttpServletResponseWrapper.setStatus(HttpServletResponseWrapper.java:201)

You may encounter this error while working on upgrading your project from JSF 1.* to 2.0. To err is human, we would have updated all our JAR files, refactored our code to use the latest features and annotations etc. But when you start your server, you will see the error, and it will go in the infinite loop. The issue is because of the we haven't update our faces-config.xml DOCTYPE to use latest version. It should be the in the old version. You have to change the version

From

 <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_1_2.xsd"  
        version="1.2">  

To

 <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_0.xsd"  
   version="2.0">  

Just change the xsd version as above, that's all.

Happy Programming...!!!

Sunday, May 8, 2016

java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute

By default, Spring MVC throws an exception when errors occur during request binding. This usually not what we want – instead we should be presenting these errors to the user. We’re going to use a BindingResult by adding one as an argument to our controller method:

 @RequestMapping(value="/addEmployee", method=RequestMethod.POST)  
      public String addEmployees(BindingResult result, @ModelAttribute("employee") Employee employee,  
                Model model, final RedirectAttributes redirectAttributes){  

The BindingResult argument needs to be positioned right after our form backing object – it’s one of the rare cases where the order of the method arguments matters. Otherwise we’ll run into the following exception :


java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply:
public java.lang.String controller.EmployeeController.addEmployees(org.springframework.validation.BindingResult,entity.Employee,org.springframework.ui.Model,org.springframework.web.servlet.mvc.support.RedirectAttributes)


To correct the above exception, just change order of the parameter, where your binding result parameter has to be just after the ModelAttribute as below

      @RequestMapping(value="/addEmployee", method=RequestMethod.POST)  
      public String addEmployees( @ModelAttribute("employee") Employee employee,  
                BindingResult result, Model model, final RedirectAttributes redirectAttributes){  


Happy Programming...!!!

Sunday, March 27, 2016

javax.servlet.ServletException: Circular view path []: would dispatch back to the current handler URL [/] again - Junit

While running a Standalone Junit Test for Spring Controller, sometimes you may incur the below exception, and your test will fail. This is because, when you don't declare or configure the ViewResolver in UnitTest, Spring registers a default InternalResourceViewResolver which creates instances of JstlView for rendering the View.

javax.servlet.ServletException: Circular view path [addExpense]: would dispatch back to the current handler URL [/addExpense] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
 at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:292)
 at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:214)
 at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
 at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)

To resolve the issue, we need to configure the ViewResolver, in the setup method of the Test class, Below is the sample code to do that. In the setup method, i have initialized the InternalResourceViewResolver, and assigned it to the viewResolver of standaloneSetup of MockMvcBuilder, this will resolve the issue.

public class ExpenseControllerTest {
 
    @InjectMocks
    private ExpenseController expenseController;
 
    private MockMvc mockMvc;

    @Before
    public void setup() {
  
 // Process mock annotations
        MockitoAnnotations.initMocks(this);

        // Setup Spring test in standalone mode
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp");
        viewResolver.setSuffix(".jsp");
        this.mockMvc = MockMvcBuilders.standaloneSetup(expenseController).setViewResolvers(viewResolver).build();       
    }

    @Test
    public void testAddExpense() throws Exception{
  
 mockMvc.perform(get("/addExpense"))
        .andExpect(status().isBadRequest())
        .andExpect(view().name("addExpense"));
    }
}


Happy Programming.

Tuesday, March 15, 2016

Error: Could not find or load main class com.sun.tools.internal.xjc.XJCFacade - Eclipse

When your eclipse project libraries are not pointing to JDK, and instead it is pointing to the JRE, you will get this error "Error: Could not find or load main class com.sun.tools.internal.xjc.XJCFacade". If the JDK path was not configured in your installed JRE's please do the following.

From Eclipse Click File > Properties, select Java Build Path and select Libraries Tab.
In the Libraries Tab, select the JRE system library and click Edit, which will pop up a window.

Then click Installed JREs, button, which will pop up a window, which will display the JRE installed, as below.



Now Click Add, and provide the path, where your java jdk have been installed. In the below image, i have configured the path, where my Java JDK has been installed. Once set the path, it will fetch all the JRE libraries under that folder, as shown below.



Once you clicked finish button, the JDK entry will be shown in the Installed JREs window. Now select the newly added path and click apply. Now in the JRE System library window, Click on the Alternate JRE dropdown, it will list the jdk which was added by us, select that and click finish. This will change your JRE System library point to the JDK, what we have installed. Now select the xsd file and generate the JAXB classes, it will generate the classes successfully without any error.

Happy Programming.


Saturday, November 7, 2015

Composite Component in JSF

Any component is essentially a piece of reusable code that behaves in a particular way. JSF 2 composite tag library facilitate you to create reusable components Facelets from the existing components. In this tutorial we will learn, how to create a simple composite component (registerComp.xhtml), a user registration form, which comprises name and email fields and a submit to button to process the action.

A composite component is a Facelet that resides in a resource library. So the component you are going to create must reside under the resource folder. Let's say if you are going to put the components under the folder named customcomponent. The Directory structure of your project will look like this below. Here the folder name resource is a must, except the resource folder name, all other folders and file names are user defined.



Now we will see, what are the contents, we need to place in our registerComp.xhtml, which we have created.

1) First we need to define the Composite Namespace in the html header as shown below

 <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:composite="http://java.sun.com/jsf/composite"  
    >  
 ...  
 </html>  

2) Next Composite Tags. Below are the some of the tags available, but we will be using the composite:interface, composite:attribute and composite:implementation for our simple example.

Tag Description
composite:interface Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. Within the tag ( parent tag ) you can add the children tags to it according to the implementation requirements. In short it is used to declare the configurable values which are exposed to the developer who use it.
composite:implementation Defines the implementation of the composite component. If a composite:interface element appears, there must be a corresponding composite:implementation. It is used for implementing the composite components declared in the composite:interface. To access the component interface attributes an expression #{cc.attrs.attribute_name} is used (cc is a reserved keyword in JSF).
composite:attribute Declares an attribute that may be given to an instance of the composite component in which this tag is declared. This tag can be used inside the tag by a zero or many times according to the requirement. This tag can also be nested inside the other tag
composite:insertChildren Any child components or template text within the composite component tag in the using page will be reparented into the composite component at the point indicated by this tag’s placement within the composite:implementation section.
composite:valueHolder Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of javax.faces.component.ValueHolder suitable for use as the target of attached objects in the using page.
composite:editableValueHolder Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of javax.faces.component.EditableValueHolder suitable for use as the target of attached objects in the using 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://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:composite="http://java.sun.com/jsf/composite"  
    >  
   <!-- INTERFACE -->       
   <composite:interface>  
        <composite:attribute name="userNameLable" />  
        <composite:attribute name="userNameValue" />  
        <composite:attribute name="emailLable" />  
        <composite:attribute name="emailValue" />  
        <composite:attribute name="registerButtonText" />  
        <composite:attribute name="registerButtonAction"   
             method-signature="java.lang.String action()" />  
   </composite:interface>  
   <!-- IMPLEMENTATION -->  
   <composite:implementation>  
      <h:form>  
           <h:panelGrid columns="2" id="textPanel">  
                #{cc.attrs.userNameLable} :   
                <h:inputText id="userName" value="#{cc.attrs.userNameValue}" />  
                #{cc.attrs.emailLable} :   
                <h:inputText id="email" value="#{cc.attrs.emailValue}" />  
           </h:panelGrid>  
           <h:commandButton action="#{cc.attrs.registerButtonAction}"   
                value="#{cc.attrs.registerButtonText}"  
           />  
      </h:form>  
   </composite:implementation>  
 </html>  

Now we have created the component, make sure that it resides in the resource folder.

3) Now let's see how to define this component for usage. Use the Custom Namespace

 <html xmlns="http://www.w3.org/1999/xhtml"    
   xmlns:h="http://java.sun.com/jsf/html"  
   xmlns:ui="http://java.sun.com/jsf/facelets">  
   xmlns:customcomponent="http://java.sun.com/jsf/composite/customcomponent">  

xmlns:customcomponent="http://java.sun.com/jsf/composite/customcomponent"
The first part defines that the namespace for the composite component is "customcomponent", and the second part declares where in the resources folder to find the definition of this composite component. In this example its in the "customcomponent" subfolder inside resources.



4) Now let's how to use and pass values to the Component

This is how you use the tag: namespace:FileName; in our example customcomponent:registerComp, registerComp is the name of the file, so by default its the tag name;

 <customcomponent:registerComp   
           userNameLable="Name"   
           userNameValue="Ramanujam"   
           emailLable="E-mail"   
           emailValue="reachram_ramesh@hotmail.com"  
           registerButtonText="Register"   
           registerButtonAction="#{register.userAction}"  
       />  

Above, we have passed the hard coded values to the userName and email and binded the submit to userAction in a managed bean named register

That's all we have created a new Composite Component. Now when you call the page, which has the defined composite component, you will see the form, which has username and email value hardcoded, and a submit button.

Happy Programming...!!!