Showing posts with label JavaEE. Show all posts
Showing posts with label JavaEE. Show all posts

AOP with Spring

Our Spring Boot Web Application is starting making sense. As we have seen in the previous post, the controller is wired to a bean, a Knight, that is wired to another bean, a Quest. When the URI /quest is accessed, the RESTful service's nature of the controller enters in the game and, following all the wiring down to the bottom, what the caller gets is the message generated by the embark() method of the actual Quest objected involved.

Now we want to introduce a class that follows a different perspective, a Minstrel whose raison d'ĂȘtre is singing when a Knight starts and ends a Quest. It's behavior is orthogonal to "normal" way we look at our code. We think at what a minstrel is interested in, we let it know to Spring, and just rely on it. In Aspect Oriented Programming (AOP) terms, Mistrel becomes an aspect of our application.

The nice point in AOP is that only the aspect, here Minstrel, has to know about what is going on. Knight could stay in its blissful ignorance on the matter, performing its mission as nothing as changed. Here I have changed the concrete Knight implementation just to add a line of log in its doQuest() method, that would help us in seeing the system at work. I have written more on Spring log in another post.

To use AOP in Spring Boot, you have to add a dependency in your application POM file. STS helps you not to forget it, anyway, groupId is org.springframework.boot and artifactId spring-boot-starter-aop. Besides, I should give to Spring some way to know which aspects it has to work with. We can do it through a XML file or a Java class configuration AspectJ style. I prefer the second way.

So I created a SpringInActionConfig class where I specified the bean that is actually an aspect:
@Configuration
@EnableAspectJAutoProxy
public class SpringInActionConfig {
    @Bean
    public Minstrel minstrel() {
        return new Minstrel();
    }
}
Notice the two annotations on the class and the bean annotation on its method that just creates a new Minstrel and returns it.

I have implemented Minstrel in this way, again using the Spring AspectJ support:
@Aspect
public class Minstrel {
    private final Log log = LogFactory.getLog(Minstrel.class);

    @Before("execution(public String Knight.doQuest())")
    public void singBeforeQuest() {
        log.info("Fa la la, the knight is so brave!");
    }

    @After("execution(public String Knight.doQuest())")
    public void singAfterQuest() {
        log.info("Tee hee hee, the brave knight did embark on a quest!");
    }
}
The class is annotated as Aspect, and it has two annotated method, one that has to be executed before the Knight doQuest() method, the other after.
Notice the AspectJ sintax. It looked a bit weird to me the first time, however it makes sense. I have used a very plain and comprehensible notation, it could get much more cryptic. On the other side, it is quite powerful.

Now, when we run our application we should not see any change in its behavior, but in its log, that now should have in it something like that:

I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of the classic xml configuration.

Full code on github.

Go to the full post

Wiring components in Spring

After mock testing the components structure of my Spring Web application, I am ready to create a real Knight - Quest couple and see how to wire them together.

Firstly, I create a concrete Quest, SlayDragonQuest, and I let Spring know, through annotations, that it is a component and it is qualified as quest.
@Component
@Qualifier("quest")
public class SlayDragonQuest implements Quest {
    public String embark() {
        return "Embarking on quest to slay the dragon!";
    }
}
Then I modify my BraveKnight to let Spring know that it is a component too, named knight, and that it is autowired to the component that is qualified as quest.
@Component("knight")
public class BraveKnight implements Knight {
    // ...
    @Autowired
    public BraveKnight(@Qualifier("quest") Quest quest) {
        this.quest = quest;
    }
 // ...
}
Let's have a look to the KnightController.
@RestController // 1
public class KnightController {
    @Resource
    private Knight knight; // 2

    @RequestMapping("/quest")
    public String quest() { // 3
        return knight.doQuest();
    }
}
1. It is annotated as a RestController, so Spring would use it as a RESTful service.
2. Its knight field is annotated as resource, so Spring would try to inject in it a component named as its type (but starting with a lowercase letter), meaning, the BraveKnight.
3. Any request to the /quest URI is mapped to this method.

I only have to run it:

If something is not clear on this last step, you may get some hints from the previous Hello Spring Boot post.

I have written this code while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. It diverges a bit from the original version, since I have developed a Maven Spring Boot Web project, and here I have used annotations instead of the classic xml configuration to signal beans to Spring and wire them together.

Full code on github.

Go to the full post

Mock test on a Spring resource

