ASP.NET MVC and EntityFramework

1) Create a new “ASP.NET MVC 4” project called “schoolDB”
2) Create a new folder called “database”
schoolDB.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace schoolDB.Database
{
    public class Student
    {
        public int studentID { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
    }

    public class SchoolDBContext : DbContext
    {
        public SchoolDBContext()
            : base("schooldb")
        {
        }
        
        public DbSet<Student> students { get; set; }
    }
}

3) Create student model (place file in “Models” folder)
StudentModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace schoolDB.Models
{
    public class StudentModel
    {
        [Required(ErrorMessage = "First Name cannot be empty")]
        [Display(Name = "First Name: ")]
        public string firstName { get; set; }

        [Required(ErrorMessage = "Last Name cannot be empty")]
        [Display(Name = "Last Name: ")]
        public string lastName { get; set; }
    }
}

4) Create student controller (place in “Controllers” folder)
StudentController.cs

using schoolDB.Database;
using schoolDB.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace schoolDB.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {

            using (schoolDB.Database.SchoolDBContext db = new Database.SchoolDBContext())
            {
                List<Student> students = db.students.ToList();
                ViewBag.students = students;
            }
            return View();
        }

        public ActionResult Add()
        {
            return View("StudentForm");
        }

        [HttpPost]
        public ActionResult Add(StudentModel model)
        {
            if (ModelState.IsValid)
            {
                using (schoolDB.Database.SchoolDBContext db = new Database.SchoolDBContext())
                {
                    Student s = new Student() { firstName = model.firstName, lastName = model.lastName };
                    db.students.Add(s);
                    db.SaveChanges();
                }
                return RedirectToAction("index");
            }
            return View("StudentForm");
        }

        public ActionResult Edit(object id)
        {
            StudentModel model = new StudentModel();
            using (schoolDB.Database.SchoolDBContext db = new Database.SchoolDBContext())
            {
                int ID = Int32.Parse(id.ToString());
                Student s = db.students.Where(m => m.studentID == ID).SingleOrDefault();
                if (s != null)
                {
                    model.firstName = s.firstName;
                    model.lastName = s.lastName;
                }
            }
            return View("StudentForm", model);
        }

        [HttpPost]
        public ActionResult Edit(object id, StudentModel model)
        {
            if (ModelState.IsValid)
            {
                using (schoolDB.Database.SchoolDBContext db = new Database.SchoolDBContext())
                {
                    int ID = Int32.Parse(id.ToString());
                    Student s = db.students.Where(m => m.studentID == ID).SingleOrDefault();
                    if (s != null)
                    {
                        s.firstName = model.firstName;
                        s.lastName = model.lastName;
                        db.SaveChanges();
                    }
                    return RedirectToAction("index");
                }
            }
            return View("StudentForm", model);
        }

        public ActionResult Delete(object id)
        {
            using (schoolDB.Database.SchoolDBContext db = new Database.SchoolDBContext())
            {
                int ID = Int32.Parse(id.ToString());
                Student s = db.students.Where(m => m.studentID == ID).SingleOrDefault();
                if (s != null)
                {
                    db.students.Remove(s);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("index");
        }
    }
}

5) Create the Views (create a folder “student” and place files in the folder)
index.cshtml

@model schoolDB.Models.StudentModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>index</title>
</head>
<body>
    @Html.ActionLink("Add Student", "Add")
    <table border="1">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th></th>
            <th></th>
        </tr>
        @{
            var students = ViewBag.students;
            foreach(schoolDB.Database.Student s in students)
            {
                <tr>
                    <td>@s.firstName</td>
                    <td>@s.lastName</td>
                    <td>@Html.ActionLink("Edit", "Edit", new { Id = s.studentID })</td>
                    <td>@Html.ActionLink("Delete", "Delete", new {Id = s.studentID})</td>
                </tr>
            }
        }
    </table>
</body>
</html>

StudentForm.cshtml

@model schoolDB.Models.StudentModel

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.firstName)
    @Html.TextBoxFor(m => m.firstName)
    <br />
    @Html.ValidationMessageFor(m => m.firstName)
    <br />
    
    @Html.LabelFor(m => m.lastName)
    @Html.TextBoxFor(m => m.lastName)
    <br />
    @Html.ValidationMessageFor(m => m.lastName)
    <br />
    
    <input type="submit" value="Submit" />
}

6) go to http://localhost:(your port #)/student

