Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlets in spring mvc

I have fundamental idea about servlet and spring mvc. But I don't know that there is a usage of servlets in spring mvc or not. In spring mvc we have controller classes. My thinking is servlet is used in spring mvc as a controller. If I'm incorrect please correct me.

like image 698
theCoder379 Avatar asked Jan 13 '16 10:01

theCoder379


2 Answers

Yes,you are perfectly right. Servlets are used in Spring-MVC. In Spring-MVC when you write annotation like @Controller, indirectly you are using a Servlet called Dispatcher Servlet. Dispatcher Servlet is defined in web.xml file with properties and class name which is mapped to .jsp pages and Controller part.

like image 55
U.Kakadiya Avatar answered Sep 20 '22 00:09

U.Kakadiya


Related / Duplicated to When to use Servlet or @Controller. The question is not the same but quite the explanation on that question you will be able to understand:

If you're a student interested in learning the language then I would stick with servlets for now. It's possible to write a web app using just servlets but in practice you'll probably want to look at JSP's too.

A JSP is a convenient way to write a servlet that allows you to mix html with scripting elements (although it's recommended to avoid Java code in your jsp in favour of tags and el expressions). Under the covers it will be compiled as a servlet but it avoids you having to use lots of messy print statements.

It's important to have at least a basic understanding of servlets and JSP's. Spring MVC is one of many frameworks built on top of servlets to try make the task of writing a web application a bit easier. Basically all requests are mapped to the DispatcherServlet which acts as a front controller.

The DispatcherServlet will then call the controller whose annotations match the incoming request. This is neater than having to write these mappings yourself in the web.xml (although with servlet 3.0 you can annotate servlets now). But you also get many other benefits that can be used like mapping form fields to an object, validating that object with jsr303 annotations, map inputs and outputs to xml or json etc etc. Plus it's tightly integrated with core spring so you can easily wire in your services for the controller to call.

It's worth noting that there are a plethora of competing frameworks built on top of servlets. Spring MVC is one of the most popular so it's not a bad choice to look into.

like image 25
Oldskultxo Avatar answered Sep 20 '22 00:09

Oldskultxo