Following the first chapter of Spring in Action, Fourth Edition by Craig Walls, I'm about to use the constructor injection (a Dependency Injection technique) to implement a IoC (Inversion of Control) relation between a Knight and its own Quest. No disrespect is meant, however I slightly change the original code to adapt it to a standard Boot Maven STS Spring Starter Project with Web dependency.

I put my SpringBootApplication in the dd.sia.knights package, and I created a couple of sub-packages, controller and logic. In the first one I have put a RestController, named KnightController, that owns a Resource Knight and performs a RequestMapping between the URI /quest and the method quest():
@RestController
public class KnightController {
    @Resource
    private Knight knight;

    @RequestMapping("/quest")
    public String quest() {
        return knight.doQuest();
    }
}
I put all the classes rooted in the Knight and Quest interfaces in the logic sub-package. They both have a single method, doQuest() and embark(), returning a String.

Constructor Injection

I created a concrete BraveKnight that implements Knight and has as private field a Quest. Which Quest a particular BraveKnight has is decided at runtime, injecting the actual Quest through the constructor:
public class BraveKnight implements Knight {
  private Quest quest;

  public BraveKnight(Quest quest) {
    this.quest = quest;
  }

  public String doQuest() {
    return quest.embark();
  }
}

Mock Test with Mockito

Now we'd like to check if the class structure we designed works as expected. We can't perform normal unit test with JUnit for the reason that we don't currently have any concrete Quest to inject in our Knight. However we can mock-test it.

To do that we have to add a mokito dependency in our project POM, pom.xml, adding mokito-core from org.mockito for test scope. Then I added a JUnit-Mockito test case for BraveKnight with a single test function:
@Test
public void testDoQuest() {
    Quest quest = Mockito.mock(Quest.class); // 1
    BraveKnight knight = new BraveKnight(quest); // 2
    knight.doQuest(); // 3
    Mockito.verify(quest, Mockito.times(1)).embark(); // 4
}
1. A mock Quest is created.
2. Injecting the mock quest in a BraveKnight.
3. Call the knight method.
4. Ensure that the embark() method of my mock quest has been called once in this context.

Full source code is on github in the springInAction folder.

Go to the full post

Plain MVC Spring project

Nowadays, if you create a new Spring project on STS, the most natural option is using the Spring Starter Project wizard that is going to push you to use Spring Boost. Say that for some reason you don't want to do that, you could fallback to the pre-boot era, here is how, in a few steps.

Basically, you just have to call the Spring Legacy Project, from menu File - New. There you just have to choose a project name and select which template you want to use. Usually Spring MVC Project is a good choice.

Next step would be specify the top level package for you application. And then the wizard would do all the job for you.

Just one thing more, when you get back the control, you'd better update the project through Maven, by right click on the project - Maven - Update Project. After that you should be ready to run the project on server.

Go to the full post

A simple IoC + DI Spring example

In the previous posts I have written a puny Spring Boot application example sporting a trivial RESTful controller Let's spice it up a bit, extracting the business logic from the controller and putting it in a hierarchy of classes. The interesting part of it is that I am going to do it using IoC (Inversion of Control) and DI (Dependency Injection).

I created a sub-package named control, and in it I put an interface, Greeter, that exposes the only method I really care of:
public interface Greeter {
    String greeting();
}
Then I refactored my GreetingController to use that interface to do the dirty job. Something like this:
public class GreetingController {
    private Greeter greeter;

    public String greeting() {
        return greeter.greeting();
    }
}
The reason for doing this should be clear. My controller won't care about the details of how a greeting is generated. It just knows that exists a hierarchy of classes rooted in the Greeter interface, and it would call its greeting() method when it intercepts a user call for this job.

Then I created a couple of concrete classes implementing Greeter. A mock one, thought to be used just in development, and the actual stuff designed to be used in production.
public class MockGreeter implements Greeter {
    private static final Log log = LogFactory.getLog(MockGreeter.class);

    @Override
    public String greeting() {
        log.debug("Generating mock greeting");
        return "mock hello!";
    }
}

public class PlainGreeter implements Greeter {
    private static final Log log = LogFactory.getLog(PlainGreeter.class);

    @Override
    public String greeting() {
        log.trace("Generating plain greeting");
        return "Hello!";
    }
}
I know, it is not easy to spot a difference between them. Let's assume they will grow and diverge to something more useful in the future.

The interesting stuff here is defining how the controller should know which Greeter to use. In the old pre-IoC days it would be its job to create a dependency with the selected Greeter, creating an object of a concrete type. Nowadays we prefer to do the other way round, we invert the control, and let the concrete Greeter signal its availability to be used by the controller to the framework (in this case Spring). We can do that in a few different ways, being annotation usually considered the preferred one.

