1) Create a new “Dynamic Web Project” in Eclipse. Name it “SimpleProject”.
Next, obtain the following jar files
hibernate-validator-4.3.0.Final.jar
jboss-logging-3.1.2.GA.jar
jstl-1.2.jar
spring-beans-3.2.0.M2.jar
spring-context-3.2.0.M2.jar
spring-core-3.2.0.M2.jar
spring-expression-3.2.0.M2.jar
spring-web-3.2.0.M2.jar
spring-webmvc-3.2.0.M2.jar
standard-1.1.2.jar
validation-api-1.0.0.GA.jar
jackson-core-asl-1.7.1.jar
Optional: Use maven to get the jar files. Put the following pom.xml in the same directory as your project
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy1</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>.\WebContent\WEB-INF\lib</outputDirectory>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2) Create a database class
package com.simplesearch.database;
import java.util.HashMap;
import java.util.Map;
public class SearchDB {
Map <Integer, String>category;
public Map<Integer, String> getCategory() {
return category;
}
public void setCategory(Map<Integer, String> category) {
this.category = category;
}
public SearchDB()
{
category = new HashMap<Integer, String>();
category.put(10, "Computers");
category.put(11, "TV");
category.put(12, "Tablet");
}
}
3) Create the model class
package com.simplesearch.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Range;
public class SearchModel {
@NotNull(message="Search cannot be null.")
@Size(min=1, message="Search cannot be empty.")
@Pattern(regexp="^[a-z]*$", message="Must contain letters only.")
String searchTerm;
@Range(min=10, max=12, message="Please select a category.")
@NotNull(message="Invalid category.")
int category;
public String getSearchTerm() {
return searchTerm;
}
public void setSearchTerm(String searchTerm) {
this.searchTerm = searchTerm;
}
public int getCategory() {
return category;
}
public void setCategory(int category) {
this.category = category;
}
}
4) Create the controller class
package com.simplesearch.controller;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.simplesearch.database.SearchDB;
import com.simplesearch.model.SearchModel;
@Controller
@RequestMapping(value="/search")
public class SimpleSearchController {
Validator validator;
SearchDB db;
public SimpleSearchController()
{
db = new SearchDB();
}
@Autowired
public SimpleSearchController(Validator validator)
{
this.validator = validator;
db = new SearchDB();
}
@RequestMapping(method=RequestMethod.GET)
public String getCreateSearch(Model model)
{
model.addAttribute("SearchModel", new SearchModel());
return "search/index";
}
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Map<String, String> create(@RequestBody SearchModel search)
{
Map<String, String> s = new HashMap<String, String>();
Set<ConstraintViolation<SearchModel>> failures = validator.validate(search);
if (!failures.isEmpty()) {
for (ConstraintViolation<SearchModel> constraintViolation : failures) {
s.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
}
}
return s;
}
@RequestMapping(value="searchResults", method=RequestMethod.GET)
public String getResult(Model m, HttpServletRequest request)
{
SearchModel s = new SearchModel();
Map<java.lang.String,java.lang.String[]> rMap = request.getParameterMap();
String []category = rMap.get("category");
String []searchTerm = rMap.get("searchTerm");
if(category != null)
{
try
{
int cat = Integer.parseInt(category[0]);
s.setCategory(cat);
}catch(Exception e)
{
}
}
if(searchTerm != null)
{
s.setSearchTerm(searchTerm[0]);
}
Set<ConstraintViolation<SearchModel>> failures = validator.validate(s);
if (!failures.isEmpty()) {
m.addAttribute("errorMessages", "Invalid input");
}
else
{
m.addAttribute("categories", db.getCategory());
m.addAttribute("searchModel", s);
}
return "search/searchResults";
}
@ModelAttribute("category")
protected Map<Integer, String> categoryList(HttpServletRequest request) throws Exception {
return db.getCategory();
}
}
5) Create the views
Create folder “views” under WEB-INF then create folder “search” under “views”
Create index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search</title>
<script type="text/javascript" src="<c:url value="resources/jquery-1.8.2.min.js" />"></script>
<script type="text/javascript">
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(document).ready(function() {
$("#SearchModel").submit(function() {
$("#category_error").hide();
$("#searchTerm_error").hide();
var search = JSON.stringify($('form').serializeObject());
$.ajax({
'type':'POST',
'url':'',
'contentType': 'application/json',
'data': search,
'dataType': 'json',
'success': function(data) {
if(data.category != null)
{
$("#category_error").show();
$("#category_error").html(data.category);
}
if(data.searchTerm != null)
{
$("#searchTerm_error").show();
$("#searchTerm_error").html(data.searchTerm);
}
if(data.category == null && data.searchTerm == null)
{
window.location.replace("search/searchResults?" + $('form').serialize());
}
}
});
return false;
});
});
</script>
</head>
<body>
<form:form modelAttribute="SearchModel" action="search" method="post">
Category:
<form:select path="category">
<form:option value="0">--Select--</form:option>
<form:options items="${category}" />
</form:select>
<div id="category_error" style="display:none"></div>
<br>
<form:label id="searchTermLabel" for="searchTerm" path="searchTerm" cssErrorClass="error">Search: </form:label>
<form:input path="searchTerm" /><form:errors path="searchTerm" />
<div id="searchTerm_error" style="display:none"></div>
<br>
<p>
<input id="create" type="submit" value="Create" />
</p>
</form:form>
</body>
</html>
Create searchResults.jsp
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search</title>
</head>
<body>
${errorMessages}
<c:if test="${searchModel != null}">
You searched for ${searchModel.searchTerm} in category: ${categories[searchModel.category]}
</c:if>
</body>
</html>
Create welcome.jsp in the “views” folder
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:redirect url="search" />
</body>
</html>
6) Create “resources” folder in WebContent folder (same level as WEB-INF). Put jquery js file in resources folder
7) Create the context configuration in WEB-INF folder
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for @Components to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="com.simplesearch" />
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="welcome" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Note: Make sure to replace “com.simplesearch” with your package.
Optional: If this configuration is not present, you will need to provide the full path in the get request.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
For example:
Without the configuration
@RequestMapping(method=RequestMethod.GET)
public String getCreateSearch(Model model)
{
model.addAttribute("SearchModel", new SearchModel());
return "/WEB-INF/views/search/index.jsp";
}
With the configuration
@RequestMapping(method=RequestMethod.GET)
public String getCreateSearch(Model model)
{
model.addAttribute("SearchModel", new SearchModel());
return "search/index";
}
8) Create/Modify the web.xml (in WEB-INF)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SimpleSearch</display-name>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Note: Make sure “/WEB-INF/servlet-context.xml” points to your spring configuration
Finally,
go to http://localhost:8080/SimpleProject in your browser.