Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Friday, August 23, 2013

Spring Form with Checkboxes

In this post, I shall explain how to create a Spring form with check boxes. Additionally, we will learn how to make a list of items checked by default.

web.xml : 

1:  <web-app id="WebApp_ID" version="2.4"  
2:    xmlns="http://java.sun.com/xml/ns/j2ee"   
3:    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4:    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
5:    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
6:    <display-name>Spring MVC Application</display-name>  
7:    <servlet>  
8:     <servlet-name>HelloWeb</servlet-name>  
9:     <servlet-class>  
10:       org.springframework.web.servlet.DispatcherServlet  
11:     </servlet-class>  
12:     <load-on-startup>1</load-on-startup>  
13:    </servlet>  
14:    <servlet-mapping>  
15:     <servlet-name>HelloWeb</servlet-name>  
16:     <url-pattern>/</url-pattern>  
17:    </servlet-mapping>   
18:  </web-app>  

HelloWeb-servlet.xml :

1:  <beans xmlns="http://www.springframework.org/schema/beans"  
2:    xmlns:context="http://www.springframework.org/schema/context"  
3:    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4:    xsi:schemaLocation="  
5:    http://www.springframework.org/schema/beans     
6:    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
7:    http://www.springframework.org/schema/context   
8:    http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
9:    <context:component-scan base-package="com.sri.test" />  
10:    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
11:     <property name="prefix" value="/WEB-INF/jsp/" />  
12:     <property name="suffix" value=".jsp" />  
13:    </bean>  
14:  </beans>  

Subject.java :

1:  package com.sri.test;  
2:  import java.io.Serializable;  
3:  public class Subject implements Serializable{  
4:      /**  
5:       *   
6:       */  
7:      private static final long serialVersionUID = 7135393884889475409L;  
8:      private int subjectId;  
9:      private String subjectName;  
10:      public Subject() {  
11:          super();  
12:      }  
13:      public Subject(int subjectId, String subjectName) {  
14:          super();  
15:          this.subjectId = subjectId;  
16:          this.subjectName = subjectName;  
17:      }  
18:      public int getSubjectId() {  
19:          return subjectId;  
20:      }  
21:      public void setSubjectId(int subjectId) {  
22:          this.subjectId = subjectId;  
23:      }  
24:      public String getSubjectName() {  
25:          return subjectName;  
26:      }  
27:      public void setSubjectName(String subjectName) {  
28:          this.subjectName = subjectName;  
29:      }  
30:      @Override  
31:      public boolean equals(Object obj) {  
32:          if (this == obj)  
33:              return true;  
34:          if (obj == null)  
35:              return false;  
36:          if (getClass() != obj.getClass())  
37:              return false;  
38:          Subject other = (Subject) obj;  
39:          if (subjectId != other.subjectId)  
40:              return false;  
41:          if (subjectName == null) {  
42:              if (other.subjectName != null)  
43:                  return false;  
44:          } else if (!subjectName.equals(other.subjectName))  
45:              return false;  
46:          return true;  
47:      }   
48:  }  

Student.java :

Student has one-to-many association with Subject:

1:  package com.sri.test;  
2:  import java.io.Serializable;  
3:  import java.util.List;  
4:  public class Student implements Serializable{  
5:      /**  
6:       *   
7:       */  
8:      private static final long serialVersionUID = -779930820340758193L;  
9:      private int studentId;  
10:      private String studentName;  
11:      private List<Subject> subjectList;  
12:      public Student(int studentId, String studentName, List<Subject> subjectList) {  
13:          super();  
14:          this.studentId = studentId;  
15:          this.studentName = studentName;  
16:          this.subjectList = subjectList;  
17:      }  
18:      public Student() {  
19:      }  
20:      public int getStudentId() {  
21:          return studentId;  
22:      }  
23:      public void setStudentId(int studentId) {  
24:          this.studentId = studentId;  
25:      }  
26:      public String getStudentName() {  
27:          return studentName;  
28:      }  
29:      public void setStudentName(String studentName) {  
30:          this.studentName = studentName;  
31:      }  
32:      public List<Subject> getSubjectList() {  
33:          return subjectList;  
34:      }  
35:      public void setSubjectList(List<Subject> subjectList) {  
36:          this.subjectList = subjectList;  
37:      }      
38:  }  

HelloController.java :

allList is a list of all the subjects available; enrolledList is a list of subjects that a student has enrolled. We simply add student object and allList to the ModelMap and return the view.

1:  package com.sri.test;  
2:  import java.util.ArrayList;  
3:  import java.util.List;  
4:  import org.springframework.stereotype.Controller;  
5:  import org.springframework.ui.ModelMap;  
6:  import org.springframework.web.bind.annotation.RequestMapping;  
7:  import org.springframework.web.bind.annotation.RequestMethod;  
8:  @Controller  
9:  @RequestMapping("/")  
10:  public class HelloController{  
11:    @RequestMapping(value = "", method = RequestMethod.GET)  
12:    public String printHello(ModelMap model) {  
13:     model.addAttribute("message", "Hello Spring MVC Framework!");  
14:     List<Subject> allList = new ArrayList<Subject>();  
15:     allList.add(new Subject(1,"English"));  
16:     allList.add(new Subject(2,"Maths"));  
17:     allList.add(new Subject(3,"Science"));  
18:     allList.add(new Subject(4,"Social"));  
19:     allList.add(new Subject(5,"Tamil"));   
20:     List<Subject> enrolledList = new ArrayList<Subject>();  
21:     enrolledList.add(new Subject(1,"English"));   
22:     enrolledList.add(new Subject(3,"Science"));  
23:     Student student = new Student(1,"SRI",enrolledList);  
24:     model.addAttribute("student", student);   
25:     model.addAttribute("allSubjectList", allList);  
26:     return "home";  
27:    }  
28:  }  