The controller should tell to Spring in some way that a field it owns should be injected with a dependency (here is where DI enters in the game). There are a few ways to do it. I usually prefer to annotate the data member, like this:
@RestController
public class GreetingController {
    @Resource
    private Greeter greeter;

    // ...
}
On the other side, each Greeter implementation that could be selected from Spring for the controller should show it up:
@Component
public class MockGreeter implements Greeter {
    // ...
}
We still have a problem. We have two different implementations of Greeter competing to be injected to the controller. Which one should Spring choose?

One way of solving it is by configuration. We specify the spring.profiles.active property in the Spring application.properties file giving to it a value that would act as a selector for the appropriate Greeter. In my case, I want to play with two different configurations, dev and prod. When in development (dev) I want the mock greeter to be injected in the controller, while in production (prod) the plain greeter should be used.

In case of production my Spring configuration file would have this line in it:
spring.profiles.active=prod
My Greeter classes would be annotated in this way:
@Component
@Profile("prod")
public class PlainGreeter implements Greeter {
// ...
}

@Component
@Profile("!prod")
public class MockGreeter implements Greeter {
// ...
}

The complete Spring Boot project is on github. The relevant files are

Go to the full post

Spring log only to file

Logging is one of the most fuzzy area in Java. The standard JUL, java.util.logging, entered the arena late, and it has to compete against well respected libraries like Log4J2, SLF4J and Logback (usually SLF4J with Logback). The Spring guys decided to go for JCL, the Apache Commons Logging, that wraps SLF4J for the actual logging library of your choice, here being Logback.

If you don't have any special requirement, you can happily ignore which actual logger is used, just write your code for the JCL interface, leaving out of your scope any low level dependency.

However, if you want your log going to a file, and not to console, as often is the case, you have to deal with the actual logger. Not a big deal, if Logback is your choice.

Let's modify the function greeting in my GreetingController to log some (un)useful comments:
public String greeting() {
 log.trace("trace hello");
 log.debug("debug hello");
 log.info("info hello");
 log.warn("warn hello");
 log.error("error hello");
 log.fatal("fatal hello");
 return "Hello!";
}
Where log is private static final object of type org.apache.commons.logging.Log initialized through the JCL LogFactory.

This could be enough. Still you should have a mildly surprising output, something like:
2016-05-30 22:14:00.888  INFO (...)  : info hello
2016-05-30 22:14:00.888  WARN (...)  : warn hello
2016-05-30 22:14:00.888 ERROR (...)  : error hello
2016-05-30 22:14:00.888 ERROR (...)  : fatal hello
I edited out details in the middle of the lines, I want to focus on the fact that we miss trace and debug messages, and the fatal one became an error one. If you really want fatal log messages, logback is not your choice, since it does not have this log level, and so they are mapped as simple errors.

The first problem could be easily solved adding an entry in the Spring application.properties file (in source/main/resources). Say that I want to log all messages, from trace up to fatal, generated in my packages rooted in dd.manny. I'll add this line:
logging.level.dd.manny=trace
Good. Now I want Spring to log to a file. By default the file will have name spring.log, and I can decided in which folder to be placed like this:
logging.path=/tmp
Nice and easy. Just one thing. I wanted the log to go exclusively to file. To get this effect I have to configure the actual logger.

For this reason I added a logback configuration file in the src/main/resources folder that is mimic of the default Spring one, but it has no appender for console. The key point is that I keep the log level to INFO and I specify FILE as appender, that is going to be set through the property specified above.

The full Spring Boot project is on github. The relevant files are GreetingController.java, application.properties, and logback.xml.

Go to the full post

A simple RESTful Web Service

In the previous post, I have created a very simple WebApp using Spring Boot. Even if it works fine, it isn't much of a fun, giving no feedback whasoever to the user. Let's add a first basic web service to it.

In the Spring jargon, we want a REST Controller, so I create a new subpackage named controller below the one containing the application class, and in there I put a class, GreetingController, that is going to perform the mapping between the URI and the service, and return the expected resource.

The beauty of the Spring implementation is that I create a plain class, called a Bean, not to be confused with Java Bean nor Enterprise Java Bean, and I just annotate the class as @RestController and the method as @RequestMapping:
@RestController
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting() {
        return "Hello!";
    }
}
That's it. Springs takes care of all the boring details, and lets Tomcat answer generating a document that contains only "Hello" to a request address to the greeting address.