Simple Forms using MVC in Spring (Java) with Ajax

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.

Simple Forms using MVC in Spring (Java)

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

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.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.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;

public class SearchModel {
	@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.")
	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.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

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 void create(SearchModel search, HttpServletResponse response)
	{
		Set<ConstraintViolation<SearchModel>> failures = validator.validate(search);

		try {
			if (!failures.isEmpty()) {
				response.getWriter().print("Search failed. Reason(s): ");
				response.getWriter().println();
				for (ConstraintViolation<SearchModel> constraintViolation : failures) {
					response.getWriter().println(constraintViolation.getMessage());
				}
			}
			else
			{
				response.getWriter().println("You searched for: " + search.getSearchTerm() + 
						" in category " + db.getCategory().get(search.getCategory()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@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>
</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>
		<br>
		<br>
		<form:label	id="searchTermLabel" for="searchTerm" path="searchTerm" cssErrorClass="error">Search: </form:label>
		<form:input path="searchTerm" /><form:errors path="searchTerm" />
		<br>
		<p>
			<input id="create" type="submit" value="Create" />
		</p>
	</form:form>

</body>
</html>

6) 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 />
 
 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</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";
	}

7) Create/Modify the web.xml

<?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
8) Run on Tomcat. The address should be “http://localhost:8080/SimpleProject/search&#8221;

Simple Forms using MVC in ASP.net

1) Create a new “ASP.NET MVC 3 Web Application” in Visual Studio Web Developer.

2) Create a simple database class (used for retrieving data)
Optional: Create a folder for the database class

SearchDB.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2
{
    public class Category
    {
        public Category(int id, string name)
        {
            this.id = id;
            this.name = name;
        }
        public int id { get; set; }
        public string name { get; set; }
    }

    public class SearchDB
    {
        public SearchDB()
        {
            List<Category> l = new List<Category>();
            Category s1 = new Category(10, "Computers");
            l.Add(s1);
            s1 = new Category(11, "TV");
            l.Add(s1);
            s1 = new Category(12, "Tablets");
            l.Add(s1);

            categories = l;
        }

        public List<Category> categories { get; set; }
    }
}

3) Create the model
Make sure to create the class in the “Models” folder

SearchModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
    public class category
    {
        public int id { get; set; }
        public string name { get; set; }
    }

    public class SearchModel
    {
        [Required(ErrorMessage = "Cannot be empty")]
        [Display(Name = "Search")]
        [RegularExpression("^[a-z]+$", ErrorMessage="Lowercase letters only")]
        public string searchTerm { get; set; }

        [Display(Name = "Category")]
        public int CategoryDDL { get; set; }
    }
}

4) Create controller
Make sure to create class in the “Controller” folder

SearchController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class SearchController : Controller
    {
        SearchDB db = new SearchDB();
        //
        // GET: /Search/

        public ActionResult Index()
        {
            ViewBag.CategoryDDL = new SelectList(db.categories, "id", "name");
            return View();
        }

        [HttpPost]
        public ActionResult Index(SearchModel search)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("SearchResults", search);
            }

            return View(search);
        }

        public ActionResult SearchResults(SearchModel search)
        {
            if (ModelState.IsValid == false)
            {
                return Content("Invalid Input!");
            }

            ViewBag.CategoryName = db.categories.Find(m => m.id == search.CategoryDDL).name;
            return View(search);
        }
    }
}

5) Create View
Make sure to create a new folder “Search” in “Views” folder
Index.cshtml

@model MvcApplication2.Models.SearchModel

@{
    ViewBag.Title = "ViewPage1";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@ViewBag.Message
@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.CategoryDDL)
    @Html.DropDownList("CategoryDDL")
    <br />
    <br />
                                  
    @Html.LabelFor(m => m.searchTerm)
    @Html.TextBoxFor(m => m.searchTerm)
    <br />
    @Html.ValidationMessageFor(m => m.searchTerm)
    <p>
        <input type="submit" value="Search" />
    </p>                            
}

SearchResults.cshtml

@model MvcApplication2.Models.SearchModel

<!DOCTYPE html>

<html>
<head>
    <title>Search Results</title>
</head>
<body>
    <div>
       You have searched for @Model.searchTerm in category @ViewBag.CategoryName
        <br />
        @Html.ActionLink("Back to Search", "Index")
    </div>
</body>
</html>

http://localhost:(port)/search