home.jsp : 

This holds the spring form. commandName is the model attribute which is used to fill the form, the path is the model to be used to pre-populate data, items point to list of all the subjects available and path to the subjects taken by the student model.

1:  <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
2:  <html>  
3:  <head>  
4:  <title>Hello World</title>  
5:  </head>  
6:  <body>  
7:      <h2>${student.studentName}</h2>  
8:      <form:form method="POST" action="save" commandName="student">  
9:          <form:checkboxes title="Subjects taken" path="subjectList"  
10:              items="${allSubjectList}" itemLabel="subjectName" element="div" />  
11:      </form:form>  
12:  </body>  
13:  </html>  

Output:


Cheers!

S. Srikrishnan

Saturday, May 18, 2013

Model – View Separation




Our team was waiting outside a food stall starring at the list of snack items that was put up on the board. I read one by one that was listed, and at one point my eyes stopped at “Cutlet”. “I will go with cutlet”, I said. The billing person (Lets call him the controller for now; as to why so, will be told shortly) nodded his head and proceeded to bill it. Then there came a notification from someone from the kitchen premises that cutlets were all over. Now, if the cutlets represented the actual “model”, the display board was the view. So, now I’ve explained why the billing person is the “controller”. Now if the controller had promptly informed the view about the change in the model, things would not have gone for a toss. (I know it is not something that is catastrophic, but still)

Model – View - Controller (MVC) pattern is awesome I tell you. When I was new to this pattern, I saw MVC as one among the many patterns available, but now I see it as a master pattern, the pattern that solves “data-here-display-how” problem. Let us see how MVC applies to different problems.

Firstly, I’ll talk about the files in a file system. We get to see many views of the file system- one as a general file system explorer, one as a tree structure, one as a file picker / saver dialog et al. The model is the same – the file system; the views are different.


(The tree view and the flat view of the file system)

(The file saver/picker view of the file system)

PhpMyAdmin, a tool to handle the administration of MySQL provides a view of the data in the database system. You may also wish to open a console and connect to the MySQL server. My aim here, is to explain how the model being same, is rendered in different views.

Let’s move on to few real life examples. The cutlet-board-hotel thing was one. Now, let me talk about, hmm say X-rays? X-ray gives a “view” of the actual model, the bone. 



We need to keep in mind that only “updatable” views result in change of the model information. Now, if your hand is broken, and you think you can change the X-ray image to fix the broken hand, my friend, it’s an epic fail attempt. And when you work on say, PhpMyAdmin, you can update a table, by updating the view (Hey not the SQL view, I am talking about the front end view you see on the browser), of course if only you got the permission for it. (Forget Jee-Boom-Bah pencil now)

My message to the computer science world: apply MVC pattern, it makes life simple and easy. Long live MVC! Long live MVC!

Cheers!

- ∫.∫rikrishnan

Sunday, March 3, 2013

Separation of concerns



A concern, however trivial it might seem to be, needs our immediate attention, as it might grow to something catastrophic if not tackled properly. We see people, who while talking let their ‘concerns’ interfere with the lucidity of their thought process. If one is able to distinguish the concerns involved and address each one of them separately, the problem is solved.

A computer science engineer by now would have guessed that I am talking about Aspect Oriented Programming and weaving. Well, I am not going to stick to that ‘aspect’ alone. Ok, let me hit it straight. There are things that always need to be separate initially, resolved individually and then ‘weaved’ carefully. That means, they have to live separately and carry out their work in tandem.

The separation of business logic from presentation logic is an important concern in software development. This enhances pluggability. Have we not seen electronic media reporting a piece of information in a variety of ways? Model being the same, we get to see different views. Well, this is one natural advantage of Model-View separation; lucky media people! Now, take the example of HTML, CSS separation. While HTML is all about document structure, CSS is about offering styles to the document. The same is the case with LaTeX, where the presentation of content and the content itself are separate. This tool is popular over WYSIWYG editors for the very reason- the concerns are separately addressed.

Earlier during king rule, judiciary and executive were one. These concerns are now separate in our country. Rulers and their parties are separate concerns. There needs to be a perfect co-ordination between the two, but at the same time, they should not interfere with each other’s business. Well, it is the duty of the leader to ensure that; in other words, a good leader is one who ensures that with sincerity. People misusing cars provided by their workplaces for personal use, usually for dropping their kids in school are not a rarity. Clearly, separation of concerns rule is violated.

The philosophy part starts here. Body and soul are also separate. Body is dead, once the soul departs. Body is perishable, soul is not. Body and soul are separate concerns. Body is something temporary. To accuse someone of being short is not right as it is not his / her posession. For that matter, one cannot claim posession of anything in this world. We come empty handed; we leave empty handed; however, we quarrel stupidly for things that are not ours.

Cheers.