To test if this is working as expected, we can now start the project from the Boot Dashboard, and then accessing the resource from the internal browser, or from an external one. In any case the result should be something like this:
If you wonder why and how I'm using a non-standard Tomcat port, please refer to the previous post.

Sure you can run the application outside STS. Calling maven on the package target would let it generate a jar named something like hello-0.0.1-SNAPSHOT.jar in the target folder, than you can run it with the java -jar command.

Source code is on github. The only relevant change from the previous version is the GreetingController.

Go to the full post

Hello Spring Boot

Creating a web app with the Spring Framework using Boot is quite easy, assuming you have already installed Spring Tool Suite, the Pivotal IDE based on Eclipse.

Actually, it is just a matter of selecting on the menu File, the item New, and there Spring Starter Project. There you are presented with a bunch of names to give and selection to make, I'd suggest you to check start.spring.io for inspiration, since this STS wizard it is nothing more than a proxy to that web page, that would guide you to the creation of a Spring application.

I named my project helloSpring, and then I kept all the main default settings, like the Maven support, jar generation, Java 1.8 language usage, and I only added one single item in Dependencies: Web.

What it is going to happen is that my Spring project would generate a single huge jar embedding Tomcat and all the required dependencies to let the application work. After confirming, Maven could take some time to get all the required jars. However in the end I'll have a nice project ready to be compiled. Even if it is not to do anything sensible at all.

I'd suggest you to have a look at the generated pom.xml file. You won't be surprise to find out that it shows the information you entered in the wizard.

Then, accessing the Project Explorer, you'll see in the Spring Elements a bean HelloSpringApplication (the prefix is the project name, if you chose a different name for it, you'll see the change reflected here).

Let's have a better look a this bean. I asked to the wizard to put the generated classes in the dd.manny.hello package, so there I'm going to find it.

There is not much to see, apart from that the class has been decorated with the @SpringBootApplication annotation, it contains a main() method that calls SpringApplication.run() passing the class itself. Even without knowing anything about Spring Boot, looks intuitive what is going on here. On startup Spring would see that this is the booting class, and would use its main to call the SpringApplication run() method.

Now I'd like to run this application, even I can't expect to get much feedback from it. The easiest way to do it, it is from the Spring Boot Dashboard. You should see that view in the bottom left of your STS window. If for any reason it is missing, you can get it back from Window - Show View - Spring - Boot Dashboard.

In the Boot Dashboard you should see a collapsed list named local. Open it and you should find your project. My one is there, named helloSpring. Now I can use the menu on the Boot Dashboard view, or right-click menu if I am in the mood for it, to start or restart it.

What I usually I get it now is a fat exception. This is because I have something else running on the 8080 port on my machine and STS is trying to run the embedded Tomcat for my application right on that port. If you get
java.net.BindException: Address already in use
You are having the same problem.

Not a big issue, tough. There is a file in the source/main/resources/ folder named application.properties that, not surprisingly, let us to set properties used by our application. Initially it is empty, I added this line:
server.port = 8585
Meaning that I want my Tomcat to use a different port from the standard one.

Now I can restart my application, and get a smooth startup, as showed by the error-free log in the Console view.

The full code for the project is on github.

Go to the full post

JSP servlet init parameters

Creating init parameters for a servlet is easy, when we need to do that for a JSP page it is only a bit more trickier, and we should remember a couple of details.

We can't use annotations, since the translation from JSP to servlet is not in our control. So we have to fall back to the Deployment Descriptor (DD). So, let's go in our web app WEB-INF directory and modify (maybe create) the web.xml file.

In the web-app element we need to create two elements, a servlet and a servlet-mapping, and in the servlet one we could create any init-param we need, just like we can do for a plain servlet.

Here is an example for a servlet element, based on a JSP page named counting.jsp placed in the web app root directory:
<servlet>
  <servlet-name>Counting</servlet-name>
  <jsp-file>/counting.jsp</jsp-file>
  <init-param>
      <param-name>base</param-name>
      <param-value>42</param-value>
  </init-param>
</servlet>
Notice the jsp-file element, that replaces what in a plain servlet is a servlet-class.

Then we need a servlet-mapping element, that should look something like this one:
<servlet-mapping>
  <servlet-name>Counting</servlet-name>
  <url-pattern>/counting.jsp</url-pattern>
</servlet-mapping>

And that's it. Now we can access that init parameter from our Counting JSP page.

