MVC-ClassNotes
MVC-ClassNotes
-----------------------------------------------------
Pre-Requiesites
-------------------
Spring Core is mandatory
Servlets
Jsp
Why MVC ?
----------
To make our application classes loosely coupled.
@WebServlet("/userServlet")
public class UserFormServlet extends HttpServlet{
RequestDispatcher rd = req.getRequestDisp("succ");
rd.include(req,res);
}
Spring MVC Advantages
----------------------
1) Spring supports form binding objects
(form data will be stored into model objects)
8) java to json and json to java will be converted by spring mvc using jackson api.
9) java to xml and xml to java will done by spring mvc using jax-b.
2) HandlerMapper
3) Controller
4) ModelAndView
5) ViewResolver
6) View
Note : All above components are called as Web Components in Spring MVC.
DispatcherServlet
-----------------
-> It is a predefined servlet class in Spring MVC module.
HandlerMapper
-------------
HandlerMapper is used to identify Request Handler in web layer.
HanlderMapper will identify which controller class method should execute for this
user request.
Controller
----------
Controllers are called as RequestHandlers.
ModelAndView
-------------
Model is used to store data which needs to send from controller to UI.
In model, data will be stored in the form of Key and Value pair (Entry).
View represents logical view name (only name of the file without file extension).
ViewResolver
-------------
-> ViewResolver is a predefined Interface in Spring MVC module.
InternalResourveViewResolver
UrlBasedViewResolver
XmlViewResolver etc....
/WEB-INF/views/index.jsp
View
----
It is used to render model data on view page.
In view files we will use model object keys to print corresponding value.
a) servlet-api
b) spring web mvc
Syntax: DispatcherServletName-servlet.xml
DispatcherServletName=mvc
FileName should be : mvc-servlet.xml
DispatcherServletName=dispatcher
FileName should be :dispatcher-servlet.xml
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/web-beans.xml</param-value>
</init-param>
http://localhost:4040/MVCApp-1/welcome.htm
http://localhost:4040/MVCApp-1/date.htm
http://localhost:4040/MVCApp-1/greet.htm
4) Configured ViewResolver with prefix and suffix to identify physical view files
(InternalResourceViewResolver)
DispatcherServlet
HandlerMapper
Controller
ModelAndView
ViewResolver
View
@Controller
public class WelcomeController{
@RequestMapping("/wish.htm")
public String wish(Model model){
model.addAttribute(key,value);
return "index" ; //logical view name
}
@RequestMapping("/greet.htm")
public String greet(Model model){
model.addAttribute(key,value);
return "index";
}
}
http://localhost:9092/GreetApp/greet.htm
http://localhost:9092/GreetApp/wish.htm
Business Components
--------------------
Root Application Context --- ContextLoaderListener (IOC-2)
In Web application, forms are used to capture data from end user.
I.e -> Once form is submitted, form data will be captured and will be stored into
model object.
To support for form binding, spring mvc provided form tag library.
---------------------------------------------------------------
<%@ taglib uri="www.springframework/tags/form" prefix="form" %>
<td>
<form:radiobutton path="gender" label="Male" value="M" />
<form:radiobutton path="gender" label="Fe-Male" value="F" />
</td>
--------------------------------------------------------------
------------------------------------------------------------------
List<String> courses= dao.getCourses();
model.addAttribute("courses",courses");
------------------------------------------------------------------
-----------------------------------------------------------
SQL Developer
Toad
con = ConnectionManager.getConnection();
boolean flag = true;
System.out.println(bookSearchSql.toString());
pstmt = con.prepareStatement(bookSearchSql.toString());
rs = pstmt.executeQuery();
while (rs.next()) {
Book b = new Book();
b.setBookId(rs.getInt("BOOK_ID"));
b.setBookName(rs.getString("BOOK_NAME"));
b.setAuthorName(rs.getString("AUTHOR_NAME"));
b.setBookPrice(rs.getDouble("BOOK_PRICE"));
books.add(b);
}
---------------------------------------------------------------
Basic Search : Retriving records based on primary key
In Developer Tools click on Debugger menu and choose a breakpoint in java scirpt
code from where you need to start debugging.
Note: When we modify java script code, then we have to reload the page in browser.
(Ctrl + F5 or Ctrl + R )
<head>
<script>
function validateSearchForm(){
if(banme == ''){
alert("Please Enter BookName");
return false;
}
return true;
</script>
</head>
boolean preHandle()
void postHandle()
---> Before sending response from DS to browser
ExecutionTimerInterceptor
BrowserCheckingInterceptor
BusinessHoursCheckingInterceptor
registry.addInterceptor(new ExecutionTimer());
@RestController
@RestController
public class WelcomeRestController{
@GetMapping("/welcome.htm")
public String getMsg(){
return "Hello";
}
@PostMapping("/adduser.htm",consumes={"application/json"})
public String addUser(@RequestBody User user){
@Controller
public class GreetController{
@RequestMapping("/greet.htm")
public String greet(Model model){
model.addAttribute("msg","Hello");
return "greet";
}
@RequestMapping("/validateEmail.htm")
public @ResponseBody String checkEmail(){
return status;
}
}
------------------------------------------------------------------
Spring framework having direct support for POI and IText apis.
Paragraph
Table
<form action="singleFileUpload"
enctype="multipart/form-data"
method="post" >
Select File : <input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
-----------------------------------------------------------------
@Controller
public class FilesController{
@RequestMapping(value="/singleFileUpload",
method=RequestMethod.POST
)
public String singleFileUpload(MultipartFile file, Model model){
@RequestMapping(value="/singleFileUpload",
method=RequestMethod.POST
)
public String multiFileUpload(MultipartFile[] file, Model model){
MultiPartFile file
Files.write(path,fileData);
------------------------------------
MultiPartFile[] files
Path path =
Paths.get("Directory-Path",file.getOriginalFileName());
Files.write(path,fileData);
Spring MVC
Spring MVC Advantages
Model-1 and Model-2(MVC) Architecture
Front Controller Design Pattern
Spring MVC Architecture
Dispatcher Servlet
HandlerMapper (SimpleUrlHandlerMapping & ReqMappingHandlerMapping)
Controller(AbstractController, @Controller, @RestController)
RequestMapping with URL (@RequestMapping)
ViewResolver (XmlViewResolver, InternalResViewResolver)
ModelAndView
WebApplicationContext & RootApplicationContext
ServletConfig
ServletContext
ContextLoaderListener
Request Redirection (redirect:buildDashboard)
Form Binding Object (modelAttribute & path)
Search Forms Development
Spring Form Tag Library
@ModelAttribute
Interceptor
File(s) Uploading (enctype="multipart/form-data", MultiPartFile)
Java Config Approach(WebInitializer, AppConfig, WebConfig)
POI & IText Reports (AbstractXlsView, AbstractPdfView)
RestController vs Controller
Exception Handling in Spring MVC (local handling & global handling)
Double Posting Problem in Spring MVC (P-R-G)
HttpServletRequest and HttpSession in Spring MVC
Spring Boot & Spring Data & Batch & Security & MicroServices