SpringMVC Notes
SpringMVC Notes
SpringMVC Notes
Spring MVC is a framework for building web applications in Java.Its based on the Model-View-
Controller(MVC) framework and also has the benefits of the Spring framework.
First we will look at the controller part of the MVC framework.
The controller part is responsible for our http requests which are coming from the
client(browser) to our app which is on the server , the controller handles the the requests
according to the nature of the request and then responds or does something according to that
request , and the doing of the controller is the job for the programmer to tell it what request
should it listen to and what to do after the request is recieved.
Before we move to the controller we should mention how Spring framework deals with web
requests ( http requests i.e. GET, POST, ...). The Spring framework has its own controller which is
defined and implemented by the Spring framework itself and its purpose is to recieve the
request and find the appropriate controller created by the programmer himself and send the
request to the desired controller.
Now when the DispatcherServlet gets the request if there is no controller defined and
implemented by the programmer for the given path i.e. if someone sends a web request like
www.hellowrold.com/sayHello if we didnt define a controller that will handle the request the
DispatcherServlet will accept the request search in our app for the controller and when it
doesnt find it, it will throw an 404 error which means the resource that is asked for isnt on our
server. If we want the Spring framework to not show the ugly page with errors we can define an
error.html page which will be rendered to the client if something is wrong and we do that by
defining the error.html ( you have to be carefull because the name of the file has to be exactly
error.html otherwise it wont work).The error.html file resides in the /resources/templates folder
if youre using Thymeleaf.
So we need to define a controller to handle the requests we want i.e. the request for the path.
In Spring framework to create a controller we create a Java class , the naming of the class
doesnt matter you can put whatever you want, but common practice of naming controllers is
putting the purpose of the controller and than Controller after that for ex. we want a controller
to manage student requests we name the java class StudentController.
When we created our class we have to make it a Spring framework controller and we do that by
giving the class the annotation @Controller this is right above the declaration of the class.By
annotating the class with @Controller we tell the Spring framework that this class is a controller
and thus it will handle some form of web requests and also we tell it that this class is a Bean so
that the controller can be created by Spring framework and the DispatcherServlet can find it
when the request arrives.
Now the second step is to map this class to a path i.e. to tell which requests should this
controller receive.
There are two method for doing so.
We can use the @RequestMapping annotation or the more sophisticated annotations which
correspond to the acctual requests : @GetMapping , @PostMapping , ... or we can use
combination of these two.And we sepcify the path inside the braces of an annotation :
@RequestMapping("/").
Usually the common practice is that the @RequestMapping annotation is applied to the whole
class meaning every method would respond to that path,
In a Spring framework controller the requests are processed by methods inside the Controller
class i.e. we define a method for every path we want to have in our web app.
We first declare a method and then we give it a mapping with one of the mappings according to
what request we want this method to recieve.
If we want the method to react to GET request to a certain path we set the @GetMapping
annotation directly above the function declaration.
We have now an example:
@Controller
@RequestMapping("/student") // this is the base path of the controller
class StudentController{
// now we define methods for other paths
@GetMapping
public void index(){
System.out.println("We are inside the index controller method on path
/studnet");
}
@GetMapping("/grades") // now this path is appended to the base path and we
// call this method by accessing the path /student/grades
public String showStudentGrades(){
System.out.println("We are inside the index controller method on path
/student/grades");
}
}
We defined controllers and they just recieve basic requests without any data, usually when
there is a request there is some data bound to it , so we need to access it in order to process it
and give an answer according to the data.
When a client sends a request the data is usually some html form which then is turned into a
http request.
When the data is passed either by a GET method in the url or by the POST method inside the
body we can access the data by passing the name of the attribute as a parameter to the
controller function which maps that request.
If we send two attributes and theirn names are name and surname than we pass those two
attributes as parameters to the function :
If the GET Request is like this :
http://localhost:8080/student? HYPERLINK "http://localhost:8080/student?
name=Edin&sname=Elezi"name HYPERLINK "http://localhost:8080/student?
name=Edin&sname=Elezi"=Edin HYPERLINK "http://localhost:8080/student?
name=Edin&sname=Elezi"& HYPERLINK "http://localhost:8080/student?
name=Edin&sname=Elezi"sname=Elezi
@GetMapping("/student")
public void controllerFunction(
@RequestParam("name") String theName,
@RequestParam("surname") String theSurname){
// some code
}
Now by using @ResquestParam the parameter names theName and theSurname can be any name you
want.
When we talk about binding we also have to mention the Model class which is passed by the Spring
framework to every controller method we create, but in order to use it we have to include it as a
paremeter to the controller method in which we want to use it.The Model is there to store data and it
travels from the DispatcherServlet to the Controller and then we send information to the view by the
same model.
We can use it by adding it as a paremeter :
@GetMapping("/student")
public void controllerFunction(
@RequestParam("name") String theName,
@RequestParam("surname") String theSurname,
Model model
){
// some code
}
As we mentioned above the Spring framework maps the data that came with the requests if the names
are the same, but what if we want to have an object as a paremeter.
It's the same rule as the first approach but now we define the object as the paremeter and the names of
the attributes of that object have to match with the names of the attributes sent in the request, and also
we need to define setters and getters for all the attributes in the class so the Spring framework can use
the setters to bind the attributes to the object we passed in the function , and getters when it uses
them , and of course constructors:
Persistence
Hibernate ORM is concerned with helping your application to achieve persistence. So what is
persistence? Persistence simply means that we would like our application’s data to outlive the
applications process. In Java terms, we would like the state of (some of) our objects to live
beyond the scope of the JVM so that the same state is available later.
Meaning that when we create an object and after we quit the application and then run it again
the object is there and its not deleted.
Hibernate
Hibernate is a framework for saving POJOs into a database.We use hibernate in our Spring MVC
web application to store Java POJOs as tables to the database so we can save some information
after the application is terminated.We store Java objects into a relational database of our choice
it can be either MySQL , PostgreSQL or some other but commonly if we only want to test our
application with some data we can use the H2 database which comes with the Spring
framework.
To set up a databse inside Spring we have to write some configuration, and the configuration is
set inside the application.properties file.
And this configuration is for local developing of the app.
First we need to set the datasource url i.e. the path to the database, and we do that like so:
spring.datasource.url=jdbc:nameOfTheDatabase://localhost:portOfTheDatabaseServer/nam
eOfTheDatabese
So if we wanted the MySQL database and our database is called db this line would look like this :
spring.datasource.url = jdbc:mysql://localhost:3306/db
Second we also need to give the username and the password with which we access the
database :
spring.datasource.username = username
spring.datasource.password = password
Hibernate allows us to write POJOs and create tables inside the database just by annotating the
POJO with some annotations, it behaves like an intermediate layer between POJOs and the
database i.e. it maps a single POJO to a table or an entity inside the databse.
For example :
if we have a POJO like this :
@Entity
@Table(name=”student”)
class Student{
@Id
private Long id;
private String name;
private String surname;
}
This maps to a corresponding table Person inside the database.
Person
----------------------------
Id | name | surname|
----------------------------
The annotation @Entity means that this POJO will be an entity.
Additionally the @Table annotation explicitly specifies the table name.
@Id marks the property which defines the entity’s identifier.
But we can also specify the strategy in which the id will be set or incremented , we add that
inside the paranthesis of the annotation ,
@GeneratedValue(strategy = GenerationType.AUTO).
We have 4 ID Generation Strategies:
• GenerationType.AUTO - Pick an appropriate strategy for the particular database.
• GenerationType.IDENTITY - Assign primary keys using database identity
• GenerationType.SEQUENCE - Assign primary keys using a database sequence
• GenerationType.TABLE - Assign primary keys using an underlying database table to
ensure uniqueness
The AUTO strategy picks one of the three (IDENTITY, SEQUENCE, TABLE) strategies depending on
the chosen databse.The IDENTITY strategy is auto-incrementing meaning it starts from 0 and
goes +1 for every new entity added to the table. The SEQUENCE and TABLE strategies keep
another table called hibernate_sequence which keeps track of the value which is given to the id
column of the specified table, and it is incremented every time an entity is added.
But if we dont like any of these strategies that Hibernate gives us, we can create our own
strategy , we can do that by Java code i.e. writing some code in Java that will generate our id.
To do so we have to create a new Java class anywhere inside our application , and than that
same class must implement the com.hibernate.id.IdentifierGenerator interface which contains the
public Serializable generate(...) method in which you define the bussines logic for your own id
generator strategy. BUT WE HAVE TO BE CAREFULL!!!
Because we need to proof this method for several situations, it must , MUST always return a
unique value, it must work in a multithreaded enviroment, it must work im high-volume , etc...