For instance, we could be interested in accessing it when the JSP is initialized. In this case, we would override the jspInit() method and get it through getServletConfig(). Like this:
<%!
public void jspInit() {
    log("Config init param: " + getServletConfig().getInitParameter("base"));
}
%>
If we want to access it from a scriplet, we use the config implicit object:
<%= config.getInitParameter("base") %>

Go to the full post

Learning Apache Maven 3

I have just finished watching to this Pack video course about Maven, on youtube there is a preview that shows what you can expect from it.

It is designed to follow a Java programmer who knows nothing about Maven from the absolute beginning to writing a multi module project.

The major emphasis is on Maven for Windows plus Eclipse, just at the beginning it is shown how to install Maven on Linux and Mac, and how to integrate it also in Intellij and NetBeans. This is not a big issue, since we are in the Java world, and the platform differences are usually not too harsh.

The course is structured in four parts. After the installation/integration done in the introduction, we are guided to write a first "hello world" application. The third block is about creating a Web App by Maven that uses features from Struts2, Hibernate, and Spring. The last part shows how to develop a client/sever multi module project.

I found the standard price for this course a bit excessive, but in this bargains season, at less than five bucks, I wouldn't see how to complain.

It works fine as an introduction to the matter, in a couple of hours you can't expect to become a Maven master, but I'd say it succeeds in giving a good overview.

It has a few weak spots, too. Mainly, the audio comment is not lively at all, and there is a curious alternation in voices that I found distracting. Hear this, for instance, at around 1.30:

Go to the full post

Maven 3 video course

I have got a pointer to this video course on Apache Maven 3, you could also find a preview on YouTube that gives the gist of it.

It is a couple of hours long, it looks to be designed as an introduction to Maven for a Java developer who has no (or little) previous knowledge of it.

Since I use Maven in an unstructured way, it would probably good for me to find the way to spend time watching it. I plan to do it in the near future, and writing something more about it.

Go to the full post

Google App Engine Setup

You can develop a web application for Google App Engine in Java, Python, and Go. I did it in Java, and here is a report of what I have done, from nothing till having a very simple web app running on appspot.com.

If you don't have any strong argument against Eclipse, it should a good idea to pick that IDE to develop for App Engine, and the reason is that Google makes available a plugin that would simplify a bit your job.

Currently are available plugins for Eclipse Europa, Ganymede, Galileo, Helios, and Indigo. You can install it directly from Eclipse, by the Software Update feature. If this does not work, firewall issues are a common reason for that, you can download the zipped plugin, and install it in Eclipse as a "New software".

Once the plugin is installed, we can run a testing version of the Google App Server locally. From the shell we go in a bit obscure directory, under eclipse\plugins, should be named something like:
com.google.appengine.eclipse.sdkbundle_1.6.1.v201112160242r37\appengine-java-sdk-1.6.1\
From there we can run the Application Server, in developing mode, passing to it as parameter the directory where it could find a .WAR file created for the Google App Engine.

For instance, to run the demo application Guestbook, we call:
> bin\dev_appserver.cmd demos\guestbook\war
You could have some error (again, a firewall issue could be the culprit), but if in the end you get the confirmation on the server going up and running on http://localhost:8080/, and:
The admin console is running at http://localhost:8080/_ah/admin
You are ready to open your favorite browser on localhost and see the test web application running locally.

Pay attention to the port number. If you run the server "by hand", as we have just seen, it is 8080, but when you run it from Eclipse the 8888 port number is used.

Go to the full post

Filter

Filters are Java components similar to servlets that are used to filter the connection between client and servlets.

To create a filter we implements the Filter interface, specifying what it should do in the doFilter() method.

