Over a million developers have joined DZone.

Exploring Spring Controller with JSTL View

DZone's Guide to

Exploring Spring Controller with JSTL View

Let’s improve our previous Spring JDBC application with some more exploration on Spring MVC’s Controller development.

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Let’s improve our previous Spring JDBC application with some more exploration on Spring MVC’s Controller development. I will show another exercise of writing a new Controller that processes a HTML form and use JSTL tags in JSP view pages.

To enable JSTL in Spring MVC application, you would need to add the following to the WebAppConfig config class. Let’s move it outside of WebApp.java and into it’s own top level class file insrc/main/java/springweb/WebAppConfig.java.

package springweb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

public class WebAppConfig {
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver result = new InternalResourceViewResolver();
return result;

Inside the InternalResourceViewResolver bean, you define where to find your JSP pages that may have JSTL tags in them. The prefix setter is a path in relative to your src/webapp location. This allow you to hide your JSP files completely if you want to. For example, by setting it to "/WEB-INF/jsp" then you may move and store all JSP files into src/webapp/WEB-INF/jsp which is private in the web application. The suffix is just the file extension. These two values allow you to return a view name inside the controller with just the basename of your JSP file, which can be short as "/myform" or "/index" etc.

If you are to use Tomcat as your web container, you would need to add JSTL jar dependency as well, since the Tomcat server doesn’t come with standard tag library! So add this into the pom.xml file now.


While you’re at the pom.xml file, you might want to add the Tomcat maven plugin so you can type less in command line when running your web application.


With that, you should able to run mvn tomcat7:run in root of your project without plugin prefix.

So what does JSTL bring to your application? Well, quite a bit actually. It lets you use some standard JSP tags that’s frequently used when writing JSP views. I will demonstrate this with a set of Controller and views to capture user comments from the application. Note that I will try to show you how to work with Spring Controller in the most basic way only. The Spring actually comes with a custom form JSP tag that is much more powerful to use. I will reserve that as another article in another time. Today let us focus on learning more about basic Spring Controller and JSTL, and a bit more on Spring JDBC data service as well.

We want to capture user comment, so let’s add a database table to store that information. Add the following DDL into your src/main/resources/schema.sql file. Again, this is for H2 database per last article project setup.


This time, we will write a data model class to match this table. Let’s addsrc/main/java/springweb/data/Comment.java

package springweb.data;

import java.util.Date;

public class Comment {
Long id;
String text;
String fromUrl;
String fromUser;
String fromUserIp;
String tag;
Date ts;

public Long getId() {
return id;

public void setId(Long id) {
this.id = id;

public String getText() {
return text;

public void setText(String text) {
this.text = text;

public String getFromUrl() {
return fromUrl;

public void setFromUrl(String fromUrl) {
this.fromUrl = fromUrl;

public String getFromUser() {
return fromUser;

public void setFromUser(String fromUser) {
this.fromUser = fromUser;

public String getFromUserIp() {
return fromUserIp;

public void setFromUserIp(String fromUserIp) {
this.fromUserIp = fromUserIp;

public String getTag() {
return tag;

public void setTag(String tag) {
this.tag = tag;

public Date getTs() {
return ts;

public void setTs(Date ts) {
this.ts = ts;

private String getTrimedComment(int maxLen) {
if (text == null)
return null;
if (text.length() <= maxLen)
return text;
return text.substring(0, maxLen);

public String toString() {
return "Comment{" +
"id=" + id +
", ts=" + ts +
", text='" + getTrimedComment(12) + '\'' +

public static Comment create(String commentText) {
Comment result = new Comment();
result.setTs(new Date());
return result;

Just as previous artcicle, we will write a data service to handle insert and retrieve of the data model. We add a new src/main/java/springweb/data/CommentService.java file

package springweb.data;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommentService {
public static Log LOG = LogFactory.getLog(CommentService.class);

private JdbcTemplate jdbcTemplate;
private SimpleJdbcInsert insertActor;
private RowMapper<Comment> commentBeanRowMapper = new BeanPropertyRowMapper<Comment>(Comment.class);

public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.insertActor = new SimpleJdbcInsert(dataSource)

public void insert(Comment comment) {
LOG.info("Inserting Comment + " + comment);

Map<String, Object> parameters = new HashMap<String, Object>(2);
parameters.put("TEXT", comment.getText());
parameters.put("FROM_USER", comment.getFromUser());
parameters.put("FROM_USER_IP", comment.getFromUserIp());
parameters.put("FROM_URL", comment.getFromUrl());
parameters.put("TAG", comment.getTag());
parameters.put("TS", comment.getTs());
Number newId = insertActor.executeAndReturnKey(parameters);

LOG.info("New Comment inserted. Id=" + comment.getId());

public List<Comment> findComments() {
String sql = "SELECT " +
"ID as id, " +
"TEXT as text, " +
"TAG as tag, " +
"TS as ts, " +
"FROM_USER as fromUser, " +
"FROM_USER_IP as fromUserIp, " +
"FROM_URL as fromUrl " +
List<Comment> result = jdbcTemplate.query(sql, commentBeanRowMapper);
LOG.info("Found " + result.size() + " Comment records.");
return result;

Since we did not use any fancy ORM but just plain JDBC, we will have to write SQL in the data service. But thanks to Spring goodies, it makes life much easier with helpers such as SimpleJdbcInsert, which handles DB insert and retrieval of auto generated key etc. And also notice that in query, we use the Spring’sBeanPropertyRowMapper to automatically convert JDBC resultset into a java bean Comment object! Simple, direct and quick.

Now we add the Spring controller insrc/main/java/springweb/controller/CommentController.java to handle web requests.

package springweb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import springweb.data.Comment;
import springweb.data.CommentService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class CommentController {

private CommentService commentService;

public ModelAndView comments() {
List<Comment> comments = commentService.findComments();
ModelAndView result = new ModelAndView("/comments");
result.addObject("comments", comments);
return result;

public String comment() {
return "comment";

@RequestMapping(value="/comment", method = RequestMethod.POST)
public ModelAndView postComment(HttpServletRequest req, @RequestParam String commentText) {
String fromUrl = req.getRequestURI();
String user = req.getRemoteUser();
String userIp = req.getRemoteAddr();
Comment comment = Comment.create(commentText);
ModelAndView result = new ModelAndView("comment-posted");
result.addObject("comment", comment);
return result;

In this controller we map /comment URL to handle display of the HTML form, which returns the comment.jspview. The method default to handle a HTTP GET. Note that we remapped same /comment URL to handle HTTPPOST on a separated postComment() method! See how clean the Spring Controller can be in this demo to handle HTTP request. Pay very close attention to the parameters declared in the postComment() method. Spring automatically handles the HTTP request object and map to your method just based upon the types you declared! On some cases you need to be explicit with the help of annotation such as @RequestParam, but Spring does the parsing of HTTP request and extraction for you! This saves you tons of repeated boiler plate code if we were to write a direct Servlet code.

Now let’s see the view and how to use JSTL. The /comments URL is mapped tosrc/main/webapp/comments.jsp view file, which will list all Comment model objects.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:when test="${empty comments}">
<p>There are no comments in system yet.</p>
<table border="1">
<c:forEach items="${comments}" var="comment" varStatus="status">
<tr valign="top">
<%-- The c:out will escape html/xml characters. --%>
<td><pre><c:out value="${comment.text}"/></pre></td>

Pretty standard stuff on JSTL. Next is the HTML form to post comment in src/main/webapp/comment.jspfile.

<form action="comment" method="POST">
<textarea name="commentText" rows="20" cols="80"></textarea>
<input type="submit" value="Post"/>

When form is posted and processed successful, we simply return to a new page insrc/main/webapp/comment-posted.jsp file as output.

<p>Your comment has been posted. Comment ID=${comment.id}</p>

If you've done these right, you should able to run mvn tomcat7:run and browsehttp://localhost:8080/spring-web-annotation/comment to see the form. Go to /comments URL to verify all the comments posted.

Note that despite I used Spring Controller as backend, all the views are in basic JSTL, and even the form are just basic HTML elements! I did this so you can see how flexible Spring Controller can be.

I know these are lot of code to post as a blog article today, but I wanted to be complete and try to show a working demo with tutorial notes. I choose to make it into a single post with file content instead of having you download a project somewhere else. It makes my notes and explanation easier to match onto the code.

And that will conclude our tutorial for today. Please leave a note if you find this helpful.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

java ,frameworks ,spring ,tips and tricks

Published at DZone with permission of Zemian Deng, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}