Writing a simple web application using Spring MVC template
Based on the template we created let us start implementing a Spring MVC application, the application has a web interface, where given a brand it will display all the cars for that brand. To download the sample, click here. Download and import the pom.xml in STSIDE.
The car POJO looks as below,
@Entity
public class Car implements java.io.Serializable {
private String brand;
private String model;
private long Id;
//
private static final long serialVersionUID = 1L;
//
@Id
public long getId() {
return Id;
}
//
public void setId(long id) {
Id = id;
}
//
@Column
public String getBrand() {
return brand;
}
//
public void setBrand(String brand) {
this.brand = brand;
}
//
@Column
public String getModel() {
return model;
}
//
public void setModel(String model) {
this.model = model;
}
}
Once you defined the POJO you don’t need to do anything else, based on the configuration below in the root-context.xml,
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
When the SpringSource TC Server starts it will automatically create the database and the db schema with the entity name. In our case we have used hsqldb inmemory database.
CarDao interface and CarHibernateDao implementation is as below,
public interface CarDao {
List getCars(String brand);
//
List getCars();
}
//
@Repository
public class CarHibernateDao extends HibernateDaoSupport implements CarDao {
@Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
//
public List getCars(String brand) {
return getHibernateTemplate().find("from Car car where car.brand=?", brand);
}
//
public List getCarBrands() {
// TODO Auto-generated method stub
return getHibernateTemplate().find("select distinct car.brand from Car car");
}
}
CarService interface and CarSerivceImpl implementation is as below,
public interface CarService {
List getCars(String brand);
//
List getCarBrands();
}
//
@Service
public class CarServiceImpl implements CarService{
@Autowired
CarDao carDao;
//
public List getCars(String brand) {
// TODO Auto-generated method stub
return carDao.getCars(brand);
}
//
public List getCarBrandss() {
// TODO Auto-generated method stub
return carDao.getCars();
}
}
Controller code looks as below,
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
logger.info("Welcome home!");
//
return "index";
}
//
@RequestMapping(value = "/indexResponse", method = RequestMethod.GET)
public void indexResponse(HttpServletResponse response, @RequestParam String brand) throws JSONException, IOException {
logger.info("in indexResponse!");
//
List cars = carService.getCars(brand);
JSONArray array = new JSONArray();
//
for (Object obj : cars) {
Car car = (Car) obj;
JSONObject json = new JSONObject();
json.put("brand", car.getBrand());
json.put("model", car.getModel());
array.put(json);
}
handleJSONResponse(response, array.toString());
}
//
@RequestMapping(value = "/listCarsBrand", method = RequestMethod.GET)
public void listCarsBrand(HttpServletResponse response) throws JSONException, IOException {
logger.info("in listCars!");
//
List cars = carService.getCarBrands();
JSONArray array = new JSONArray();
//
for (Object obj : cars) {
String brand = (String) obj;
JSONObject json = new JSONObject();
json.put("brand", brand);
array.put(json);
}
handleJSONResponse(response, array.toString());
}
protected void handleJSONResponse(HttpServletResponse response, String jsonString) throws IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out;
out = response.getWriter();
out.print(jsonString);
out.flush();
}
WEB-INF/views/index.jsp file looks as below,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>spartanjava.com - Simple JSON sample</title>
<script src="${pageContext.request.contextPath}/static/jquery/jquery.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/static/js/scripts.js" type="text/javascript"></script>
</head>
<body>
<form>
<select id="brand">
</select>
<input id="butt1" type="button" value="List" />
</form>
<ul id="carList">
</ul>
</body>
</html>
The JQuery script looks as below,
$(document).ready(function() {
$("#butt1").click(function () {
listCars();
});
$("#brand").click(function () {
$.getJSON('/myTestSpring/listCars', {
}, listCarsCallback1);
});
});
function listCarsCallback1(data) {
var listHTML = "";
$.each(data, function(i, car) {
listHTML += "“;
});
$(”#brand”).html(listHTML);
}
function listCars() {
var brand = $(”#brand”).val();
$.getJSON(’/myTestSpring/indexResponse’, {
“brand” : brand
}, listCarsCallback);
}
function listCarsCallback(data) {
var listHTML = “”;
$.each(data, function(i, car) {
listHTML += “<li>” + car[”model”] + “</li>”;
});
$(”#carList”).html(listHTML);
}