In the DD we could declare the filter (if we don't use the annotations that are now available) and we map the filter with the resources we want they want to interact with.

Let's see an example where the filter simply log the user name (when available) for any request sent to a servlet named with the extension ".do".

The class implementation:
package ch13;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

@WebFilter( filterName = "BeerRequest",
description = "log the caller",
urlPatterns = { "/BeerReqFilter" })
public class BeerReqFilter implements Filter {
    private FilterConfig fc;

    public void init(FilterConfig fConfig) throws ServletException {
        this.fc = fConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
        String name = ((HttpServletRequest)request).getRemoteUser();
        if(name != null) {
            fc.getServletContext().log("User: " + name + " is updating");
        }
        else {
            fc.getServletContext().log("Remote user name not available");
        }

        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}
The doFilter() accepts Servlet Request and Response as parameter, we normally have to downcast them to the appropriate Http subclass in the method body.

At the end of the job, we pass explicitely the control to the next filter (or servlet) in the chain.

If we need, we could specify init parameters for the filter using the initParams attribute. For example, if we want to use a special log file, we can set it in this way:
initParams = @WebInitParam(name="LogFileName", value="UserLog.txt")
In the DD we specify when the filter should be used, like this:
<filter-mapping>
<filter-name>BeerRequest</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Filters are discussed in chapter twelve of Head First Servlet and JSP.

Go to the full post

Expression Language functions

We can add some function support from Java to EL. Not much, actually, but in this context we should care only of presentation, so we shouldn't expected to have a large need of functions here.

The fundamental limitation is that we can use just public static method defined in a plain old Java class. Than we should describe in a Tag Library Descriptor (usually called TLD file), that is an XML file that should be made available to the project being stored under the /WEB-INF directory. Finally we should put a taglib directive in our JSP page to let the function declaration be in the scope.

The function

Let's say we want to show a random number in (1 .. 6) to the user, so we write this class:
package ch08;

public class DiceRoller {
    public static int rollDice() {
        return (int) ((Math.random() * 6) + 1);
    }
}
The Tag Library Descriptor

Now we create a new file in the WEB-INF folder named something like myFunctions.tld, and we put in it this stuff:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib 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/web-jsptaglibrary_2_0.xsd"
        version="2.0">
    <tlib-version>1.2</tlib-version>
    <uri>DiceFunctions</uri>
    <function>
        <name>rollIt</name>
        <function-class>ch08.DiceRoller</function-class>
        <function-signature>int rollDice()</function-signature>
    </function>
</taglib>
I get a few warning from Eclipse on the first line of the file, but you could safely ignore them. I reckon the support to TLD is just not that good.

Notice that we actually renamed the int ch08.DiceRoller.rollDice() to rollIt(), that is now the name we should use in our JSP page.

The taglib tag

In our JSP page we put this taglib directive before the html tag:
<%@ taglib prefix="mine" uri="DiceFunctions"%>
The uri we use here is the one we have defined in our TLD file. The prefix is the one we should call to have access in the JSP page to the functions defined in our TLD.

The function call

So now we can write the code that call our function:
You get: ${mine:rollIt()}
I wrote this post while reading the eighth chapter of Head First Servlet and JSP, a good book to read if you are interested in this stuff.

Go to the full post

Accessing init parameter

Expression Language helps us to get easier the init context parameters. These are parameters that are not servlet specific, but an application-wide available.

First thing, we should put a parameter in the web.xml. Here is my Deployment Descriptor (DD) file with the definition of the param-name:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
        version="3.0">
    <context-param>
        <param-name>emailAddr</param-name>
        <param-value>my@email.address</param-value>
    </context-param>
</web-app>
We already know how to read that parameter in a servlet, going through the servlet context:
System.out.println(this.getServletContext().getInitParameter("emailAddr"));
and we know how to do the same in a JSP page using the implicit application object:
email is: <%= application.getInitParameter("emailAddr") %>
With the Expression Language it is even easier:
email is: ${initParam.emailAddr}
Actually, the name used as EL implicit object, initParam, is a bit misleading, since it is used for accessing the context-param elements. But, well, we have to bite the bullet and use it as it is.

I firstly wrote this post as a comprehension exercise while reading the eighth chapter of Head First Servlet and JSP, it's a good book to read if you are interested in this stuff.

Go to the full post

Easy cookie with EL

When writing a JSP page we have to cope with the fact that there is no getCookie() method in the request object, just a get-all getCookies(). This means that getting just a single cookie is kind of painful. We have to get all of them, and then scan the array of cookie till we find what we are actually looking for.

Good news is that this complexity is hidden when we use the Expression Language.

A servlet creates a cookie:
Cookie cookie =
    new Cookie("accessTime", "time " + System.currentTimeMillis());
response.addCookie(cookie);
In a JSP page we want to get it:
<%
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        if ((cookies[i].getName()).equals("accessTime")) {
            out.println("My cookie: " + 
                cookies[i].getValue() + "<br />");
        }
    }
%>
Lot of code for such a simple task. Using the EL we can use the implicit object cookie:
<br />Cookie via EL: ${ cookie.accessTime.value}
A good place to read more on the EL-cookie relation is chapter eight of Head First Servlet and JSP.

Go to the full post

Implicit object and scope

Usually we don't specify the scope where an attribute lays, we rely instead on the fact that EL go through all the scopes looking for it - and gets the first one with that name.

But sometimes is good to know that we can use a scope implicit object.

Avoid name conflict

We can't always assume we are choosing, or using, unique names for our attributes, so using the EL scope implicit object could save us some headache.

For instance, referring to the code seen in the previous post, writing
${musicMap.Indie}
has the same result as writing
${requestScope.musicMap.Indie}

"Bad" name for attribute

An attribute name is just a string, we could use almost anything there. But we should use our freedom with a bit a common sense. More to the point, it is not a good idea to call an attribute using the Java class convention. Because, if we create an attribute in this way
request.setAttribute("foo.person", p); // bad attribute name!
we have the unpleasent side-effect we can't access the attribute in a JSP page in this way:
${foo.person.name}
because the containers expects foo being an attribute, and person one of its properties.

The obvious solution would be not to use such kind of names. But there is another solution, thanks to the scope implicit object and the [] operator:
${requestScope["foo.person"].name}
Head First Servlet and JSP is the book I was reading when I firstly wrote this post.

Go to the full post

EL - the [] and . operators

Using Expression Language, we can access components of a JavaBean, array, list, map, both with the square brackets "[]" operator or the dot "." operator.

Let's slightly modify the servlet we defined in the previous post, putting an array of Strings in a request attribute:
String[] favoriteMusic = {"Subsonica", "Tocotronic", "Bilk", "Baustelle"};
request.setAttribute("musicList", favoriteMusic);
In the JSP page we can access the elements of the array using the [] operator.
<h2>Using EL: [] for array</h2>
<br />First song is by: ${musicList[0]}
<br />Second song is by: ${musicList["1"]}
It is worth spending a few words on the second line: the string "1" is converted to integer, and then the number is used as index to retrieve the second element of the array.

Now we create a list in our servlet:
java.util.ArrayList<String> favoriteFood = new java.util.ArrayList<String>();
favoriteFood.add("hazelnut icecream");
favoriteFood.add("fajitas");
favoriteFood.add("veggie pizza");
favoriteFood.add("anything in dark chocolate");
request.setAttribute("favoriteFood", favoriteFood);
And we access it in the JSP in the same way. Moreover, we can also use the list as a valid object for EL, since a list has a good override to the toString() method:
<h2>Using EL: [] for list</h2>
Foods are: ${favoriteFood}
<br />
<br />First food is ${favoriteFood[0]}
<br />Second food is ${favoriteFood["1"]}
For JavaBeans and maps make sense using both notation. We define a map in the servlet:
java.util.Map<String, String> musicMap = new java.util.HashMap<String, String>();
musicMap.put("Ambient", "Zero 7");
musicMap.put("Surf", "Tahiti 80");
musicMap.put("DJ", "BT");
musicMap.put("Indie", "Bilk");
request.setAttribute("musicMap", musicMap);
And we use it in the JSP page:
<h2>Using EL: [] or . for JavaBeans and Maps</h2>
Music map is: ${musicMap}
<br />
<br />Ambient is by: ${musicMap.Ambient}
<br />Yes, ambient is by ${musicMap["Ambient"]}
We should be careful and not mix incorrectly the two notations: ${musicMap[Ambient]} won't work as expected, since Ambient is not an object available to the code in the JSP page.

If we defined in the servlet this array:
String[] musicTypes = {"Ambient", "Surf", "DJ", "Indie"};
request.setAttribute("MusicType", musicTypes);
We could use nested expressions in the JSP page, like this:
<h2>Using EL: nested expression</h2>
${MusicType[0]} music is by ${musicMap[MusicType[0]]}
MusicType[0] is evaluated to "Ambient", so it could be used as an acceptable key for the musicMap.

For more information on the subject, I suggest you to read the eighth chapter of Head First Servlet and JSP.

Go to the full post

Expression Language and JavaBeans

It is easy to access a JavaBean in a JSP page, if the bean itself does not represent a complex entity.

It gets a bit more akward if we our bean has attributes other than Strings or primitives. Expression Language is a key feature in this context.

Let's write an example that uses a Person JavaBean, designed in this way:
package ch08;

public class Person {
    private String name;
    private Dog dog;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Dog getDog() {
        return dog;
    }
}
Where the Dog class is this:
package ch08;

public class Dog {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Given that, in a servlet we write the doPost() method in this way:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    Person p = new Person();
    p.setName("Evan");

    Dog dog = new Dog();
    dog.setName("Spike");
    p.setDog(dog);

    request.setAttribute("person", p);
    RequestDispatcher view = request.getRequestDispatcher("person.jsp");
    view.forward(request, response);
}
We create a person, Evan, who has a dog named Spike, and we put it as attribute named "person" in the request scope. Then we forward the call to the person.jsp page.

In our JSP page we want to display the dog's name to the user. We can do that quite easily, but verbosely, using the scripting capabilities:
<h2>Using scripting</h2>
Dog's name is:
<%= ((ch08.Person) request.getAttribute("person")).getDog().getName() %>
This should be easy to understand, at least for a Java developer. Maybe not so for a HTML expert.

Trying to use the standard actions, we could think to rewrite that piece of code in this way:
<h2>Using standard actions</h2>
<jsp:useBean id="person" class="ch08.Person" scope="request" />
Dog's (object) name is: <jsp:getProperty name="person" property="dog" />
But the result is not what one usually expects. The issue is that the property "dog" of "person" is printed using the toString() method. We'd better add an override to it in the Dog class:
@Override
public String toString() {
    return name;
}
We don't need to modify our Dog class if we use the Expression Language (EL) instead. And we get a code that is way simpler to write, read, and mantain:
<h2>Using EL - Expression Language</h2>
Dog's name is: ${person.dog.name}
See the eighth chapter of Head First Servlet and JSP for more on the matter.

Go to the full post

Eclipse and Web Application

I originally wrote this post at the end of 2010, so now it is slightly outdated, when I ported the Beer Selector Web Application, originally written on NetBeans, to Eclipse. But the changes relevant here are minimal, so this post could still be useful for some readers.

I had Java 6 and Tomcat 7 already installed on my (Windows 7) machine, what I missed was just the IDE itself.

Installing Eclipse

I went to the Eclipse Web Tools Platform downloads page and I got a recent build (your choice, be daring or more conservative as you like). I downloaded the zipped file, put it somewhere on my machine, unzip it, and specify in the eclipse.ini file how to reach the java virtual machine, specifying the -vm option:
-vm
C:\Program Files (x86)\Java\jdk1.6.0_20\bin\javaw.exe
Then I started Eclipse, and I went on for creating a new project. The shortcut to do that is Ctrl-N. What I wanted to create was a "Dynamic Web Project", you'll find it in the Web folder.

I gave a fancy name to the project, specified the target runtime accordingly to my container (Apache Tomcat 7) and clicked the Finish button. After that I saw in the project explorer a folder for my new web app.

Model

The beer selection is done by a POJO so I created a Java class in the project Java Resources folder:
package ch03;

public class BeerExpert {
    public String getBrand(String color, String body) {
        StringBuilder brand = new StringBuilder("Our");

        if(body.equals("light"))
            brand.append(" Wishwash ");
        else if(body.equals("medium"))
            brand.append(" GoodOl' ");
        else
            brand.append(" McCoy ");

        brand.append(color);
        return brand.toString();
    }
}
Control

Time to create the servlet BeerSelector. You can do that in a number of way, for instance you can right click on the Deployment Descriptor (DD), then in the "New..." menu item you'll find a "Servlet" item to click and start the wizard process to generate a servlet.

I specified the Java package (ch03) and the class name (BeerSelector), then clicked on next, to use a URL mapping, "/BeerSelector.do", different from the default one. I confirmed, and let the wizard doing its job.

The doGet() asks the BeerExpert for a beer name and then forward to a JSP page for displaying the result. The doPost() simply calls doGet():
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    String color = request.getParameter("color");
    String body = request.getParameter("body");
    String beer = new BeerExpert().getBrand(color, body);
    request.setAttribute("beer", beer);

    RequestDispatcher view = request.getRequestDispatcher("beerSelection.jsp");
    view.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    this.doGet(request, response);
}
View

I created a couple of pages in the current WebContent folder.

The user access to the Beer Selector via an HTML page that sports a form like this:
<h1 align="center">Beer Selection Page</h1>
<form method="POST" action="./BeerSelector.do">
    <p>Select beer characteristics ...</p>
    <p>Color:
    <select name="color">
        <option value="light">light</option>
        <option value="amber">amber</option>
        <option value="brown">brown</option>
        <option value="dark">dark</option>
    </select></p>

    <p>Body:
    <select name="body">
        <option value="light">light</option>
        <option value="medium">medium</option>
        <option value="heavy">heavy</option>
    </select></p>

    <p><input type="SUBMIT"></p>
</form>
And the feedback is shown in beerSelection.jsp, where the main point in it, is represented by this line:
Our beer recommendation: <%= request.getAttribute("beer") %>

Go to the full post