Spring Boot and Spring MVC with Real World Project!! | Karthikeya T | Skillshare

Spring Boot and Spring MVC with Real World Project!!

Karthikeya T, For Your Learning Needs

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
82 Lessons (7h 33m)
    • 1. Must Watch!

      1:42
    • 2. Introduction

      7:13
    • 3. 0001PreReq1

      9:33
    • 4. 0002SettingTheEnvironment

      5:31
    • 5. 0101MVCArc

      7:11
    • 6. 0102SpringMVCArc

      4:41
    • 7. 0103MVCAppStep1

      6:07
    • 8. 0104MVCAppStep2

      6:11
    • 9. 0105MVCAppStep3

      11:38
    • 10. 0106MVCAppStep4

      5:30
    • 11. 0107WebAppContext

      4:41
    • 12. 0108RootApplicationContext

      4:16
    • 13. 0201SpringBootIntro

      5:12
    • 14. 0202CreatingSpringBootProjWithSTSnInitializer

      8:14
    • 15. 0203ProjectWalkThrough

      5:46
    • 16. 0204AppLogic

      8:10
    • 17. 0205HowItWorkednCreatingJar

      8:14
    • 18. 0206SpringBootFeatuersRevisited

      5:00
    • 19. 0207DeplyingAWarFileUsingSprinBoot

      5:45
    • 20. 0302InterceptorExample

      6:52
    • 21. 0303ApplyingRestrictions

      4:41
    • 22. 0304InterceptorsWithoutSpringBoot

      1:25
    • 23. 0401MappingAnnotationsOurAPP

      4:18
    • 24. 0402GetAndPostMapping

      8:20
    • 25. 0403URIPatterns

      1:48
    • 26. 0404ControllerMethArgs

      3:44
    • 27. 0405ReturnValue

      6:02
    • 28. 0501RequestParm,GetMapping,CookieValue

      3:00
    • 29. 0502ModelAttributePart1

      4:51
    • 30. 0503ModelAttributePart2

      4:05
    • 31. 0504SessionAttributes

      1:49
    • 32. 0505FwdRedirectFlashAttributes

      6:26
    • 33. 0601ExceptionHandling

      6:23
    • 34. 0602ExceptionHandlingInSpringBoot

      4:35
    • 35. 0701SpringJDBCIntro

      2:02
    • 36. 0702SpringJDBCWithoutSprinBoot

      9:13
    • 37. 0703SpringJDBCwithSpringBoot

      5:53
    • 38. 0704ExternalDatabase

      2:19
    • 39. 0705PreparedStatement

      6:22
    • 40. 0801 Hibernate

      0:20
    • 41. 0802IntroAndTerminologies

      6:40
    • 42. 0803JDBCvsHib

      5:48
    • 43. 0804ThingsYouNeed

      4:29
    • 44. 0805FirstHibAppPart1

      10:55
    • 45. 0806FirstHibAppPart2

      7:40
    • 46. 0808ExploringTheMailLogic

      7:18
    • 47. 0809ImprovingOurCode

      4:27
    • 48. 0810IncorporatingAnnotations

      6:44
    • 49. 0811HibernateAutoSync

      4:33
    • 50. 0801SpringDataJPA

      20:00
    • 51. [email protected],NamedParams,IndexedParams

      6:03
    • 52. 0803QueryMethods

      5:44
    • 53. 0804Sorting,Pagination,ModyfyingAnn

      2:42
    • 54. 0805CriteriaBuilder

      4:00
    • 55. 0901Intro

      6:43
    • 56. 0902InMemoryDataStore

      7:46
    • 57. 0903JDBCAuth

      5:11
    • 58. 0904PasswordEncoding

      5:02
    • 59. 0905CSRFAttack

      8:02
    • 60. 0906InstallingKeyStoreForHTTPS

      4:07
    • 61. 0907LdapIntegration

      7:54
    • 62. 1001CreatingEndtoEndApplication

      7:45
    • 63. 1002DependencyWalkthrough

      3:07
    • 64. 1003SpringSecurityFeatureBackend

      8:49
    • 65. 1004BackendComponentsForTodo

      1:57
    • 66. 1005JSPFFragments

      2:41
    • 67. 1006LoininLogoutFunctionality

      8:14
    • 68. 1007UserRegistrationAndValidation

      10:58
    • 69. 1008ViewAddTodo

      5:44
    • 70. 1009UpdateAndDeleteTodo

      2:58
    • 71. 1010EnforcingAuthorization

      1:41
    • 72. 1011UserManagement

      1:52
    • 73. 1012ProjectStructure

      2:26
    • 74. 1101SpringBootActuatorIntro

      12:26
    • 75. 1102MonitoringHealthAndCustomHealthIndi

      7:06
    • 76. 1103ExploringAutoConfigConditions

      4:00
    • 77. 1104LoggingEndpoint

      3:04
    • 78. 1105ExploringEnv

      2:56
    • 79. 1106ExploringApplicationMetrics

      2:11
    • 80. 1107CustomInfoEndpoint

      3:07
    • 81. 1108CreatingCustomEndpoints

      2:00
    • 82. 1109OtherEndpoints

      0:50

About This Class

This course is about learning spring framework with spring boot. We start with basic concepts and then we will advance to some interesting concepts!

Spring boot is the hot topic in the industry and organizations are now moving to microservice architecture  from traditional monolithic architecture. However, the migration is still in initial phase and will easily take more than a decade before we see about 90% of the projects migrate to cloud and microservice.

Hence this course will cover core concepts of MVC in Spring along with various modules. Simultaneously, this course will also address how things are done in Spring boot.

It would be a bad idea to directly learn Spring boot. Spring boot will give a lot of convenience to developers by eliminating the unnecessary tasks that the developer needs to go through. Spring boot is not any replacement of existing framework, it is an extension! So it's crucial that you understand core spring concepts and then know how spring boot does the same task with less effort. 

More content is yet to be released. Content will be uploaded as and when they are created.

Enjoy Learning.

Transcripts

1. Must Watch!: full stack developer sort in great demand and are paid very high. So it's not enough that you'll on one technology but rather full stack off technologies. We have all the courses on sculpture that would help you become a full staff Java developer so that you will gain skills to develop, end, to end applications from scratch all by yourself and be eligible for top profile jobs or to work on freelance projects. So was it this link? Its corporate dot com slash skill share. It has all the links to our courses, and they're all organized in a proper sequence. You can start from Java programming, and here's a link to that course. Once you complete this course, you can get into advance Java. And here's the course link for the same. Like was, you keep going and complete the entire stack off technologies. The courses were also include creating into and applications from scratch. And if you're struck anywhere, you can always post your questions. Even if you're inexperienced. Dollop er I would highly recommend you to start from scratch because many people who followed this approach and gone through all these courses from scratch have seen very good results. Many individuals have clear interviews. Some of them also cleared certification exams and some of them also got into good jobs with better income and all. So I would highly recommend that you followed this approach. Start from Java programming all the way to all the advanced courses. Hope it makes sense. 2. Introduction: Welcome to my course on Spring MBC with spring boot. This course will cover all the spring modules that changed to learn in order to create and to and spring applications. So this course will cover a lot Offspring, embassy concepts, spring boot spring data, JP a spring security view technologies, etcetera. Before we dive into understanding what this course has to offer, let me quickly introduce myself. Justin gets, If you're curious. I worked as a senior software engineer, technical lead technology analyst in various multinational corporations, major Lynn toe banking, telecom and financial services. I have over a decade of experience in the industry and to the most part of logged on Java and related technologies. So that's close to $30,000 off total experience, which is, by the way, not so significant. I mean, if you work on something for well over 14 years, he will hit that mark easily. I'm also mentoring projects and been training professionals worldwide. But my true passion has always been teaching, and in all honesty, I really hate talking about my achievements. What matters to me the most is when I give you the results you're looking for with my teaching here is the high level overview of what will cover in this course Initially will start off with some basics. Where will cower some prerequisite concepts like understanding traditional embassy architectural, spring dependence, injection, auto wiring, etcetera. This module will basically lay a solid foundation to understand the rest of the modules that will discuss in the rest of the course. Then we'll jump in tow. Spring Embassy concepts where will understand the architecture, various components, interceptors, annotations, along with some really nice examples. We will then get into spring boot, which is quite a buzz. Born our days. We will cover pretty much all the features that spring but has to offer, including auto configuration started dependencies, spring initialize, er, actuator, etcetera. And then, with spring Jerry Busy, we will explore and understand where this confidence in the modern part of the embassy and we will see how we can interact with embedded and extranjera basis using gala visit templates. Next, we'll explore Spring Data J B. A, which comes with a whole stuff interesting concept. So we will use the most popular JP implementation like hibernate to interact with the database. I would also cover spring data concepts like really methods. Various annotations, pagination, dynamic, Cleary's etcetera. And then we'll get into Spring Security Module and we'll talk about very security features offered by spring, like authentication authorization encoding. CSR if Attack Key store held up in decoration except Ron. And after that, we'll jump into understanding spring boot actuator to access the application metrics, endpoints, etcetera and in tired. We're going to see how we can create our own endpoint and customize the metrics, and then we'll talk about springboard their tools. Here we'll explore some of the features like live, reload, photo restart, remote, debugging, etcetera. If you want to take a look at the completely stuff course content, you can check the description of this course. I understand the significance of having practical knowledge, so we are actually going to create an end to end application from scratch, using all the modules that will learn in the scores. Our application will have customer log in and admin login registration authorization authentication. Your spring there a J p A. To interact with the database, going to use some view technologies, etcetera. It's a complete end to an application that we're going to create. Here are some other features off this course. This course will also touch on prerequisite concepts, so you don't have to take another course before you're able to understand spring MBC All the spring boot is quite a buzz word. Nowadays, there are still countless projects that are using traditional spring framework. So keeping those people in mind, we'll explore old way of doing things. And then we'll jump into modern way of doing things using spring vote. That way you'll be able to work on spring good applications as well. Last traditional spring applications. You get to download all the examples that we're going to see in these videos I have taken into use in the past, and I can certainly help you with industry relevant into your questions. I keep up building the scores that notes another valuable content. So sometimes we may even go beyond the scope of this course and explore more interesting technologies or topics. And last but not least, you'll get lifetime access to this course, and even the future update that I bring to this course are absolutely free. After you finish the course, you can add all this goes into resume, you can add spring framework, Spring boot Spring Security, spring data, etcetera, which are by the very essential skills in the current market. You will also confidently answer into your questions on the subject and get into a better job. You will also find yourself actually participating in technical discussions to discuss on the subject and don't feel like somebody who's left out. This course is currently priced at $99. This course is worth more than $19 by the way. But if you're lucky, and if your timing is correct, you may see a limited time offer that lasts only for a few hours. Well, if you're one of those lucky ones, you'll see a significant drop in the price. It's a perfect opportunity for you to own this course permanently. You also have started a different policy anyway, just to enroll. Try it. If you don't like it passed for different simple, so there is no risk at all. But if you miss the deal, you will never get it at a good price. I'm known for my teaching style. I try to make complex concepts look simple, but that doesn't mean that I will carry you on my shoulders like this one is carrying its babies. If I do so, I'm doing more harm than good. Instead, I would let you experience the new territory on your own. However, if you fall or if you need support, I'm always there to help you. So throughout your journey, in the scores, if you come across with any problem or if you're struck, I'm always there to help you. I'm only a message of a I'm also open for feedback and suggestions. For example, if you feel like adding a new topic into this course, give me a suggestion. Have listened to you. The good thing about me is I listen to you with a genuine intent to help you with your objectives, not where some day you will fly on your own, where skies only limit without needing my help. 3. 0001PreReq1: Okay, let us take a look at some of the things that you would be needing to work on Spring and Missy projects the first off, which is going to be the Jerry K. Or Java Development kit. If you re strip wonder, where do you want to learn spring framework? Then I'm assuming that you already know how to install J decay and run Java programs. In fact, I'm pretty sure that you have all that install Jerrick in your computer, and you must have been running Java programs already. In case if you don't know how to do that, that's fine. Only have to do is to go to Google and search for download Jerry K. And most probably, it's the first thing that you need to click. But do make sure that it points to oracle dot com. And once you do that, just try to download the latest wash in, and by the time of this recording, it's Java Standard Edition washing number 12 and because if you have an older version of Java installed them, it's recommended that you download the latest one. Once you click the download button, you can choose a file depending on the type off operating system. Mine has been no. 64 bit wash in, and so I condone Load one off these files. The exit file will let you install the jet decay, and here's a friendly manner. Or, alternatively, can just download the zip file and sort of exported in a specific directory whichever way you follow. The ultimate result is you will have Djelic getting populated in a particular directory, whether you do it manually or isn't the installer with any exit file. But the key thing to note here is if you have dedicate that is prayer to Java washing 11 then you should be able to see couple of actress Jerrick and J. R. E. But from Jerrick, a Washington 11 he would only see Jedi K. They have decided to get it off the Grt directory altogether because all the libraries to help from the Java programs were also part off Jedi K. Having another Jr is just to duplicate, and so they got rid off it. So since I have already set up the latest portion, which is Washington, but well, I can no get it off these two prominently, okay? I'm not able to delete this because I have the Eclipse open. I'll deal with that letter, but you can delete all the previous Washington's Another thing that you had to make sure as you go toe and Roman variables in case off windows. Just search for it in the window search and then you'd get this system properties prompt. Click on enrollment. Very balls. Make sure that you have this particular variable Java home set. Well, this is not required to run the Java programs, but this perimeter would be used by other applications, and this might be needing in future. And it's also recommended that you add the path variable. Let me show you what I mean. That points to Java home bin directory. That's where all the executable Zoff job would be reciting and by doing so from the command bro. So you don't have to actually navigate to this directory in order to use those tools, he condemn it. We run those commands, and the operating system would be able to detect these tools based on the path variable. Have older done that, and then guess if you didn't it's recommended that you do that as well wants to do that in order to make sure that things are working, just go to the command processor and and type in Java sea hyphen wash in. That should point to the right, washing off Java and also try Java hyphen coercion. So that's Jabba Washington, which is expected. Some of my students who installed latest washing off Java complained that they're not able to see the washing number when the type in job a hyphen version. If you feels the same problem, just type in the following command where Java hit, enter and you should be seeing only one single part, and it must point to the right Jessica directory and guess if you're seeing any other part , just try to get it off that file from that location. Then everything should work fine. And guess if your face and issues you can put me a question and then I'll be able to respond. You're done with installing Jerry K. But we have a couple of more tools to install. Second off, which is maven Living, is actually not mandatory, but it's going to make our life a lot easier if you don't know off maven, that's fine. We're going to use it just to manage the dependence is without maven. We would have to manually search for jar files in the Internet and download them into our projects, which is quite a messy process, given the fact that spring is very vast and it requires a lot off libraries. So it's always recommended that we need to use at two like me. Even it has a lot of features, and it is primarily meant for project management. But for this course, we're just going to be using it to manage our dependence is, or dependent Jars will definitely be using it. Incoming videos, and then you'll have a better picture on the same and instructions on how to install maven will be in my next video. I'm actually going to show you the Maven installation video from my maven course, so we'll posit for the time being and will installed in next video. The third thing that would be needing is a Tomcats over. We're going to be needing the Tomcats over just for a couple of chapters. But down the line in future chapters were going to use spring boot and will understand how spring boot is going to make a life lot easier with embedded. So was in databases so that you don't have to explicitly install a separate server or a database. However, like I said, we're going to be using. Tom gets over for initial couple of chapters are so and in order to install that you can go to Google and search for Don't know Tomcat, most probably so first link that you need to click. But make sure it is pointing to Apache dot ogg and whichever is the latest washing you're seeing on the left hand side. Just click it and download. Make sure you download one of these court files. It can never used the installer or the ZIP file. And like, as with Java installation, you want to install it in a folder. In my case, it's in this location, and we're going to be using all these files from our Eclipse I D. Pretty soon. And the next thing that we're going to be needing years and I d. In my case, I'm going to be using the eclipse i d. It is the most popular I d. It is feature rich. What not And guess if you're using any other idea. That's fine, But make sure that you know the I D. Pretty well. If you don't, then I would recommend you to install Eclipse so that you can follow along with me. And once you install Eclipse, do make sure that you can actually create a sample project, a simple hello world project, and you're able to run it just to make sure that the Jerry K is pointing to the right directory and stuff like that. So you can just simply try creating a project and then tried to run the program. Something off this sort and I'm going to create a new class, all the test. I'm going to include public studied ward mean, Let's put this assault statement here. Hello and run the program and it is booking, so make sure it's working for you as well, and goto Windows preferences. Click on Java or maybe expanded flick on Java compiler and make sure you are chosen the latest one. Also under installed Jr Reese. Make sure you're pointing to the Jessica directory that you've just installed. That's about it. You know, next week we're going to see how to install maven and with that. We should be done with the the quite set up to start working on Spring Embassy. I will see you in my next video. 4. 0002SettingTheEnvironment: in this video, we're going to take a look at how to set up the enrollment to start using may have in setting up. The enrollment for maven is equal into setting up the enrollment for and and the steps are similar. So the first thing that we need to do Mr Download dmelvin binaries has a zip file. Extract that the fire in some folder in our local machine. So let's do that. And for that purpose, go to Google and search for this term download maven and click on the first thing that you see and make sure that the website is pointing to a patch it out or GTA. So this explains that Marion is also from a battery foundation. So here we have two kinds of files. One is with the sore scored and the other is without the source code. Make a guess on which one we need to download, obviously, without a source code. At the moment, we have nothing to do with the made in source code, so let's just download the binary version off this. I've already done that and have also extracted the ZIP file in my directory like so and here is, ah, content in it. So once you have it extracted in some directory, just copy it and we'll go to the next step, which will be to make sure that the Java home is set. It always advised the two said, this enrollment variable and most likely chances are that you have already done that. If you're able to run double programs and create job application and run them on the browser, etcetera, then you must have this enrollment very below that, it said. But just for your information, they should point to the home directory off your Jerry K And in order to check if this is working fine, just go to command processor and type in job a hyphen version, and it must show you the current abortion. It's Java hyphen, Warsh in in lower case, and it must display the current job abortion. So once you make sure of that, the next thing that you need to add is to add this M two enrollment variable, and it should point to the been Dell'Utri off the moving home directory. But before that, letters at this enrollment variable them to underscore home. Let's copy it and will point to the home directory off maven. So let us go toe windows and then search for and the moment very bolts and went at a new endowment variable. And it should point to the home directory wherever you have extracted those binaries sub click. OK, and second thing is dragged this empty available as well. This is where you would have all those script and we would pointed to the BIN directory And always try to use this syntax to define your endowment variables. Basically, what this does is this is equal into me, typing the entire part off the moving home directory. Basically, whatever M two home points to will be reflected in here as well. This is good because at little point of time, if you switch to latest version off maven, then you can just change this empty home variable and it will get reflected everywhere else . So the part that m two points to will be updated as well. So let us give it this van hit. Okay, We're going to add one more endowment variable which will be this system part variable. And it would point to the bin directory again. Letters use the syntax took your part. Let us chills part and then click Edit. And in here I'm going to add essentially this particular pat wherever m two points to I went to add a new one It okay, and the reason why you need to add the spot variable. His basically Melvin is also a command line tool. And in order for us to be able to run the Maven commands from any director from command processor, then you need to add the part two that bin directory as part of the path variable. So basically, let's go to command line and now type in, maybe hyphen version. Now this Ambien script is not deciding in this directory user, said men, so the operating system will go and take a look at all the part that are mentioned in the path variable to see if the script is present there. So since we've all their specified the part variable that points to the BIN directory, this would essentially work. And here it is. If we're able to see the maven version that you have downloaded and set up, then you're good to go. Also, I assume that you have the clips and Roman said so that's about it. See, assume 5. 0101MVCArc: in this video will try to understand what is the model view controller, architecture or simply embassy architecture? Beat mobile applications or rebelsde applications. NBC is the most popular it is and patent to create enterprise applications. And in order to explain things better, I'm actually going to consider a use case where the user tries to log into his account to perform some meaningful action. For example, think about a banking application. A user would visit the bank website, try to enter his credentials, and then he will hit the log in button Hasson as he hits the log in button. The request will be sent to the DNS server from the client. When I say claimed, it can be a browser or it can be a mobile application or it can also be another application . Whatever the client is, the request would be sent to the D in a server stands for domain names. Over. The job of being a silver is to maintain the list off all the domain names with their corresponding I p address. So depending on the domain name, the to enter its corresponding I P address would be returned back to the client the point is then aware off the actual location of the silver. It will then try to establish the connection with the server in order to send or receive the requests. So once that lined established connection with the server using protocols like TCP or UDP, it will send the request from the plane using Hester DP to the server. Once the requesters to silver, the silver would delegate that request to Port 80 by the four. Port 80 is where all that should be. Request Woodland, and that's where the Web server are the Web container or so that container would be installed. Typically, if you have your Web server installed in any other port, then you have to explicitly mention that port number in the Ural itself. So once that it was lands in Port 80 it is a responsibility off the Web server to handle the request and the way it handles the request sees. It will take a look at the web dot XML file, which will have the mapping instructions, which means here you'll have banks that will map a particular You're a pattern with the specific sold it, for example. In our case, since the users trying to log in the u. R L may have the string slash log in So inside developed or xml file. We may have a mapping the chase whenever there is a you earl or a request that has slash log in. We want to delegate that call to particular so that for every Ural Patton there is a specific so that toe handle that request. So in case off, log in one off this so that would be taking the request and the job also, that is to control the flow of that request, and that's why it's called a controller. So once the request lands, and so that the soul it will have the logic to delegate that call to model the solar will also send the Ural perimeters like user name and the password. And as part of the model will have things like the business logic. Our anything related to interacting with the data base hit is where we would perform the transactions and gets awfully. JB hit is where the session beings would be reciting or so visits and gets off spring frame book. We have entities did act subject etcetera. Hold is together well, actually process the data and would interact with the database or money. Played the data with the data base. Finally, the job off mortal his to take the details, process them and give some kind of a response in the form off air. Simple data. In our case, we have sent the user name and password, and the model will have the logic to validate the user name and password. And depending on that, it would rather send true or false. Now do taken note. That model does not have any knowledge on the view logic like JSP hatched email, etcetera. All it cares about is raw data is just going to send the raw data. It is the responsibility of the soul. It toe wrap that data with the necessary presentation logic and then send the response back to the client so that it will be represented in some meaningful manner. And this is exactly what is a moral view. Controller architecture. We have a controller logic which will control the flow of the request, and we have the mortal which will take care off crossing the data and then sending back some kind of a response and it does not care about the presentation technologies. Hold the presentation logic. All it gives about is to process the data and then send back the data as a response. The control of will then take it off, wrapping that data with some view technology like JSP or Apache velocity cascading style sheets. Charles crept, etcetera. All such technologies will come in the category off of you because these are all meant for presentation just to improve the user experience. I mean, you just can show the raw data on the browser just doesn't look friendly at all. But the main advantage off using the embassy architecture is that we're encouraging separation off concerns. For example, a person who is working on View technologies does not need to know any off the technologies that fall in the model. Similarly, the developers were working in the mortal area. Doesn't need to bother much about the view technologies, because between these two, we have a controller that is kind off acting like a mediator to control the floor frequents and is helping and separating the concerns. If you have all these layers, club together and develop an application without following this architecture. Then, along with the data, you would also have to take care off, putting the tags that are something to do with the presentation and all. It becomes a lot off mess, and it's impractical to actually write an application in that manner is just going to result in a very cluttered code that is hard to maintain our rather impossible to maintain . So for that reason, embassy is almost like a standard for creating applications. One does that wanted with this approach is that if you wanted to switch to a different view technology, then it's bit off a work to actually make those changes. For example, say that you're currently using JSP has your view technology, and now you're trying to switch to, say, Apache velocity. Then you have to make a lot of changes in all the solar. It's in your application that might be a little messy. In order to address this kind of an issue, we have another pattern called the front control of Patton, and that is a pattern that is incorporated in spring MBC. But what you have seen right now is the typical floor family see application. I hope it makes sense. I will see you soon 6. 0102SpringMVCArc: Okay, let us try to understand. Spring muc Architectural Spring Embassy architecture is nothing different from a traditional embassy architecture, but the only difference is we know have so called a front controller or in case offspring, that's going to be the dispatch of So let. So whenever ed Request is sent from the client the extra duper request, the Web server will take a look at the Bar XML file, and it tries to look for a mapping and this time inside of Abdur XML file, we don't try to map the you Earl with So Let's, but instead would try to map A. You are with a front controller. And in a typical case, we will write the Ural pattern in such way that all the student requests will end up in the front controller. But it is a job of different controller to deter mined the right sole it where it needs to send a request to, and in order for the controller to figure out to would so let to send the request, it will consult so called a handler mapping. Now this is a class that is part offspring framework, and we need to explicitly specify the Ural mapping with a so let inside our conflict file. But with the recent versions Offspring framework, you don't have to do that. We can just simply use annotations. Once we take a look at an example, you'll have a better picture on the same. And once Eric was reached to the soul, let sub let will. Then they'll get the call to model within, which will have the business logic in case offspring. Those are called services, and the service layer will make use off Dow objects or did access objects to be able to communicate with the database and then finally will get some kind of result. And in spring terms, we call that result in model, which is essentially an object that holds a particular data that will be populating to the end user. There's so little then send of mortal, along with the view name to the front controller. Now, the key thing do not here is the control is just going to send of you name. It does not specify where that view is. Reciting are the file extension. For example, if we were to call hello World or JSP, the view name is just going to be hello world. It does not tell the part of that file are the extension which, in case off Jsp, it's going to be door JSP or in case off velocity, it's going to be dot William. So once a soldier it sends a mortal and the view name to the front controller. It's the responsibility of the front controller to send the mortal object to the desired view. But how does the front controller know the location of the view and the file extension? Well, it will take help from the view result over which is again will be configured in the spring Conflict file. And then after that, the model will be sent to the Have you and then a two like Jasper. We'll try to convert that JSP file toe unequal and so let and then the Soviet engine. We'll try to send the tester deeper response, using the response object back to the plant and so the usable see some result. The main advantage off this approach over traditional MBC architecture is that let's say that you're using JSP as of your technology, and now you're trying to switch to a different technology say Apache Velocity. Now you don't have to worry about making changes in the solar. It's because nowhere in this of let code were hard courting the view technology. But all you have to do is to make some changes in the view. Result will and you're good to go. And that's going to save a lot of development effort involved. Well, you know, next week we're going to take a look at a simple example, basically a simple hello world example there. We will have a better picture on what's happening. But in order to keep things simple, I'm not going to use database just yet. We're going to be using until this part the control apart. But sure enough, down the line, we will be using a database in order to create our projects. How will see assume 7. 0103MVCAppStep1: okay, It's time to create our for spring embassy project. And in order to explain things better have actually broken down the task into multiple steps. In the first step, we're going to be creating our project and add the dependencies are the required libraries to build our project. And as I've mentioned before, we're going to be using it to, like, maven to fulfill that purpose. And then after that, we're going to be introducing a JSP page, which will be the entry point. And this is the place where the user would interact from the browser. He would enter some retails, and those details will be sent along with destructive request to the front controller and then the dispatcher soul. It will delegate that call to the controller logic, using the hand of mapping. And then after that, finally, we will render back some result by using a view result war. So let's take it off the step one where we want to create a project. So inside the eclipse Goto file New Maven project. If you don't see maven project in here, click on other and search for maven. You should be able to look at me even project in here and you don't have to install any additional plug ins in order for your eclipse and Roman to stop supporting maven. Moving is such a popular thing that Eclipse has built in support for Megan. Choose the project and click next. What we're seeing right now is a prompt that is specific to maven Project. Going into details about this prompt is definitely beyond the scope of this course. So just fall along with me and do exactly what I'm doing. Just leave everything to default and click next. But in this prompt where you have to choose the archetype, I would recommend you to choose maven archetype who are back because this is the kind of project that will help us create the war file, which we can then deploy onto the Tomcats over to see our application running. Choose that and click next. And as part of the group I d. Just Entercom got company. There are certain naming conventions that we need to follow again. It's beyond the scope of this course to talk about all of that. Just try to type in exactly what I typed group. It is going to become the company and we lived Abortion toe the default one as part off artifact I. D. I'm going to be entering spring hyphen garage stands for a spring project and then hit Finish. It's going to take a while. You can see the progress on the bottom right corner, and once it's done, you should be able to see that project getting populated on this left hand side panel. We are having another. And if you notice, actually, we have a JSP page created by Maven already with some country to tell the world. But we're seeing another because we don't have this older. Maybe I in the class part. So let's try to introduce this holiday P I as well as this spring libraries required for a project. And the way we're going to do that is by opening this pile called Palmer XML File stands for Project Object mortal. And if you're not used to maven, this may look a little intimidating. But always concerned about here is to add few tags, has spot off the dependencies so that maven will download all the libraries for us in order to create a spring Web application. We would basically need couple off libraries. The first off, which is a spring core which will enable all the spring core functionalities and the other is the spring Web Embassy to create above applications. Along with that, we're also going to be including this all that FBI library. Once I had all these types inside our project, let me copy it and passed it inside the dependencies. Stag Hello, Contra shift Death to give proper indentation. And then after that, let me also add the following property in here. Well, I could actually copy this portion everywhere, but the reason why I had to separate it out is because at the moment I'm using release. Why 16 for all the spring libraries in future. If I would like to upgrade to a latest wash in, then I could just simply change in here and don't have to change in all the locations. So let me also add this property inside our formed a maximal file. And after that, all you have to do is to right click on the project maven a bit project only then will may even go and download all the required libraries into your local depository and that's about it. The beauty of it may even is that maybe it is not only going to download these particular libraries, but also the jar files that these libraries rely on. So it will just simply download everything into end that your project ever need. And with this we're done with step number one, we will move on with step number two. 8. 0104MVCAppStep2: Okay, let's move on with step number two, wherein we'll try to create the JSP page along with the front controller or the dispatcher . So let going back to the architecture how on Jsp Page would be present it to the user on the browser. And in our case, we're just going toe. Have one input field where the user will enter his or her name. And then we have a submit button, which, when clicked, all those details will be sent in the form of request of the front controller. But for that way, to have a mapping inside the backdoor XML file to instruct the Web container that it needs to send all the requests toe the front controller and, luckily, spring pro Reuters. The dispatches. Hold it. We don't have to create on our own and Springs dispatcher soul. It well, just saw the purpose. So let's see how it's done. When you create a maven Web application, it comes with the indexed or JSP page, so we can make use off this, and by default it has the hello world takes populated with ash to tank. But I'm going to replace this with the form and the action is going to be, I'm going to give a part and down the land we're going to have some kind of mapping to forward that request to a particular controller logic. I'm going to provide the product name. And then I went to say hello. So down the line will have some kind of mapping, which says, Whenever we have a stripper request that has a following world or the string, we will have a particular controller logic to deal with it and the type off matter that I want to use to send this request his get method. And inside this foam, I'm going to have a couple off input fields and the type off this is going to be text. I'm also going to do a unique identify about the name. It's just simply going to be name. We're going to use this to sort off, read the user, enter data inside our controller logic, and finally, let's also introduced the submit. Nothing type is going to be submit control shift tough to give proper indentation, and that's it. On the JSP page. The next thing that we're going to do is to mention the dispatches all it inside who have got XML file so that the continue can create an instance off dispatches All that when needed and web dot xml file would be inside the Web band off directory. I want to replace this tag with Standard XML and according Tank So I'm going to say XML washing is going to be say we're not hold and and according is going to be utf eight. This is a standard xml dag and hopefully the syntax is correct. Yep No, it is inside the web app tag I'm going to do declare our soul it. Okay, so that bag I'm going to point to the dispatcher soul it so let class the dispatcher Soviet would recite in our dot spring framework Do make sure that you don't mess up with the names . Has to be exact bat that dot So let Dart Dispatcher So let I'm going to give a unique identifier for this dispatcher sold it but the tag So that name and you can give any name off your choice dispatcher is what I'm going to call it. And then there's one more tact that went to introduce because dispatch facility is one such solar that we wanted to initialize right when the containers starts, or immediately after we deploy the project onto the container. And for that we have to use the stag load on start up and we're going to give some positive value. So what this is is we wanted to preen ish lies, this particular soul, that right when the container starts or when we deploy the product, the next thing that we want to do is to provide the your mapping hard the Soviet mapping hopes. I'm just simply going to copy this name, and we want to specify your pattern. I'm just simply going to put their slash, and that just simply means we just wanted to forward all the requests to the dispatcher soul. It No restrictions are Look under shift F to give proper indentation. That's it. Down Step number two. We will continue with step number three 9. 0105MVCAppStep3: Let's continue it. Step number three women will introduce the controller logic along with the handler mapping going back to our architecture. So far, we're able to acquire the user information, and the request would hit different controller along with the user. Enter date as a urinal. Param Eter It's time to now introduce the controller logic, which will do something meaningful with the user. Enter data and in order to instruct the dispatcher Sollett to which controller it needs to delegate the call to. We also need to introduce the handler mapping in the form of annotations and both handler mapping in the controller Logic will go hand in hand in the same file. So let's see how it's done for this purpose. I'm actually going to create a new package, by the way, by default, you don't have the job off holder inside the maven project. We need to create one. So I'm going to create a new job, a folder, and this is where our Java source files will be deciding inside, which I'm going to create a new package. I'm going to call it calm. Company controller. This is where all or controllers will be reciting couldn't have finish and create a new class file. You can give any name off your choice, but I'm going to choose Hello World Controller. And inside this file, I'm going to introduce a public method. I'm going to call the tiles again. You can give any name off your choice, but one thing that you to make sure we to return an object called model and view. That's what we're trying to do. The controller needs to send back the model along with the view name, and that is possible with an object called Model and the View, which is part of the spring framework. So I'm going to say more than and view human method, some name, show message or whatever I look until shift oh, to import all the necessary classes and interfaces and country chef death for proper indentation. Inside this method, I'm going to create a new instance off model and view M. V close, new model and view. If you notice there are many variants off the constructor, that means down the Landman. We have databases. We have more complex ways to send back the data to the dispatcher soul. It we can even send a map with string as a key and agenda type has a value. That means you can also introduce your own objects anyone. All these will come in in future videos. But for now we're going to keep things simple by just passing a string, which will be the view name, but just scrolled on to all these medicine. Tryto read the description that is populated on the left hand side just to get a sense of what they're doing. And as a view name, I'm going to say hello world. You can give any name off your choice, but in future we're going to be introducing a view you know, because it's a jsp page. It must have the same name. Whatever the name that you given here, it has to be the same name down the line. So just simply fall along with me and you the same name and with the semi colon. And before I returned this particular object I'm going to add a couple of details had object. This will help us add an attribute which we will be reading inside our view, which will be sent back as a response. So I'm going to say add object. I'm actually going to use the matter with two para meters. The 1st 1 I'm going to say hello has a key and the values also going to be Hello. The second attribute, however, is going to be a little tricky because I wanted to read the Ural perimeter that was entered by the user. So this has to be I'm going to call the key as the name, and this in here has to be the user into data. That means we're going to be using this particular name to read that user enter data. But how do we get the user enter data before that? We want to make sure that the dispatches over it is able to forward the request toe this particle controller logic and that happens with their request mapping. So guess what? I'm going to introduce an annotation at the matter level, and it's called request mapping, and I'm going to send one para meter, which is a string in my case, I'm going to say hello. What this means is whenever there is a request that has a following string, this is a handle logic for that. And if you remember inside are indexed or jsp. We do have that in here. So whenever the usable submit this form the request your little must be having the following string. The same will be identified by the dispatcher soul it using this request mapping And so the following handler logic will be triggered Now we also need to read the Ural perimeter and there is another annotation for that purpose. It's request Batam and then you would mention the perimeter that you want to read by providing this attribute called value And then you would provide name Basically, whatever the name that you given here is the same thing that you would provide. And in addition to that, we're going to say that this is required has false. These are not mandatory, but just giving them anyway. And we can also provide default value in case if user does not enter anything, then this is going to be the default one and want to say world. And then finally, I'm going to specify the method argument string name. Now this particular argument name will hold Whatever is the value the resulting value off this annotation. Now I can use this name in here to be able to read the your With Madame, we seem to be having another Let's see what it is. Oh, yeah, Went return this object back to the dispatches. So let and that's it, were able to introduce the controller logic along with the request mapping and by just returning the model and view object. The underlying spring container will take care of handling that object to the dispatcher solid, but we're not done yet. There's one last thing that went to do as part of this step is to specify this has a bean inside the spring conflict file Well, in dies offspring, you in the controller is essentially a bean, and typically the conflict file would be with the name the name of the Soviet hyphen, so that dot xml and that goes inside the ribbon of directory. So let's just quickly created. I'm just simply going to copy the web dot xml and name it as dispatcher hyphen. So that and typically for each never dispatches solid, we would have won conflict file associate ID, and this is a file that spring will take a look at in order to create the context or to create instances on demand. We'll talk about the route context, application context, Web application context accepted on the line. But for no. Make sure that to have this fight in place with the following naming convention that's a solar name hyphen. So let if you want to have a different name, or if you want to store this file elsewhere inside the by buying off directory, then you have to add a context. Batam tag inside the web dot xml file. But this is a standard convention that everyone follows in reliable projects hit, okay and inside this, we can specify are beans, and I already have the content ready with me. I'm just going to copy it and have it in here. I really can add the controller as a being inside this conflict file, but in real world products, we can have 100 self controllers, and it's really hard to maintain them inside a conflict file. Spring providers the convenience off so called a competent scan, or that means is you can just annotate this as a controller, using an annotation just about the class definition and spring will take care off. Scanning all the beans that are annotated as at the raid controller. And that scanning happens only when you provide the following tag that will say it was a lot off effort, and with this we're done with step number three. 10. 0106MVCAppStep4: as part off step number four, we're going to be introducing the JSP page along with the view result War. Going back to the architecture were able to acquire the model and the view object from the controller to the dispatcher so that now it is the responsibility of the dispatches. Hold it to identify the right of you and send a model object to it. And in order for dispatches, sollitto identify the right view. It needs to know the location off the view along with the file extension. And for that it's going to consult the View resolver, which is also a class that is part offspring frame book. So let us first introduce the view, and then we'll introduce the view, resolve our I'm going to create another folder inside the bourbon of directory. I'm going to name it as views. This is where hollow response views would be reciting and do. Make sure that you create this particular folder inside the turbine off directory because whatever that recites inside, developed by enough cannot be access directly with a your and inside this I'm just going to copy out existing JSP file and makes a minutes to it. Of course we want toe named this as Hello world. Basically whatever Dave you name that. Just send back from the controller. It has to be with the same name. Only then will the dispatcher solve it. Identify this and I want to replace this with her. Simple. It's three tank inside which I'm going to read both the para meters that we had set in the controller. Hello And the name? Hello. I would give a space and then name. Now it's time to introduce that view. Resolve or and we can specify the view result were inside the conflict file like so So this is a class file reciting in the spring framework. All we have to do is to inject a couple of properties like we're doing here. The 1st 1 is the prefix which will tell the part where our response view is reciting and another properties the suffix. In our case, it's jsp. Since we're using, JSP has a view technology. If it is something else, you would have a different subjects that's have the file and we're done. We just need to run our application now. It's really unlikely that this would work in the very first goal because things that are as simple as file names can actually mess up with exhilaration flow and can result in an error . But let's see, we already seem to have a cross market, but I don't see any others inside this package. I'm assuming this is not intended. Let's refresh the project once before we done it. Let's take a deep breath and go to run us run on silver. And here he would choose the Apache Tomcat server that you're downloaded. In my case, it's washing number nine. Hit next and hearing it, too. Select the territory, the home, their tree off the Apaches over and then click Finish. This will deploy the war, file into the server and then run it. See what's going on here. There seemed to be no exceptions that center some value when to say some names. I'm submit query, and we got the response that does not go back and enter some of the name. Hello there, and it worked. If it worked for you as well, then that's great. If it didn't do put me question and I would be happy to respond and let me tell you this. I'm actually going to make this project available for you to download so that he can import this into your workspace and work with it. But I wouldn't recommend you to do that. Since this is the first embassy project that you're working on, I would recommend you to just try to do everything from scratch all on your own. And guess if you face and issues I'm there to help but do it on your own. Because this is the first crucial milestone for you to learn spring MBC. So don't lose this opportunity. Hope it makes sense. I will see you soon. 11. 0107WebAppContext: let us talk about the Web application contest in spring. Whenever the silver start, it will take a look at the deployment descriptor or developed or XML file, and it notices that it needs to load the dispatcher select. And since we said the stag load on start up and gave a positive value, the servant knows that it needs to preen ish lies the dispatcher. So let and the job of dispatcher sell it is not only to divert the calls to a relevant controller logic, but pray or toe that it needs to create so called a Web application context inside, which will have the instances off all the beans that are declared in the conflict. File the Dispatcher soul. It would be able to identify this file with the following name Dispatcher, which is the name of the Soviet that you given here high pins all the dot xml file, and this has to go into the root directory with the name Web hyphen. I enough. If you have this file deciding in any other directory hard, if you have a different name, then you need to add so called and in it, madam, with the following Batam name. That's context conflict, location in Camel case. And then you would provide the class part as its value, which would point to the file name. But whichever way you follow the whole point off dispatches Soviet is that it needs to create the Web application context and thought of create. Singleton instance is off all the beans to find in here and in here. We're currently performing the components can off this package within which we have set off controllers annotated with that direct controller. Now you may have a question as to why should we let the dispatches all that create the Web application context? Why shouldn't we create the context separately? Well, the answer is the dispatch. Issel that is tuned are written in such a way that it has the knowledge on how to delegate the calls to a specific competent based on the request mapping. In fact, the dispatches all that internally uses the Soviet context in order to get access to various instances and para meters. Also, if you remember, I mentioned that there would be a Web application context for each and every dispatches solve it, which means we can have more than one dispatches sold it. So what are some cases where we might be needing to create multiple dispatches? Soul. That's well, one such example that I can think off is currently we're using spring MBC, the spring by BlackBerry. But the same application can also use another library like spring Web services. In that case, we might need to use another dispatcher, solve it specifically tuned to work with Web services, something off this sort. So we have this particular dispatches. So let the message dispatches Soviet, which does pretty much the same job as off the dispatches sold it. But this is meant for spring Web services, another case where you might need multiple dispatches. So that's is when you want to segregate the controllers in an organized manner. For example, you might want have a set off controllers for website authors and another set off controllers for website admin and another set of controllers for develops that visitors etcetera in that case who just make multiple copies off this tag essentially want to create multiple dispatches, all that instances and then have a different your mapping reach one off them. So, for example, maybe for upset artery might have a your that has Arthur text in it. Something of that sort. The point I want to make here is you can have multiple dispatches. So let's and each dispatches all that would need its own. My application context. You can create a Web application context specific to Web services, using a normal dispatches so that which is meant for spring Web and wise worsen the message . Dispatches solve. It is not June toe Delegate. The cost of spring Web component. Once we talk about root application context, I'm actually going to show you a quick diagram on how things are organized here, thereby you will have a better picture. Hope it makes sense, House, he assume. 12. 0108RootApplicationContext: Okay, let us talk about the route application context. So far, we're able to perform the components can. Inside the following package we're in all or controllers are reciting, but down the line, we may actually have to introduce some additional components, because when we introduce some additional layers like service layer or the data access later, etcetera, we may have some additional components like this. We may have a service component, which is where our business logic would be reciting. And then we may have a repository component which will help us interact with the database, etcetera. We can actually perform competent scan on all those packages wherever these components are reciting and make them part of the dispatches all that XML file, so that when the Web application context gets created, all those instances would be created as well, which is perfectly fine. But the problem arises, especially when you have multiple dispatches. So let's, for example, inside our web dot XML file. We have a couple of dispatches, so let's and each would correspond to their own specific of application context. So performing the competent scan on service components from one conflict file will not suffice. Same has to be performed in all the conflict file for all the dispatcher Soviets, which is definitely not a good idea, because we may end up creating duplicate instances in each and every Web context. The answer to it is the route context. We're going to create yet another context called the root context, where we would keep all those common components that we want them to be accessible from all the Web application context that correspond. Each never dispatches solar. I'm going to show a diagram that would represent the scenario. But before that, let us try to understand how we can create a route application context. For that, you have to add a context Barham in this manner, along with the context loader listener. This is a class that would actually make use off this context. Batam. In order to find or locate the application context or XML, file and create the route context and inside the application context XML file, we would perform the components can off services or repositories, basically all the components that does not have that it relation with the dispatches all that. So, as a rule of thumb, you can remember that whatever goes inside the dispatches off that contact file has some kind of relation with the dispatcher, so that while inside the route application context, we would have components that will remain common for all the Web components. So let me quickly show you a diagram that represents the following scenario. So here we have a couple of dispatcher, so let's and their corresponding with the application contexts and the need to have application context, we have companies that are related to the dispatcher sold it, so we may have controllers view result, vers or handle map. Incompetent, etcetera. So here we have couple of dispatches. So let's along with their corresponding context. And inside this context, we have Singleton instance us off all the components that have a direct relation with the dispatcher sublet. So we may have things like controllers or view resolve er's our handler mappers etcetera. And then we have the route context, wherein we'll have the components that are going to remain common for all the Web component like these. So you can think off the route context as kind of like a parent context for the Web application context and whenever you need a specific competent, the continued for such inside the Web application context. If it doesn't find there, then the call would go to the root context to find irrelevant component. Hope it makes sense. Haven't see you soon. 13. 0201SpringBootIntro: I'm pretty sure that you have been hearing about spring boot for a while, doing the fact that it is such a buzz word in the industry, but you don't know exactly what it is. Well, hopefully with this we will have some better picture on Spring Boat and the problem that it is trying to address. So before we talk about the spring boot, let us try to understand the problem that it is trying to address. I mean, all the tools out there must have come into existence to solve a problem created by some other technology. Right and springboard is no exception there. So let's talk about the problem first as a developer, even if you were to write a simple hello world application using spring framework, the following are the typical steps that you need to take. You would create the project using a project management to like Meghan or Gradel, and this is going to take place, probably in an idea like eclipse. And after you do that, you'll have to take care off, adding the dependencies or the required libraries or the jar files that you're going to use in your project. No, this mess on simple, but practically takes a while to do the research on what are all the libraries you'd be requiring in your project. And then you have to take care of finding the ideal tags that you need to add in the palm the maximal file so that men will take care of fetching all those libraries into the class part. And after that, you have to take care up, installing all the required. So first, you have to download the Tomcats over, install it and also configure it in your I D so that you can run your application directly from your I D. And if you're using a database software, you have to install that as well. And only after performing all these steps will you actually jump into writing the application logic. And the story continues. After you write the application logic, you have to create a lot of convict files. For example, you have to define the dispatcher Soviet in the web dot xml file or equal and java file, and you also need to define all the beans, for example, something like a view resolver in the Web conflict file, etcetera, and similarly, for using database, you need to take care off, introducing some additional conflict files along with the data source and entity manager to be able to talk to the database, etcetera. And then after that, you take care of building the project, deploying Dart, in fact, onto the server to see it working. But what is the problem here? The problem here is, as a developer is supposed to be focused on writing your application logic. But you're forced to pay attention to a lot of other aspects which will help you run your application. And remember, all the steps are required to run a very simple application like Hello world. You're probably not going to work on a hello world app when you're working on real world projects, right? You're going to deal with a lot of conflict files. You're going to deal with thousands off lines off court. Imagine amount of time that the dollar, perhaps to spend on all these aspect about from reading the actual application logic. That's a huge waste of time, and it would severely impact the overall productivity off the company. They're going to be delay in the project deliveries, etcetera. So how about having some kind off a tool that will take care off step 1234 and six on eight . And as a dollar per you, the only required to focus on writing the application logic. That's exactly what Springboard does it's going to add. The dependence is for you. It's going to use an embedded silver there. We don't have to install the silver manually. Same is the case with the database. Spring boot will also take care off at in the conflict files for you, depending on the kind off libraries that are required in your project. So on and so forth. Well, all this Miss own little futuristic, but it is in place. Spring Boot is already doing that for us. Once we take a look at an example, you'll have a better picture on the same. And here is official definition. Off the spring boot springboard makes it easy to create standalone production. Great spring based applications that you can just run were taken opinionated view off the spring platform. Enter party libraries so you can get started with the minimum, plus more springboard applications need where a little spring configuration. I'm pretty sure that this definition may not make complete sense to you at this point, but once after we take a look at a simple example, offspring boot. This definition will make a perfect sense, so we'll get back on this letter. And here are some of the features that spring boot offers at a very high level. Again, we're not going to talk about these right now. We'll take a look an example first, and then we'll get back here to uncover some of these features, thereby you will understand better. 14. 0202CreatingSpringBootProjWithSTSnInitializer: Okay, Let us take a look at how we can create a springboard project from scratch their multiple ways to do so, but they approach that I'm going to follow in this video is by using so called as spring tool suit, which can be installed as a plug in in your eclipse and Roman. We're going to explore the other options in coming time. So go to help a clips marketplace and search for that plug in spring toe suit, alternatively condone, or the zip file from the Internet and install the plug in manually from Eclipse Home Directory. But before you try to install this plug in, do make sure that you have the latest version of Eclipse installed, get all the updates and keep the software up to date. In my case is have all that installed. This particular plug in it is showing as installed, but you go ahead and install it, accepting all the prompts. You can leave everything toe their defaults, and once you install this plug in, by the way, this pregnancies from the water make sure you don't install any other random plug in that you're seeing in here months. Install that plug in, just goto file new, go to other and search for spring. You should be able to see this spring starter project. You will not be able to see this unless you install that particular plug in. If you're familiar with creating maven projects in eclipse, I D. Then this interface in here Well, look very familiar to you. The first field in here is a your That's where the spring initialize er is reciting. We're going to talk about it in a while. The name is going to be your project name. You can give any name off a choice and the type of project management tool. In my case, it's maven, so I would leave it to default. If you're using Raedle, then you can choose either of these options. The packaging part is a little tricky. If you're coming from Java background without much often exposure to spring boot and cloud architecture, then you may be tempted to choose who are archive here. But in our case, we're going to be needing jar file. This jar file in here is different from typical jar fell that were used to when we think off a jar file we would think off the tiles bunch of dark class files. But in this case, this is not a simple jar file. It's called a fat jar. It's a world in itself because the fat jar is going to constitute everything to run your application. So it's going to constitute all the libraries that your application ever need, including the silver's very replication would be running. So the result in Jar file is something that you can just run with a simple command and you would see your Web application running well. It will make sense in a while, however, if you're not going to use them better silvers. But you want to deploy your application on an existing Tom kits of are located elsewhere. Then you can create a war archive and then take care off the throwing it over there. For now, just use jar. He also can choose the JV, um, language off your choice and my guess. I'm going to be using Java. I would leave it to default. You can also choose the job abortion. I'm going to leave this to default for now, and everything else you're seeing in here is something specific to maven. There are such a naming conventions that you need to follow. So if you're not ever off heaven, I would recommend you to type in exactly what was type didn't here. And after you do, so click next here, he would get to choose so called a starter project dependence is now. These are little bit different from project dependence is because typical in the maven project, you would choose all the set off dependencies or libraries required in your project. Here, you would choose the technologies that you're going to use in your project. For example, let's say my application needs a database, something like post curious cure. Well, you can just simply choose this and spring boot will take care off, including all the dependence is required to run equity in the state of base. Or, if you're using a close service like Amazon Web services, then you can choose one off. These are Microsoft Azure. You can just one of these, you know, case we're going to keep things simple for now. And I'm just simply going to be needing a Tom gets over to run our application. And if you simply hold your muscle, what there, you can actually see the description. If you sell it this particular start to dependencies, then you'll get everything in place to start working or building a rest ful Web service are serving Web content with Spring Embassy are to build arrest service with spring, and this is exactly what I'm going to be needing. So this comes with embedded Tomcats over as well. So there is no need to you installing this. So was separately again. Once we create and run the application, all these would make perfect sense. So you need to hold on to that point and click next in here. You can actually see the Ural that is being used to send the request to this. Bring initialize er. Let's quickly take a look at what's happening in here. Control. See, go to browser and see what's going on there. So whatever you have done so far using spring tool suit you pretty much through the same stuff in here as well. Say what? Jews At the maybe no, gradual. You would choose the language Springboard wash in which we will just simply leave it to default and then project matter, data hero, the Maven coordinates. What proper naming convention, and then, finally, he would get to choose. All the dependence is required in your project are for your application. So here are the list off dependencies are the technologies, essentially that you get to choose. And finally, after you choose everything you can click this button gendered project, which will generate a ZIP file, which you can import it as a maven project inside your Eclipse and Roman. And that's essentially what's going to happen here as well. This is a your that is being used to send the request to that server to perform the initialization process and then get back. The result as the file which the stool will imported indoor eclipse and Roman and sod off created project that we can walk on. So let's hit finish is going to take a while, and here we have it. We just created the spring boat application. We do seem to have one ever let's take a look at what's happening in there. Well, I don't see anything that May to fix. I'm assuming that this is shown by mistake anyway, Let's leave it there and and I'll see you soon and I will see you soon 15. 0203ProjectWalkThrough: Okay, let us explore what's going on in this project real quick. What you have here is pretty much a standard maven director structure you have source Main Java directory within which you have this package. Calm that company. This is something that you specified while creating the project using spring toll suit. And inside this data to recon have all your source files. Spring toe suit also generated. One file for us will explore it in a bit. We also have the resources folder within which you can keep all your static resources like images html, CSS, JavaScript, etcetera. Or, if you're using any kind off a template engine like Time Leaf, you can keep all those templates in the Star victory. So what's the big deal in here? Everything looks pretty normal, right? Nothing significant. While all the magic is happening right here in this form that XML file. So let's explore what's happening in their first Let's take a look at the dependencies part . Remember, While creating the project, you have chosen web as a starter dependency. Well, here you have it. One of the features off maven is that when you specify a particular dependency maven will not only download that particular dependency, but also the dependence is that this dependency depends on. For example, say that your project is dependent on Project A and Project A is dependent on project be when you specify Project A as part of the dependency. Maybe we will not only download Project a jar file, but also beast, because is dependent on B. That's called transitive dependency. I hope I made myself clear. So with spring boot, you have this dependence in here and inside this particular project Springboard Start of EB you would have all the libraries or dependence is that you ever need to run your Web application. If you're using Eclipse, you can press control and you can explore what's inside the poem that XML file of this particular project. And if you notice he would come across with all the dependence is that would ultimately help you run Web applications without spring boot, you would have to define all this. Dependence is yourself. You have to spend time doing research on water all the libraries required and then find the right war Shin's and then include all those dependence is in here well with spring boot. You don't have to do that. All you have to do is to specify the technology that you want to use and you're good to go . Another key thing to notice here is you don't have to specify the wash in Washington D managed by so called a parent Palm. You would specify the parent bomb with the stag parent, and it would give the project coordinates. So let's take a look at what's inside the parent palm. Can you compress on control and you can click on this project and here is a parent Palm Springboard dependencies, and this will have all the dependencies, plug ins, properties, configurations that you would ever need for any kind offspring project, and all these would be inherited into a child project. But do taken note here, you would see literally. All the dependence is that spring boot ever supported. Springboard doesn't include all these dependencies and plug ins automatically in your child project. There isn't being human or be needing all those dependence is right. You're not going to work on Amazon Web services. Are you not going to be used a mongo DB or whatever, so you don't have to include all those dependence is and increase the size off your resulting artifact. But what you can do is you can specify the dependency that you need and just off the configurations would be inherited from the parent bomb. And so we don't have to specify the washing number in here because it is being inherited from the parent bomb. Let me search for this particular artifact inside the bed and bomb. And here you have it. This worship number would be inherited right here inside your project. Same is the case with the plug ins and other configurations. All those configuration details would be inherited only when you need them. You can actually control the springboard washing itself. In this case we're using to rot one about five. He can change the washing if you wish. And accordingly, specific parent palm would be targeted and saw the dependencies abortions. So you don't have to really manage the dependencies yourself, including their washing numbers. All that headache will be taken care by all this springboard projects. We also have a plug in, which is Springboard maven Plug in. It's really crucial that you have this plugging in place because this is what is going to create what I call a reasonable fat jar. We'll talk about this plug in once after we run our project. But again, it just specified the plug in that you want to use your in space for any office configurations. All those conflagration details would be fetched from its bed and foam. 16. 0204AppLogic: okay, It's time to bring life to our application by writing some logic. So now we're going to be introducing some presentation as well as the controller logic. But before that, we need to choose one off the template engines that are available in the market. One of the popular options would spring is time leaf, and there is also free marker, and we'll have Apache velocity, which is now off course, outdated. You can even use JSP without any problem, but the one that I've chosen for this particular video is a party free marker. If you're not familiar with the patchy free market, that's fine. If you're familiar with any other your technology like, say, for example, Jsp. You can understand free market pretty easily because all these your technologies are pretty much in the same page, and they pretty much have the same syntax. So this shouldn't be surprising to you. But one thing that we need to do is to add the starter dependency. I copied it from the Internet, and I have it handy, and so I'm basting it in here. I look under Shift F to do proper indentation, and then once you add the dependency. You need to do a maven update off the project so that all the dependencies, including the transit dependence is would be downloaded from the remote depositary to your local depository by moving. So let's do that real quick. So now we have all the free marker libraries in place. The next thing is to just introduce accord. Brother. We didn't talk about this particular dependency, which is added by default. Typical in any kind of a project. It would definitely have unit tests in place, Right? Enter Spring has added this dependency to test your application more on it at later point of time. So I already have the cord handed with me. Our goal off our application is to show an input field to the user along with the submit button. When the user enters his or her name and clicks a suburban button, the request would then go to the silver and sort of the controller. Based on the request. Mapping and the cost mapping text will match with this action texting here. And so we can say that the request would hit this particular method and in the process were also reading the Ural para meters. I mean, whatever the name that the user enters will be read and stored inside this perimeter name. And inside this method, we're just simply populating this particular object model and view. This is a view name that we want to render back along with the results, and I'm adding couple of attributes, which will be read from inside the view. So after we returned, this particular object spring framework will take it off, giving this object to the dispatcher soul. It dispatches. So that will take help from the View resolver to identify the right view based on the name as well as extension. And it would forward the model data This couple off attributes to that particular view, and so we were able to read the information from that view. So let's quickly introduce this particular page, which is going to be the home page, so it's going to have the name index dot water the technology that you use. In my case, it's free market, so it's going to be FTL is extension for free marker. We already have the templates directory, and here is where it would go, so it's going to be indexed art FTL. Similarly, I'm going to introduce another free market file to display the results, but do make sure that you name it but the exact name and there's just one last thing before we can magical run out application, its gentle just the controller logic. Let me copy this piece off code and create a new class file inside this. Hello World Controller. Dr Java Control shipped Oh, to import all the classes and intra faces and control shift eth. The court is indented properly anyway, and that's it was seen to have another off course, but it mentioned the package. Let's do that real quick. And will you believe me if I say that we're done, we're good to go. And on our application, the answer is yes. That's a beauty Offspring boot. So let's run this particular file now. We're definitely going to get into details off how this is working and stuff like that in a while. But for now, just run the application and see, and that's working out. Just bring boat. App it. Okay, And if you notice the results here, you would notice that the M. But it's over. It's started at Port 80 80. Even the soul that engine has been started. Even the have application context is created, including the route application context. And even the spring is able to identify they in the START FTL file, which will be the default page that gets rendered when we visit the your In our case, our summaries hosted in the same PC. So it's going to be a local host and let's go to browser and type in local host. And then 80 80 hit, enter and hopefully things will go well. Ah, something is terribly wrong. Let's take a look at what's going on inside the index start FTL file. How dare you go? We're supposed to pass this code. Sorry about that. Real quick. A quick tricks. Save the file. Stop the program and run it again. Everything is as expected. That's reload the page. Let me type in something you can type in your name. But I'm going to Stipe some something. Whatever it iss click submit. And there you go. It worked, But now the $1,000,000 question. How did this happen? This looks very magical, right? Well, the magic is happening in this particular instruction. I will explain it in a while 17. 0205HowItWorkednCreatingJar: Okay, let's take a look at this magical file that is doing a lot off stuff. Let's break it down. And for stop with the sanitation. Although you're seeing single annotation in here, it is actually combination off multiple annotations. So this is one of the convenience provided by spring boot. Instead off you having to define or declare all these annotations, you can just declare one annotation. The first sanitation would just say that this particular file is the springboard conflict file. I mean, if you worked on spring projects before and when you define your contract file where he would list on all the beans, he would annotate it with advert configuration. Well, this is exact same annotation, but for spring boot. And secondly, you have this enable auto configuration, which will enable the auto configuration, meaning whatever the dependence is that you add in the palm, the XML file springboard will try to make a guess on what put with the ideal configuration so you don't have to create conflagrations. As an example, we never declare our dispatcher. So let it was all taken care by spring boot and even let's say that you're going to introduce some overtime framework like hibernate. Then you can just provide the start of dependency and spring but will take care off, creating the conflagration. And for a dependency like hibernate, he would need a data source, entity manager and the host off other conflagration details which would be taken care by the spring boat. You can also alright certain conflagrations if you wish, but more on it later. We also have this competent scan annotation, and this particular generation would enable springboard to scan all the beans in our project. I mean all the classes that are annotated with that direct controller, address service or address repository, etcetera. All those components would be discovered if you specify this particular annotation and the other annotations are not off a great significance. Once a specify the sanitation have to call this method run offspring application class. And here in the sanitation, we have actually enabled a lot off stuff, but it is in this class where the actual action will take place, so it's going to create the application context wherein you'll have all the singleton instance is and it will also register recommend line property source to expose command line arguments meaning this has something to do with externalized configurations, which will talk about that later point of time. And it would also help in refreshing the application context. Again, as we progress through the course, you will see these features being used. But ultimately, for now, you can think of this as this is going to kick start out application or bootstrap our application by combining everything that we defined and finally help us launch our application. Also, it's what mentioning that were not really creating a war are Kevin than deploying into them . But it's over. This is going to walk a little different. I mean, if you want to create a rock of, then you should be having a verb started to write. And moreover, within Builder project, we just run this file and everything is working and our application is working, gripped. So this is a John archive we're talking about. Another thing to note is for testing purposes. We developers may actually run this main method, but in production, this is not how it's going to work in production. We would actually deploy the jar file and that John file works at a standalone application , meaning you can run that jar with just a single command and we can treat their jar. If you remember, we call it a fat job that would have everything in place. It would have all them, but it's overs libraries, conflagrations and what? Not everything. To help run your application. In order to create that particular jar file, we can right click on the project Goto Maven. How rad the wrongness may have been build. It is successful, but in my case I have used an existing configuration. But you may be required to provide a goal with me. Show you what I mean. Here is where you need to mention the goal and the goal that we are focused on right now is package going to package everything as a jar archive. Because if you remember, that is artifact type we have chosen. We've done that while creating the project. Using spring initial eyes. There are spring tool suit. I believe it would default to John file and after the building successfully would see that the target directory of me just quickly refreshed. This has this artifact in place. Let's go to that directory and take a look at what's inside this file? I'm going to use the software. Seven zip to take a look at what's inside it. If you go to Mattei enough, you would notice this manifest file and it has specified our class file springboard application, which is a starting point. This is the file that were run to see our application working. And when you run this jar using a command in Windows, it's Java happened jar and the name of the jar file that would would stop everything but in generally. This is the class that gets called. Let me just show you real quick. So before you run the command, make sure that you terminate all this otherwise will have poor conflict. So I'm going to go here and location where John Farley, the deciding Java Have fun jar Hoop. Oh, God. Editor seemed to have not changed, so it's going to be slash D Still No, I guess I have to use the other slash and there you have it. Job a hyphen jar and let's run it and you're seeing the same result. Let's go to browser. You're fresh And it walked 18. 0206SpringBootFeatuersRevisited: Okay, let's revisit our previous slights and see, for perception about spring boot has improved a bit. So typically without spring boot. These are all the steps that you need to follow, but with spring boot, you need to follow the step number one. Create the Maven or Griddle project, but you don't have to follow this step Number two in here, which is to find the required dependencies or libraries that your project needs off course . We need to add the start to dependencies, but you don't have to add a whole list off libraries that your project ever needs. You just have to focus on what technologies you would need in your application, not what libraries he would need in your application, and that's going to save as significant amount of time. I mean, tell me if it is easier to find the one single start to dependency our 100 different library dependencies. Obviously you would prefer to find one tag, so I don considered this all that off a pain and would exclude from the list off things that you need to do in case offspring boot coming to step. Number three wouldn't installing the software wouldn't installing Tomcats overall, installed it or even configured it. It's all taken care by spring framework with an embedded silver, and same is the case with Step number four. Although we haven't used database, even if we had toe, we don't have to install a database software, and then off course went to ride the application logic. Coming to Step number six. Create a conflict while defining all your beans. We didn't define our dispatcher Sollett or the View resolver our even our controller. It's all taken care by spring boot and again, we didn't use database. But even if we have to use, you can live raised the auto configuration functionality and let the spring boat do the conflagration for you. But if you want Oh, all right, some of the perimeters you can do that. We'll talk about that later, and then you don't have to follow step number eight. In order to see your application working, you don't have to bundle your project as a viral archive, manually copy that war, file into your mom, gets over and then tested. That's a very long and lengthy process. You just have to run one single file. That's it. you will see your application working so pretty much Everything is automated by spring boot except step number one and five. And be happy that these steps are not automated. Otherwise, we don't have jobs today. That's more and try to understand definition. Now this definition will make 100% sense to you. Well, hopefully, springboard makes it easy to create a standalone production grade spring best applications that you can just run exactly what has happened. We take an opinionated view offspring platform and third party libraries, which means auto configuring, depending on the type off libraries that you add in your project or the type off stopped or dependence is that you add configuration is taken care by springboard. That's what the Stedman means. And so you can get started with minimum fasts, which means spring good will try to auto country where everything. But if you're not happy with it, or if you want to make some amendments, you still have the flexibility to do that. So majority off the job will be taken care by spring boot. You just have to take your a few minor things if you want to, and more spring boot applications need very little spring configuration, and the features would sound very obvious to you. Now, at least a few of them automatically configure component Centre Party libraries. Of course, this is true. It is very evident in our sample. Application creates standalone spring applications with temperate servers where a true provide opinionated started dependence is super true. Provide externalized configuration is something that will talk later and provide developer tools, which is again something We'll talk later. This there are little advanced use actuator advanced and provides testing you till it is not now. So at least you have some good overview on what is spring boot. And I believe you're convinced of the fact that it is going toe. Save a lot of developers time as the dollar, but don't have to pay too much attention on creating then Roman to run the application, but rather spend a lot of time in creating the application itself. And that's the major problem that springboard is trying to solve. All right, I hope it makes sense. Have a great day. I'll see you soon 19. 0207DeplyingAWarFileUsingSprinBoot: OK, currently we have a springboard project that is generating a jar file that we can just run on any JV and platform. But if you're following a monolithic way off developing applications, then chances are that you want to deploy war file onto an existing Tom, gets over and not use embedded servers in this video, I'm going to walk you through how you can make some changes in your project so that you can now gender the war file and then deployed on any Tomcats over the first chain that went to make is to make sure we said the packaging type toe war inside the bomb dot xml file. If you're using maven, this will ensure that the resulting artifact that gets created after we build this project would be of our file. Another change that you need to make inside the Palm. That XML file is to make sure that you said this dependency to provide its scope because we're going to deploy on Tom gets over. We don't have to have the storm cat libraries inside our war file there, already provided by the time gets over. And so we have to set the scope to provide it. Let me say this file and since we're going to deploy it on a Tomcats over and Tomcats over can typically have any number of applications running this time, our application, your role is going to change a bit. It's going to look something like this. And this is the name of the project that we have except in here. And so we have to make those changes inside our application accordingly. Inside or index start FTL file. We had this text flash. Hello? No, since the Ural is going to change, we have to ep in destroying as well so that the request would be sold by the spring boot application. And there is one last thing that we need to do is to make changes inside our springboard conflict file. But before we talk about the changes that went into just here, let's take a look at how we created the application context without using spring boot. So here we have that last file that is implementing Web application initialize er and whatever the class that implements this particular interface, the Tomcats over, is a wear off the methods in it. So as soon as we deploy our application onto the dom gets over Tomcats over will call this particular method on start up along with passing the Soviet context object and inside here I'm creating an instance off annotation conflict web application context as we're going to create a context using the Java conflict which is right here and then we're also creating an association with the solar context so that Sprink and Dr the underlying platform which is a Tomcat server, to do a variety of things. So here is how we have created the context without using Spring Boat Well, in springboard, we have to do something similar. We're going to be using a class file that provides implementation to this interface. And here is a class that I'm talking about. Let's take a look at what's inside it. So it has implemented the Web application initialize er and has also provided the implementation for on start up method, which is exact method that we have overridden. This method has pretty much done the same with this instruction. But what this logic is not a better off is is a convict file with the instances something like this, this is a glassful that we have created and then fed this into this particular method. But here it cannot make a guess on the conflict feel that we're going to create. We have to manually provide that in order to do so. We have a method that we can override. And that method is let me such for con feeder. And here is that method Let's overwrite this mattered here like so and then we're going to provide our conflict file. And, of course, in case offspring boot, this class is a configuration file. And with this we're done with what we have to do. All we need to do now is to build this project. I'm going to go toe run as may have been built. Package is the goal that I want to sell it. And after it's done, you can dry click on the project rawness Run on server has you mean that you have configured the Tomcats over inside Eclipse Click finish and you would see our application working right here. And there you go. Ignore all the messages in here. That is something that will talk about incoming videos 21. 0302InterceptorExample: Okay, let us take a look at an example off Interceptor and spring. I already have a working springboard hello world application, and I'm going to introduce some changes to introduce the interceptor for our controller. The first thing that we need to do is to create a class file. This is a very plain class, while no funky annotations or what so ever Well, we're going to introduce some in a while. The first thing that I'm going to do is to use an interface called Handler Interceptor. And this is the interface that has some default method in it which, if you wish, you can all read them and provide some behavior. And here are the methods that I'm talking about. Pre handle will come into picture before the controller is executed and post handle comes into picture after the controller logic and after completion will come into picture after the requester sold to that line. In my case, I'm going to all right, all these methods and I have them in here. The pre handle method would return a Boolean value if it's going to written True. That means we are giving a green signal that the request can be forwarded to the desired controller. If this region's falls in spring from Michael assume that we're handing the request ourselves inside this method, and it doesn't have to take the request all the way to the controller and send the response back to the client, and here he would typically have a logic. For instance, you may want to authenticate the use of before you forward the request of the controller, and it can use this request object for the same. You would civic was dot So we have this method authenticate, which will trigger the same authentication process as would be triggered. If the request is for a resource that is protected by a security constraint, at the moment wouldn't include spring security into our library, and so we cannot authenticate. But down the line when we create applications, then we're certainly going to include spring security. And so the authentication logic. But you got my point. I hope for simplicity's sake. I'm just going to print a message and written true and similarly, we also have the post handle as well as the after completion matters with simple messages. One another thing that I need to make sure is to add the sanitation at the rate component. Because this interceptor is not a controller, it's not a service. It's not a repository hit some general component, which we want to be discovered by the spring while performing the order scan. So by saying this at the red component, this particular being would be identified by the spring and spring would create an instance off it in the context. Likewise, we can have any number off interceptors as you wish, in which case you would create another class with similar methods. But spring cannot make a guess on what our old interceptors that you want to act to it and what you want to deactivate. So for that purpose, we need to manually register these interceptors ourselves in the Java convict file. But since we're using Spring Boat application wouldn't create the Java conflict file ourselves. It is all taken care by the spring boat, but what we can do, rather is make use off. Another interferes, which will have set off callback methods, and these methods would be called by spring. Let's take a look at all the list off matters in it, so here we have list off methods that will allow us to do some customization for our conflict file. You can just quickly walk through this particular file and read the description off each one off them. But the purpose off this particular class is it would define all the callback methods to customize the Java based configuration for spring MBC enabled applications. So the method that we're going to be using is right here. Add interceptors. This comes with the interceptor registry object, which we're going to use to add our interceptors. In my case, I'm only going to add the very interceptor which is present. But before I add it, I had to make sure spring will dependency inject this particular object, and that will happen without a wide annotation. So when we deployed this application, the dependency would be injected by spring and again. This is also a competent which needs to be harder scanned, and that's pretty much all we have to do. If you want to add additional interceptors, just copy this statement and repeat it. Keep adding as many interceptors as you wish they all would be executed in sequence. So let's run our program and see if things are working and I'm going to run out application as a standalone jar file that's going to save a lot of effort, reload the page and type in something. Let's go back and take a look at the console, and there you have all those messages. So pre handle came into picture before the controller and right after finishing deacon Dollar logic. We have post handle and and then, after they cost is served, we have after completion as well. Now let's try to written falls here and see what's going to happen. Let me go back to the Broza and Control is not called because we were returning faults pre handle and that's it. Hope it makes sense. 22. 0303ApplyingRestrictions: in a typical application, we might have a lot of controllers, and we don't want to apply all interceptors in all the controls that ever existed in our project. That would be very inappropriate. For example, consider the following scenario. Let's say you have a banking application. You don't want to use that to log in in order to see the register page, because only if he registers, can they use the log in. Similarly, don't want to restrict the user. When the user is trying to access the home page and same is with the log in page, you don't expect their user to log in in order to log in. That does make sense. But there are certain pages in our application that only the logged in users should be able to see, for example, dashboard or account information, etcetera. In this case, we want our intercepted to come into picture only for these two cases and not for the rest of the cases. So I'm going to be using a your baton and check to see if the Ural has this text, innit? User. If it does, then I want to activate the interceptor. So let's see how it's done. We don't have a banking application to demonstrate, but we're going to use our existing application. So currently, if you enter something in click submit query, you're able to say this message. I went up a restriction on this page. Only the user is authenticated. Should he be seeing this page? Let's go back to eclipse. So currently we have our interceptor and is applicable in all the your worlds. Now let's up by the restriction. We can use one of the methods available we have add part baton, or you can even exclude apart baton. And as an argument you want to provide a string, which is basically kind of like a regular expression. You want to provide the Ural pattern that you want to active it. In my case, I'm going to say hello because I know that my application your is having the word hello. In order to view this page and then followed by any text, I'm going to save the file. And from this point on, if I run the application, go back, enter something and it should be able to see interceptors coming into picture. Let's go back and change the text of something else. And this time, if we run the application, our interceptors should not come into picture. Let's give it a try, test or whatever. And there you have it. Interceptors didn't come into picture because off the restriction that we applied letter that I want to use it to log in when they're trying to access a your that has Hello in it. I'm going to make some modifications inside our interceptor code instead of returning true , I'm going to be returning falls Now. You tell him that we had sent a database query in the user authentication failed and instead going to say response dot Get right, ah dot Right. And I'm going to send some text. Please log in. This time we are abruptly holding the process off forward in the request of the controller . Instead, we're handling it ourselves. Let's run our program and see how things will go. And I'm going to enter test. Please log in. We didn't see the controller logic taking place. Hope it makes sense. I will see you soon 23. 0304InterceptorsWithoutSpringBoot: How can let us take a look at how you can add interceptors and traditional way without using spring boot? The approach is pretty much similar. All you have to do is to introduce the interceptor class in this manner, along with required methods. Pre handle, post handle after completion. And then, just as in the case, offspring boot, you do have to register this interceptor inside your conflict file. So here we have our Web conflict file, and we defined, however, bean Interceptor example. Just interceptor class, and then you have to register it by implementing dis mattered. This matter belongs to the Web gem basic conficker interface, and once you do so you're done. You're interceptor is in place and will be activated. Let's run our application, but pray out. Running the application. Do make sure that you build the project so that you will have an artifact ready to get deployed onto the server. Let's enter something, and it worked pretty well 24. 0401MappingAnnotationsOurAPP: Let's talk about various different mapping annotations you can include as part of the controller class are controller logic. First, let's talk about the request mapping annotation. The request mapping annotation is the gender can notation, meaning that whatever the Ural pattern that you specify has an attribute is applicable for all scdp methods. So be to get request or post request. It doesn't matter. The annotation is applicable for all those cases. However, if you would like to get more specific and target only a specific actually being method, then you can have the following syntax. He's a stab to add an additional attribute, telling the matter that you want to target. So in this case, we're just targeting only the get requests and would like to map for the following your baton. However, this is all the way off declaring the sanitation in the reason abortions offspring we know have more specific annotations specific toe a Chester diplomatic. We have get mapping, which will accept only get requests. Similarly, we have post mapping, put mapping, delete mapping and patch mapping. If you're using Web browser, then only these two annotations would be relevant. Brother is not capable off sending other types off requests like Put, delete or patch. However, if you're using restaurant Web services, then definitely other matters will come into picture as well. In rest Web services get would mean that want to retrieve a resource or a database entry post would mean insert a resource put would mean you want to replace a resource. The late would mean just as the name suggests you wanted the leader Resource patch would mean you want to partial update a resource or an entry in the database. Since we're not concerned with restaurant Web services at the moment, we're only going to focus on these two annotations. In fact, we're going to take a look at a very good example by creating a very simple application and by using these annotations does not mean that we're going to neglect the request mapping annotation. In fact, the perfect design practice is to have the sanitation added at the control of class level and then get more specific with these annotations at method level. Once we take a look at how we write our example application, you'll have a better picture on the same his application that we're going to create. Imagine that you're given with the project off, creating an application we're in. When the user visits, a website they use must be able to design his or her own T shirt. So this is the home page off our application. And when we click on design, which is a link, we're going to send a get request to a controller logic where and we're going to populate some data, which will then be sent back as a mortal data to this view technology in order to render all those details. In this case, we would let the user customers a T shirt by selecting all these options, including the name that he want to give to his T shirt. And this time I have chosen time leave has a template engine just so that we can touch on all those view technologies that are popular with spring. Once the user chooses all the required customization, they use the word, then click on proceed and we're going to send a post request toe yet another matter inside the same controller. And that method logic would just simply right back the text. Basically, all the options that the user had selected in the previous page down the line. As we progress through the course, we're going to introduce some additional models inside our application one off, which is going to be a database so that we can actually store the data into the database and do some processing. But for now, this is how our application is going to look like. Once we have a project, walk through, you'll understand things in much better way. 25. 0402GetAndPostMapping: Let's take a look at Howard. Application is written. This is our applications home page. Whenever somebody visits a website, this is the first page that they come across. But this is very simple page that has one image, which is basically our company's logo and then happy subtext. And then we have one link, which, when clicked, would take the user to this custom designed page where the user can actually designed the T shirt, giving their giving it some name. So let's take a look at what's happening in the code. Our home pages written inside indexed Oreste Immel Page. And when you need the file as index that's going to be detected automatically has a home page. I mean, you don't have to introduce a controller just to handle the homepage request. It will be detected by default. And inside this file, we just simply have a very simple test email code with image text as well as one link. The link would point to this resource slash design, so we have introduced at controller toe handle that very request. So I've used the sanitation to cross mapping and provided the your baton, and in our case, this year, Old baton would map with the request when somebody clicked on this link and since by default hatched IMA links or get requests it would land. The request would line inside this method. Since it has the sanitation get mapping. We can also have and attribute a your let tribute just as in here inside the sanitation as well but there is no need for it right now. But if you want to add something like this, for example, say test, then your your has to be design slash test Only then will it land inside this control method. Let's under those changes by the in order to make our application visually appealing have also introduced the cascading style sheets. You don't have to introduce this if you're creating this application from scratch, this is just to make our application look better. I'm going to make this project available for you to download anyway so that you can experiment with it. What we're doing inside this method is pretty straightforward, since we don't have a database were explicitly populating the model data, But I really would be fetching all these details from the database and what I'm trying to do here is I'm just trying to add few attributes with key value pairs. The key is going to be the string and the value is going to be and add a list off strings, which will basically describe all the customization options so users can customise with the color of the T shirt size sleeves as well as the call a style and, uh, each one have their own responding values. We're populating these details because we want to populate all this data under you, I because that's what user is presented with. And as I mentioned before, we're going to be using timely template engine to do this job. And in addition to adding this attribute, we also created an object. Let me explain. So when the user select various different options and clicks on proceed, we need something that will hold all entered or choose and details and when he clicks proceed, will do some crossing with that data. So for that purpose, I have to introduce another class, which is a simple Poggio. It has one string attribute as a last list off strings. Basically what this means is the user will enter some name to their customization, and that name will be held by the string attributes and all the rest of the choices that the user will choose are going to be stored as a list inside this attribute. So we have to create an empty object off it and send it as an attribute so that we can use it inside our template. So let's take a look at the time with template that's going to populate this page, and here it is. The key element here is this form with the Method Post were using Post Request because we want to keep all the user enter data secure. I mean, if you use and get request, then all that he just couldn't be seen inside the request. If you're is imposed, all the enter details would be part of the request body, which is more secure. So once user, enter some data. Let's say test and I'm going to choose one color, as allows the size. And once we click proceed, we have a handler method for that inside the same control of class, but with post mapping annotation. And inside this, we're trying to receive the object that we had populated and inside this form. In order to take the user input here, we had to use some timely specific stuff. For example, we have timeless value which would map, but this the name. So we have to provide the exact same name in here as well. Just try to pause the William, try to understand what's going on in here. It would look very obvious and we're using timely forage and inside select. We're going to populate all the list off options available. I mean, what are the list were populating here? We just want to look through them and sort of populate all them has a list. And so we're using this particular attribute pH each this is equal into for each in Java and we're populating all the options available inside the color. Attribute again disposability and try to understand this would look obvious. Similarly, restaurant elements were also populated and finally we have the submit button that would ultimately send all these details in the form off request. And so our handle logic will receive it. Finally, amusing the SDP response object to sort of write back some kind of response I deliver should be doing some crossing with the details entered. But for now, since that application is pretty simple, I'm just displaying back the text. So these are all the details entered by the user. But the point don't make here is to demonstrate these annotations and also and also to demonstrate the right designed baton. I mean, you're going to use the request mapping to target one specific Ural Patton, and then you'll have list off methods handling specific history. P methods hope it makes sense. 26. 0403URIPatterns: you can use certain special characters to express your your baton. We have this question mark symbol that would match with any off the character, an example of which can be seen in here. We have this request mapping annotation with this year old baton. So this will accept all the your requests that would have the following text. And this question mark can be any character. Here are some examples off valid Urals. This would match with that baton. This would also match with that pattern because we have the exact same characters. And in place of question mark, we have some random character. But this year Orlin here is not valid. Who said org But there is no he and so this would be qualified has a valid your or your I. Similarly, you can use the symbol and that would mean zero or more characters similarly can also use double star in this manner, and it would match with anything, including the forward slashes. So when you say order slash double star slash than any your that starts with this particular set off, characters would be qualified as a valid your whereas in here it doesn't start with that. And so this is invalid. You cannot a mix and match all these three symbols and create a Patton. Something like this, and it would work as well. 27. 0404ControllerMethArgs: Okay, let's take a look at some of the arguments accepted by the controller methods. There are quite a few have actually picked them from the official documentation from spring dot I will website and here are they? I'm going to make this notes available for you to download so you can take a look at it as well and feel free to experiment with some of these annotations. And sure enough, you don't need to know everything in here. In fact, in my entire experience, off working with spring framework up never, he used majority off. These have used only a few to the most, but I would use these annotations, which will talk about incoming videos. But you can have all these arguments. For example, you can have Web request as an argument, and isn't that object you can. Actually, you can actually access some request battle meters as well as some session attributes. We've already seen how we can access request para Meters using annotations, so that's an ultimate too to accessing using this object. Similarly, God, few other objects to start off to start off, use them inside your logic. He can also access the extra dipping method through which the request is coming from. Let me just quickly demonstrate this going to copy this and I mean just simply display the math. Adi's yesterday we met that that was used look under shift. Oh, to import the class. I'm just simply going to display it in here, just as so let's relaunch our application, go to the browser and test or whatever, and there you have it similarly can use all the other arguments that you're seeing in here . For example, you can get access to the clients local. This is useful for internationalisation off your application. If the request is coming from, say, Japan, then you want to render your website in Japanese language stuff like that and get access to time zone. You could even get access to the input stream and thereby can access that it was body. And we have, ah, host off other annotations which will be exploring incoming videos. But just go through this file and sort of get some understanding on what are various arguments accepted inside the controller methods, and it will be just something off me to talk about all these methods. It would just waste your time, so just have a look and get some idea about it, and you're not restricted to only have these arguments. You can have your own custom arguments. And that's what we have done in our previous example, were able to get access to that domain object, and we could access all the details entered by the user. So that explains hope it makes sense. 28. 0405ReturnValue: Let's talk about various different written values that convey returned from the controller methods again. All these were actually picked up from the official website spring dot Ivo, We're going to talk about this annotation. Basically, what the sanitation would I love you to do is that you can actually send back the history Peabody, the response body and this region type responds entity would I love you to modify the entire extra dippy response. The best way to understand it is with an example. So let me just quickly copy this and, uh, go to our code. And what I want to do is I want to add some Mr TP response headers, and then we'll take care off, creating the entire response around with status as well as the body. So for this, I'm going to do as should it be headers. I would just simply say headers New yesterday, beheaders. And then I'm just simply going to add list off hander's with key value pairs. I would just simply say custom hadn and use some value to it. And then we're going to add this headdress part of the response. And for that we're going to be needing this object and that's what we're going to write down the matter. OK? To set the status off the extra deeply response, I would add the headers and then finally, I would add some the body as well. You can type in any text off your choice. I'm just going to say custom mori text or whatever, and the return value is going to be same response entity off types drink added control, ship those so that even this classes now right here. Well, excuse to try before that. Let me just commend this out. That's freedom. Our application that's relaunch your application. Go to the browser and some Madeira close. And there you have it. Here is the response body. If you'd like to take a look at the headers, though, you have to use one of the browser tools. And in Firefox you can use the stolen potatoes and go to network stab and then submit the request and you should be able to see all the requestion response headers. And here's the custom header that were just added, so this might come in handy at times. Although it is very rare, let me just quickly undo all those changes similarly can return. An instance office treated beheaders and, as the name suggests, that will let you return back has really beheaders with nobody. You can also written string and we've already seen an example of the same. This just means that you're sending back the name of the view. You can even send the view object itself. We've already seen an example off is in the model object. Although we don't explicitly send it, it would be sent implicitly to the view and again, we're going to talk about these attributes. Pretty soon you can also send model and do you object that would just comprise both the model data as well as the view name that you want to target, why it would mean that you're not sending anything. Instead, you want to deal the response within your own logic. And we've already seen an example of the same as well with response. Writer were able to write back some response and all these types in here the four result colorable etcetera will come in the picture when we talk about Ascend grown its requests. So you have to hold on to that point and finally can just send any other. It on value would just simply means you're ready returning a string or wide and this treated outs have you name? So that's about all the supported written types. You just have a look at this file and just have some understanding on what's going on in the written values as well as the arguments. If any off the sounds confusing, then definitely down the land, we will be covering majority off these annotations and written values. 29. 0501RequestParm,GetMapping,CookieValue: Let's take a look at few controller annotations. The reckless Param annotation would help you read The euro Barometer's are the data submitted using a form, and he it is how we would use it. We wanted to take a look at an example of the same in one or four previous videos, but distinct, as if you're curious as to how it's done. Well, haters this index for that you would make this annotation, but off the method argument. In this manner, you can see the text that is highlighted in blue. You can set few attributes for the sanitation as well. So in here were saying value as name. This would correspond to the one of the form fields, and you can also said the flag required if it is set to true and the data is not provided by the user and the request won't be processed and the user would be shown and other. You can also set the default value. If you wish intensive, the user doesn't enter anything, then you can assume a default value and finally can map the value to this matter argument so that you can now use this name inside your matter and do something with it. He also have records, Heather annotation that would basically let you read one off the coast headers going back to our example. Let me just go to the network tab and submit the request. And if you click one off these, your Children staff request headers, and this is what you can read using that annotation. So inside here, I'm trying to read Holst as villains the except language, which you can see in here. And this would come in handy, especially if you'd like to know, declines local and uses language preference. And you can do something with that inside this logic. Or if you'd like to read all the list off headers than instead of mapping with a string object, you would map it with Esther dippy headers and inside the method behavior you would just say has to do. We had to start to string value map that would generate a map off all the headers in the form of key value pairs. If you're storing cookies on the client machine and you'd like to read them, you can always do that with the sanitation, and this will come in handy, especially if you're maintaining it line session. And most often this would be used to get decision I d. And that's it. For now, we'll explore more incoming time. 30. 0502ModelAttributePart1: Okay, let's talk about moral attribute, annotation. The moment you click on this link, we send a request to this handler method inside which we're trying to populate. The model object by adding all these attributes in the form off key value pairs. And this is the exact data that gets populated inside our form so the user can choose all the options required and then click Submit. However, there is another way you can add these annotations. It's by using the model attributes annotation. Let me demonstrate to you what I mean. So instead of writing this method in this manner, I'm actually going to right another matter altogether and annotated with at the rate method attributes annotation. So I would say public wide color. What are the name that you is to give And inside here we're just simply going to return a list off string values. And so now we have to change the rhythm diet and make sure that you had the sanitation more the latter tribute. And just as you have given some name in here, which is a key, he can provide an attribute. In this case, this is going to be the key and the values. Whatever this matter would written in this case, we're trying toe return list off string values. How you can get it off this seven on relaunch the application and you would see that the data still gets populated, demean it, want ages. You can no access this mortal attribute from inside this Control a class for multiple requests. Whereas if you define your attribute by using this method, you cannot do so Let me quickly demonstrate the same as well. So from inside this method I'm going to use a mortal map object to be able to read all the model elements. And I should be able to get the more delectable that I've just added by saying get And then you would provide the key. You know, kids, it's going to be the string, said the file and re launch our application. And if you go back, re lord and click submit and you would see the model data getting populated Really, contacts is one of these attributes that are deciding in this matter. Obviously God, no. And the way this works is the moment you send the request to this particular you are. Then spring will scan all the methods that are annotated with mortal attribute, and it would create a temporary map with all the key value pairs. So let's say that you have 10 different moral attribute methods, and Springwood scan through all of them and create a temporary map with all the key value pairs. And only after doing so, we'll go ahead and call. The handler mattered one thing, which is also what mentioning is the methods that are annotated with morel attribute well except all the perimeters, that other hand lament that would accept. So whatever the arguments that you can send to this method can also be sent for for this method, which off course also means that you can do whatever you want with those objects. 31. 0503ModelAttributePart2: another advantage off model attribute is that it will help you map all the form details with the command object going back to our application. Once the user fills this farm and clicks on proceed were able to carry all those details into the command object. And so we're able to display them. Has a text in this page. If you take a look at the form, we have this object which is a command object, and all these fields are actually mapped to the fields in here. The text field is mapped to this field. Indistinct options which were chosen are mapped to use a choice. But if you notice once the uses of Mr Phone, we didn't really take care of converting the request perimeters and mapped them with the fields in this command object. It's all they can get automatically. Well, that was possible because off the sanitation model attribute on the wouldn't explicitly mention the annotation in here it is implicitly assumed, like so. We thought this feature we would have to manually read all the perimeters and then sort off map all those elements with the fields in this command object. So this generation definitely says. There's a lot of her fort. Sometimes you may not want to bind the form with the common object. In that case, you can use the following attributes for the sanitation. Finding equals force by default. This is true, my specifying So you're telling spring that you don't want to bind with the form instantly want to read this object from the mortal itself? So you may have another mattered something off this sort, and then the written type is going to be whatever you want and he would get done and new custom. T something of this sort. Let me just quickly populate some details of that. We can show some data, and I would say CD dark, set, name, best name and then finally done said the file. And let's relaunch our application. Reload the page and it doesn't matter what you enter. Since we disabled the binding, we have the object picked up from the model. And in case, if you don't have this model attribute in here, then then spring is actually going to create a brand new instance off this by itself that's real on your application, and this time you just don't see any data at all. Hope it makes sense 32. 0504SessionAttributes: All these model attributes are request scoped and are not accessible from another controller. If you want to be able to access these moral attributes from another controller, you have to make them bart off this session scope. And for that very purpose, we have the sanitation session attributes and then you would provide the attribute that you want to add into the session. I've already talked about history possessions in one off my previous courses. If you're not aware, off sessions go Panda Chris Cope, then it might be what want to export about it a little bit. But once you have this added as part off this session scope, you can no access this morel attribute from another controller using the sanitation session attribute. And in order to demonstrate this, I've actually created another controller what you're seeing right now but the following mapping. So before I send request to this controller, I have to make sure that I send request to this control because only then will these model attributes be added into this session. So let's go back and reload this page that would populate the map as well as it would make all that to be a part of the session. And now if I goto shop, it would show has that object, which is exactly what provided in here. I hope it makes sense. House, they assume. 33. 0505FwdRedirectFlashAttributes: okay, We have a farm which after we fill and click on submit, we're just displaying back whatever has been entered behind the scenes, we have a controller that is receiving the request and then using the response writer, we're just trying to write back whatever is entered in the form. Well, in most cases, the scenario may not be so simple. You might want to perform something complex if you wanted to use that data to send a query to the database and then render back some kind of a response, in which case it may not be a good idea to have this logic reciting in the same controller . Instead, we want to forward that request to yet on the controller, which will take care of rendering some kind off response. So let's take a look at how we can forward the request to another resource. So here is the method which will be triggered right after we submit the form and inside here we're using the forward attribute, and we are, and we're pointing to yet another resource. So for this purpose have actually created yet another controller with that exact request mapping and with the post mapping annotated method. And inside this matter, we're just simply using the response writer to display back some kind of message. And do take a note that whatever all the model attributes that are accessible in this particular controller can also be accessed with this controller, because what we're doing here is a forward off the same exact request. If you want to get into internals and take a look at the cord, this is how it's going to look like. We have both accustomed response objects, which will be provided by the container, and we're going to forward both those objects to a particular resource. In our case, it is this. Even if you go back to our application, you would notice that the Ural didn't change. Let me go back, reload the page. It's the same design page, and then it would be the same. Your you know, after submitting the form that's because we don't have any new request. Is exact same request that got forwarded from one controller to the other. And for that very reason, we can also access the model attributes and some ableto read all the form details which this object is holding However, one down tear off this approach is that every time you do a refresh off this page, it's actually going to send. It's actually going to resubmit the form every single time. And so we're able to see the same message again again, and that message is being displayed with the statement. So every time you reload this page, what kind of resubmitting the same form again and again, which doesn't sound efficient In order to solve this problem, we're going to use at redirect, so instead offer forward. I'm going to say redirect and that we were essentially going to create yet another get request and redirect to another your which was pacified in here. In this case, since it's going to trigger a get request, the post mapping may not work. We have to have to get mapping method to handle the get request. Well, this has certainly saw the problem created by forward, but this comes with a side effect. Since we created yet another request, all those moral attributes that were accessible in the previous controller would no longer be available in this controller. We have to incorporate some kind of a mechanism to start off carried the moral attributes to this controller. For that, we have to use the redirect attributes and using this reader attribute we can have so called a flash attribute, which will be accessed after the redirect inside this controller. Once you had the flash attribute. It's as good as all those moral attributes are available in this controller. And just as the name suggests all these attributes, we'll stay in doctor in a flash map only until the time redirect happens. After re that happens, the map would be cleared. So let's relaunch your application and see how things are working. I go back, miss amid the form, and this time, if you notice the euro isn't same anymore, we're pointing the different resource altogether. That's because we're just creating yet another get request. Along with that, you're also seeing the session I d. The reason is the flash attributes that were just added internally uses a session to store all these attributes Well, in other words, flash attributes are Samos session attributes, but the stay alive only during the time reader it happens. And unlike the forward attribute, the way the reader attacked a bit works is as follows. We're not forwarding the request and response objects. We just simply performing redirect to a different resource. I hope it makes sense. 34. 0601ExceptionHandling: Whenever you try to access a server resource with a suitable request, the request would land in dispatches. So that and then the dispatch Issel that will take care of delegating that call to the desired controller. But what if the controller is not found by the dispatch of sold it well, so what would just respond back with 404 not for ever with this default page, this default page is not so user friendly as in India, So you want to say something more meaningful and visually appealing. If we wanted to show a message saying that the requested your does not exist or whatever and then put a link to the home page. So let's see how it's done. I'm going to show you how it's done without using spring boot, and then we'll take a look at how we can do the same with Spring Boat. First and foremost thing is to design the page that you want to render and gets off for forever. And here's a page I'm talking about in order to keep things simple. I'm just displaying this message, but we can introduce all the CSS and other styling aspect into your page and make it look more appealing. And I also named the speech as photo forever. You can give any name off a choice, and since I'm going to correspond this page with photo for better, I just named it so. The second thing that you need to do is to manually enable the exception, my default dispatches, all that will not throw did this was not found exception. We have to enable it manually in this manner by setting this flag set through exception. If no handler found too true, so that the dispatches all that we'll throw this exception in case it does not find any handle logic or the controller logic. And once you enable it, we have to know take care off, creating a class or method that would be called in case often exception. And that method would be annotated with exception handler with the exception itself. So whenever we have this exception, then this method would be more and in here were just simply returning a string, which is essentially the view name that we want to render in case off this exception. Well, we could have this matter as part of the controller class itself, but it would be applicable. Only written that controller in order for this method to be applicable across all the controllers that are existing in our project, we have to have this method inside a class that is annotated with controller Ed wise. And when you have the sanitation, this class would be identified as a spring bean with competent scan. Or you can even manually declare this as it being inside your conflict file any which ways this is all there is to it. So now if you try to access the resource that is not present, then this exception would be raised by the dispatch of solar. Enter this method logic would be executed, which would ultimately render how jsp page you can actually add list off exceptions inside a car. Libraries, for example, say that I won't execute this mattered whenever there is a handler, not phone exception as well as a null point exception. Say the fine and no. Whenever you have an ALP under exception, the same behavior would take place. And in order to make sure that we get another point exception, let's go inside our controller logic and then do something here that would explicitly throw in a blunder exception, I'm going to say if true, and then throw no point exception. Of course, we need to throw an object. All right, let's say the file build our project and then on the application, let me pause the video, do all those stuff and get back just to save some off your time. So here we are again, have old it on the application. Let me type in something and click Submit button district, throw an Al Ponte exception, and so we're able to see Theater Page. Of course, this is not a 44 patter, but I hope you got my point. And no, this tried to access a resource that is not present and again en garde. The exception. Hence we're seeing this page. This is more user friendly. Also, if you wish you can get more specific on which are all classes, it won't apply this method on. That's by sending para meters to the sanitation, and he knows the various ways you can do so you can have Controller Edwards annotation with the following Param Eter and this were targeting all the classes that are annotated with rest controller. The sanitation, by the way, comes into picture for rest ful FBI Similarly conspiracy If I a specific class and now you can target all the classes that are reciting inside the package Wherever this class is reciting, similarly can also target a package so that all the methods would be applicable in all the classes residing in this package. In our case, we left it to default so that it is applicable for all the controllers. I hope it makes sense cells easily. 35. 0602ExceptionHandlingInSpringBoot: Okay, let's take a look at how we can handle exceptions in case offspring boot. We pretty much have the same code we have. The exact same controller has the last the controller advice class, with the exception handler mattered. Everything is similar to our previous example, but the difference is in our previous approach, we had to set this flag off dispatcher so lead to true in order to throw this exception. But in case Offspring boot wouldn't introduce a class like this or we don't have any rebel or xml file. When we're declaring the dispatcher sold it, how are we going to set this flag in case offspring booed? Well, the answer is application don't properties, and it's going to recite inside the resources folder, and it would be identified by spring framework automatically. But it has to be with the same name application, not properties, and this would be auto generated if you've created your project using spring to suit, otherwise you have to manually create a file with the exact same name. And remember, it has to go inside the resources folder, and here is where I'm actually providing are setting that flag throw exception if no handler found to true. Along with that, we also need to set this flag toe falls, which means we're deserving the default resource handling. And that's pretty much all you have to do. But let's talk a little bit about this file applications or properties. If you do a quick Google search on application or properties in spring, you would come across with the link that points to Doc's not spring that I will. And here you can see all the default values that would go inside that file by default. And if you want, All right, any off this properties, he can do so, and that's exactly what we have done. For example, if you change, the default has to report to something else. You just have to copy this property and thought off, Override it right here. Likewise, being providers a host off such defaults, and you would find conflagrations for pretty much all that acknowledges supported by spring boot. You can even write your own properties and then read them in your application. We're going to talk about all that stuff when we talk about externalized configurations, so we need to hold. Until that point but currently for our purpose. These are the couple of properties that we're concerned with. Let's save the file and run our application. And if you notice what has not changed to 80 81 let's go to our application and try toe reload. Oh, sorry. That's supposed to be anyone. Let's enter something here and some of the dreary, but we didn't see that page populated. Let's take a look at the gold and make sure everything is okay. Let's go back to our controller logic and we seem to be throwing a wrong exception is supposed to be Null Pointer exception that save it and read on the program. That's reload the page and you see it working. Now. Let's try to access a resource that is not present and you would say the same bitch getting populated. I hope it makes sense. I'll see you soon 36. 0701SpringJDBCIntro: Let's talk about Spring Jedi BC But before that, let us try to understand some of the problems faced by dollar per if they were to use Jerry BC without spring. It is a very simple scenario. 1,000,000. We're trying to find an insert Quito the database using very busy and then get back some results. Even for such simple scenario, you have to introduce a lot off other boilerplate code that will support you. To run this query, for example, you have to specify the your That's where the database server would be running along with its port number. And they also need to specify the name of the database using them and password to access the database. And then you have to create that connection object, using the driver manager, passing all those para meters, and only after doing all that you would ride the cord to fire the inside query. And once after you do that, you do have to take care off handling any possible exceptions and then finally have to take care off, closing all the connections, our resources inside the finally block, and if you want to introduce transactions, you have to use the transaction object to begin the transaction and then finally coming the transaction, etcetera. The problem here is, although you're focused on fighting a query, you're forced to introduce all the other piece off code that will support you to run this query. Well, well, these are the exact problems that spring Jerry busy eliminates Spring introduces so called a jerry busy template, which is essentially a class file that will take care off all the problems that I just mentioned and would let you focus only on the things that matter is to fight acquitted to the database. Let's take a look at an example, and then you'll understand better. 37. 0702SpringJDBCWithoutSprinBoot: So let's take a look at a simple example offspring Jerry B. C. So that you'll get a better picture on the problem that it is trying to solve. Possible. Let us take a look at an example without using spring boot, and then we'll move on and do the same thing using spring boot. And since we're not using spring boot, we have to add the dependencies on our own. Here are the dependence is that any spring embassy project should be having. In addition to that, we're going to add a few more dependence is to interact with the data bases in jail. ABC The first off, which is optional, incur severe using transactions in your project. Then you would be needing these two dependencies. And of course, our example is pretty simple. We may not be needing transactions, but just for demonstration sake, I'm going to be using transactions inside our logic. Hence our been eating these dependencies. The next stop, which is the most obvious fund. You would need the spring very busy library and depending on the database that you're using unit to had its specific driver dependencies. In my case, I'm using post area school database. And so I wanted to have this dependency. This is a jet visit. Driver Pop was great skill, and here is the console off was were skill accordingly. Must be having your own database, and you should be able to log into the database and run some commands. So do make sure that your database is working before you run the project. Next, let's go toe the controller and take a look at the larger Connect here. I'm trying to dependents Inject something. Student depository. Let's take a look at it. Here's a class student depositary. This is essentially like a date access object in a typical J two EE application and in spring applications for such objects, we would annotate it with had direct repository so that it can be found by spring with competent scan. And inside here we just have one method find, all with which would be able to fetch all the students that are available in the database. So basically what I'm going to do is we have a database called School DB inside which we have a table with the name students with list off students. Well, our databases not populated yet We have a script that would populate the database once we're on our application. So it is Ah, SQL statement with which I can fetch all the students. But here's something really cool jelly busy template, which I'm trying toe dependence. Inject. Let's take a look at the Web conflict file and see what's happening in there. So we have the data visit template defined in here, and it is taken one argument, which is the data source. And here is where I'm populating the date. A sore subject with all the connection para meters specific to the database that you're using. In my case, I'm using Post Grad school until all the connection batter meters are specific to my database. Well, you don't see them Action battle matters in here because I'm fetching them from the external conflagration application or properties which recites in the Resources folder. And here are the connection para meters. You must be having similar perimeters no matter what database you're using, but do make sure that you point to the correct database. Correct. I p address. We're about your databases running and the port number in which your software is running. Here's a name and password off the database and the driver class name specific to your database. I'm trying to fetch all these details using these keys inside our Web conflict file. So we're using this and Roman Variable, which is auto wired so that we can fetch all those properties. And once we populate all the connection perimeters, Hamilton is in this class provided by spring framework results database populate. Er, here's in which I'm trying to execute a script inside my database and here is a script with the daughter school extension, and this is going to go inside the Resources folder as well. And all I'm trying to do is I'm trying to first drop the table just in case if it is already present and then I'm trying to create the student table. It would have these four fields Heidi, name of the student age of the student and some description about the student and here, a couple off interested on trying to insert. And finally, isn't this matter? Execute off database, populate er metals. I'm telling spring to execute the script inside the database and returning the data source , which will be fed to the data best template Let's go back. So once you have this object, we can call the smart that query. We have a lot of other methods which will be exporting incoming videos, and this meant that takes a couple off arguments. The first off, which is SQL in the form of string and second is a class that implements row mapper. What this allows us to do is to map all the first data to a list off student so that we can display them. And since I'm going to need this pro mapper only within this class, I'm using the No Class to do that job for me. Here's a class a temperamental mapper and this interface has only one method. My pro. That takes a couple off arguments. The first off, which is a result set which is fetched from the database and the second argument is the current rule number. And here we have said all statements that would map each of the elements in the results set with that did evil object which I've created specifically for this purpose. So we have a student class with the exact same feels with the gators and centres, including the to stream method so that when we try to display these objects, we can see something meaningful. And finally, we're going to written back the list off students, which will be received inside the controller. And I'm trying to display here as a last on the browser with the response writer. That's from our application and see how things are going. Of course, it's always a good idea to clean the server, do a mean clean off the project so that all the old artifacts would be wiped out and then finally run has do. Make sure that you do may have an update, though once after you add the dependence is have already done that. So I'm not doing it again. But you should and then install Let's from our application. Well, this form is it element. All we want is to send a request with this mapping, and sure enough, we're getting the results. I'm going to make this project available for you to download. You can take a look at it are you can experiment with it. Next. We're going to take a look at how we can do the same isn't spring boot and then we'll talk about a list of problems that spring. Jarvis's hold 38. 0703SpringJDBCwithSpringBoot: Let's take a look at how we can use Spring Jedi BC using spring boot. Since you're using spring Boat, you don't have to introduce a holy stop. Dependence is. All you have to do is to add one single dependency, and this will download all the dependent jar files. Transitive Lee. This includes everything that you would need to interact with the database using Jade, ABC Along with that, you don't even have to install any additional database software's. He can use one off the available Lember data basis. In my case, I'm using extra database, which is pretty lightweight. But if you wish, you can use other M better databases. There is embedded washing off all the popular databases out there. He can use one of them and accordingly ad its corresponding dependence in this manner. Our control logic is pretty much similar to the one that we're taking a look at. In the previous example, we have Hello mapping that would they'll get a call to the student repository in this manner and internally Berries in Jeddah. Basic template. Not pretty to fight acquitted of the database, and we use the sanitation transactional so that everything that is happening inside this map that would be part off a transaction. If you want to ride very basic or on your own without using spring, you have to do transaction got begin transaction that come it and all such kind of stuff. But spring. Very busy. It will be taken care with an annotation and with spring boot. You don't even have to define any data source or anything of that sort. Since your added this dependency in your jar file in your palm dot XML, spring will make a fair assumption on the data source that you would be needing in your project and it would created on the fly. And so wherever two dependents inject the gel, it is a template which we can use. And since spring is that there that you're using History Database Spring is also going to create the connection battle meters on its own if you want. All right, though you can do that inside the application to our properties file, which reciting the result is folder. Along with that, there are a couple of ask your files with the name Schemer or SQL and data or a school inside the schema or SQL file, you would have the video that would define the scheme off the table. And in here I'm just trying to drop the table students and create the table students in the data or SQL file. I'm just trying to insert a couple off entries into the database and into that table. And in order to tell spring that we want to use embedded database, not an external data base, you have to add the following key value pair inside the application or properties. This will tell the spring to use the embedded extra database. So by using spring boot, we have said a lot off. A fort involved in finding the dependence is heading it into the palm file and creating the Web conflict file like we did in our previous example. We don't have to. We don't have to specify the application or properties that would be picked up automatically as long as you keep it inside the Resources folder. You don't have to even create all these beans. You don't have to create the data source. How did the best populate er our jilib is a template? It would all be taken care by spring if they're using spring boot. Based on the dependence is that you add inside the palm that XML file and in addition to that spring Gereb is it has sold us a different set off problems. For example, we no longer have to pay attention to all this boilerplate code that we have to do without using Spring Jetta BC. We don't even have to handle the exceptions because internally Spring will convert all this checked exceptions to run time exceptions, so you don't have to handle exceptions on your own. You don't even have to take care off opening in frozen the resources like you're doing in the finally block. It will be taken care by spring framework so that there will be no scope that you forgot to close the unused resources. So instead of writing all this cord, you're just focused on what you need to do as a developer, which is to fight equity to the database. And that's what we're trying to do here. That's the beauty offspring boot and spring Jerry busy. Let's run our project and see if things are working. I would say hello and it did. I'm going to make this two projects available for you to download so that you can compare both off them an experiment. I hope it makes sense. 39. 0704ExternalDatabase: in case if you'd like to use any external database, not one off the embittered databases available, then you have to add it specific driver dependency inside the palm dot xml file. In my case, I'm trying to connect supposedly a skill database that is install elsewhere and so have Dad . It's specific. Driver dependence is as follows. And once you do that, you have to change your schema both video as well as the M L to make it work with the database off your choice. So I've changed his statements a bit to make them compatible with was re SQL database. And after that you have to add all the connection batter meters inside the application dot properties file just as you see in here. In addition to that, you have to manually enable the data initialization so that these files would be executed in the database and that is possible with this perimeters. Well, you can take a look at the default para meters inside the application that properties file and sort of get a sense off what each one of them do. You can actually hold your mouse on one of these properties and take a look at the description and get a sense off. What the purposes Down the line ones who introduced J. P. A and Hibernate. We would be using some of these anyway. But that's about how you can access external database. I can just run the program and see it working. You can also customize the data source if you wish. Well, with spring boot, we didn't get to configure The data source is taken care by spring itself, but in kids, if you want to customize it, then you can introduce the Java Contact File and configure the data source in there, just as you would do with any other spring project. Hope it makes sense. 40. 0705PreparedStatement: in this video, we're going to take a look at how we can use prepared statements. Use injectables, a template were able to fire. Our SQL query is in the creative method. The equipment that is apt for writing static quit. It's like this, So let's start from students. However, if you'd like to write a dynamic equity like for examples, let's start from students where student ID equals 10. The numerical 10 in here is not consistent. Become hard coded as part of the string. This will be received as a matter argument, which we would then need to happen. This to this query. Well, we can just go on Captain it for dickweed a string as well as the argument in this manner and used the method query to fight acquitted through the database. But this is not all that great in dumps off performance, because if you're fighting the squeegee, it's 100 times. It has to become filed 100 times by the quit engine, which is not so performance efficient. However, if you use prepared statement, the statement would become piled only once, no matter how many times you would fire this query so that way it will improve the performance. Let's take a look at the example of prepared statement. So for this purpose inside our controller, I'm populating the student object and then I'm passing it as an argument to this matter entered student off student depository Here we have that method. It has one query string which is trying to perform, means that operation and we also have for placeholders which will be replaced with the prepared statement. So this time I'm not using the query method Instagram using the execute method off Gereb is a template it accepts couple of perimeters, the first of which is a quickie. The second is the prepared statement called back and in here I'm just all writing are providing behavior to the only matter that is present in this interface which is due in prepared statement I'm using anonymous in her class to be ableto alright. This mattered so that I don't have to create another file and ah provide implementation. And inside this method, I'm just trying to sort off replace all this placeholders in the sequence one would correspond to the first place holder to would correspond to a second so on and so forth and all these spills would correspond to the fields in the database table students. So we have student I d name, age and description. And then finally, I'm calling this method off prepared statement execute to fire that quickly into the database. So let's run our application and see how it goes. So this should not only add the insert that I'm trying to perform from this SQL file, but also we should be able to see this particular record. Let's go to the browser and hit it. ISS All the the courts are populated as expected. Do make sure that you don't reload the page once again. That would cause another because off the primary key violation. Because we're trying to add the same entry once again, just read on the application once again that would delete the table and created once again so you shouldn't have any problems. This is just for testing purposes, but ideally, we don't follow these practices. Once a build a real world project, we're going to be performing host off operations on the database, and we follow best practices and design patents for now. This is how it's going to be another way, you can deal with this prepared statement, which is much easier. And this is not as complex. Has previous one. This looks pretty simple. And here is a statement I'm doing. Jeb is a template dot update passing the exact same quickie in certain the students with placeholders, and then I'm just adding all the list off arguments. It would correspond to each one off these placeholders in the same sequence. Internally, this is what is going to happen. This is just a shorter washing up doing the same job that's from the application. It work in a similar fashion. You would perform the leading upgrade operations. So you have a delayed query within placeholder with this method update a passing couple of para meters, which are the query itself and the value that you would like to pass to this place holder. And this would typically be the matter argument. Same is the case with update. You're populating all these placeholders that bunch off values hope it makes sense 41. 0801 Hibernate: 42. 0802IntroAndTerminologies: in this video will try to get some quick understanding on have Been it framework and a few other terminologies that you should be aware off before we dive into our first example. First, let's try to understand the term framework you can think off framework as an enrollment are set off libraries that together will help you address a particular set off related problems . I mean, think about any framework out there We have logged for the framework to a does a problem off logging, thereby will be able to trace the application errors efficiently by taking a look at all the log messages. And we have maybe in which acts like a framework or as an enrollment on which we can run our made in plug ins, and this plug INS will actually perform the project. Management tasks similarly, have been. It is also a framework and is there to address a particular set off related problems. And those problems are obviously associated with database. We're going to take a look at the difference between dealing with the database in traditional approach, where since I been eight and then you'll see the difference obviously have been, it is going to be a better option will see wine in a while. And here are some of the advantages by using the framework, and these are quite obvious. Print books would save a lot off project development time because you don't have to write all on your own what a framework is already doing. Insurrection. Just download the framework and use those libraries that would save a lot of typing, and it will also increase the aural productivity off the project. We just quite obvious, and framework will help you write clean code. You can accomplish the same task with less a number of lines off God, and at the same time you're court looks more readable, etcetera, and then we have autumn or object relational mapping tools. These tools help you map the Java objects with demolition database tables. I mean, if you take a look at a job object, you have an object called Student within which we have all these properties. I did name an email we consort off Magda seem with the relation that the best table we have , student table and its attributes. I d name an email. So this is a kind of problem that these autumn tools are going to solve. And here are some of the examples off or them tools. One is have been it, which this course is about. A clip link is another example of the same. If you take a look at how we deal with database using J BBC, we start off, create our database specific query, and then isn't the execute query off the statement. Object will be able to get back, the results said. And then we have to manually take care off, looping through all the results and assigning those results into an object like student. And then we're also adding each off the student object into the students list. Well, all this can be done automatically when you use an autumn to like hibernate. So that's going to save a lot off time and the host off of the benefit and what? The real reason why we want toe use an Orem tool is it would help you get it off some of the discrepancies associated with we trying to map the Java objects with relation database tables, for example, not all data types that are supported in Java or supported in database so tools like Cabinet are actually going to solve the problem, and it would enable the developers to interact with the Java objects while happen. It is actually taken care off mapping those objects with the relational database tables and is going to perform all the database operations. So these autumn tools are going to provide that kind of an abstraction for dollar purse so that they more or less interact with the Java objects, but not with the database. Java persistence API is simply a specification whose implementation is actually provided by these Orem tools, and having it is one off them. So at let up one of time. If you try to switch to a different all the NATO or a different or um, tool, then you have the flexibility because all these frameworks will actually implement the same specifications, which is Java persistence. FBI specification. And here's a Cabinet definition, and you'll be able to understand on your own having it is simply an open source or I'm tool from Red Hat. And that is basically a framework that provides implementation for Java. Persistence, FBI and the major role off hibernate is to map the relational database tables with the job objects. Here is the high level architecture off. Dealing with the database isn't a traditional approach. I mean, isn't very busy. So we have our job application inside which we're going to use the jetty busy FBI to start off, interact with the multiple data basis by using the driver manager. And these drivers that are specific to database will actually implement all these AP ah specifications so that we can interact with the database coming toe have innate having it is actually going to take care off all that headache, and we actually interact with the Cabinet framework and then have been it. Framework will deal with all these technologies like Jdb Siege our database connectivity, and J. And I were going to talk about J N D. I Jabba naming and directory interface when we talk about the connection pulling etcetera and it would also use the Java transaction. FBI to perform the transactions were going to take a look at examples off transactions as well. So this is the high level architecture off hibernate now. This is not the exclusive architecture. There are few of the components that are in mold in this architecture, but I'm not going to present them right now. For obvious reasons, you're not yet ever off. Some of the concepts involved in have been it. But I will definitely revisit the Harbin IT architecture and would let you know the other components that are involved in this architecture. So for the time being, this is This is what happened in architecture would look like at a very high level. All right, let's continue from next video. 43. 0803JDBCvsHib: Here are some of the differences between J. BBC versus Happen it and you'll see why have been it is a better alternative combat to jail . BBC One is off course, the object mapping, which we've already talked about with Jerry busy, we have to do it manually and with have been it, it will do the same for us. One of the primary strengths off happen. It is it offer so called I have iniquity language. Now. If you worked with database for a bit, then you probably know that the syntax off SQL statements vary a little bit, depending on the database that you deal with, if you learn, have been it query language. No matter which did the best you're using, the statements are going to remain same so that it would be easier to switch to alternate data basis without having to change or without having to introduce a lot of changes in your code. Using Jerry BC, you sort of have to enter the database specific queries, but with Cabinet EQ and just simply use hedge fuel that would remain common for all the databases because because happen, it is actually going to take care off converting this into the database specific SQL statement. And added to that, as I've already mentioned with have been it, you're actually interact with the Java objects. So in here, in the statement with which we're trying to delete an entry from student, this student in here is actually the name of the class, not the name of the table reciting the relational database. So that's the kind of beauty that happen. It offers for developers. And all the Java developers would actually feel more comfortable interacting with the job object rather than the relation database table. And as a by product, we have the falling advantages. With this approach, we can actually get into the notion off polymorphism inheritance, etcetera and have been It will take care off mapping all these notions with the relation database. We're going to take a look at an example. We have videos dedicated to talk on all these. You'll have to wait until then and the statements that you write in happen it or not case since two, for example, hammocks off upper case and lower case in here, but still it is valid. But of course, case sensitivity is applicable when you're defining your class name. This is something that revolve that you talked about isn't HBO? You don't have to worry too much about switching to alternators. One of the major advantages off use inhabited framework is its ability to handle the exceptions. I mean to go back here with very busy approach. We have to rob the code and on the try catch block, and then we have to cast the exceptions. That's because these are checked exceptions, and and we developers have to take care off dealing with those exceptions. But whereas with hibernate happen, it is actually going to convert those checked exceptions into unchecked exceptions so that we developers don't have to deal with it. So that's going to save a lot off typing, improve the readability of the code, etcetera. And having it is actually going to incorporate certain mechanisms, like cashing mechanism to improve the performance, thereby it will try its best to keep the database requests at minimal level possible. Also, there was some kind off a database connection, which was all that existing from previous initialization then have been It will try to use that connection instead of creating a brand new connection again and again. So aspects like these would help us improve the overall performance off the application and have been, It allows us to write annotations. These are basically GP annotations, and the advantages associated with annotations are quite obvious. You can get it off all the XML configuration files. It's also like your writing court in more natural passion. Get it off lot off mess by using annotations. And finally, one of the greatest strengths off have been eight is that it's ability is that its ability to adopt is, is that its ability to adopt a new changes introduced in the database. For example, with Jerry BC If you're trying to add a new column in the database, then you have to go and change the court in here, for instance, in here we have toe add another statement to deal with that column, and even in the cord, that helps in adding an entry into the database. We have to introduce another statement to deal with that new column. Oro. It is we developers who have to take care off those new changes, but whereas with happen it happened, it will help us get it off all that burden and it is going to do the job for us. Now we have a host of other benefits off hibernate. Worse is dealing with the database in traditional approach. But I'm not going to list them because because you're not yet aware off some of the habitants concepts, and they would not make a lot of sense. Well, we're going to talk about all those concepts in detail. Sell state June for that. And of course, we can get it off some of these problems with Jerry BC, as well by introducing new class files, etcetera. But it would be as good as introducing a brand new framework all on your own. So that's Ah terrible West off time. Instead, it would be a wise choice to use a well matured framework like cabinet that is specifically tuned to solve your problems. All right, I think this is a good start. Stay tuned 44. 0804ThingsYouNeed: in this video, we're going to take a look at some of the things that you would need before we start working with Have been it, the first of which is Jessica or Java Development Kit. If you're able to write Java programs and run them comfortably, then that means you, although they have this installed in your computer. What you need to make sure, though, is that you have the latest one installed, and I believe since your enthusiastic about learning have been it, I assume that you know how to install J decay or upgrade to latest wash in. Then, once you have the set, make sure that you have a database management system software installed in your computer. I'm going to be using posed re SQL software. It is one of the most popular databases used along with job applications, and if you want to fall along with me, you can install the same database, or if you're comfortable with any other data base, you can use them as well. In this course, we're not really focused on database specific concept. Rather, we would interact with hibernate and having it is actually going to take care of interacting with the database. And that's the beauty of Harbin. It we developers don't have to interact with the database, but we would rather interact with hibernate and have been it will do the job for us. So for this course, it doesn't matter what database you use, but you need to make sure that you have some evidence off how database works. Some of the basic SQL queries, you know, joins etcetera. That would be a great value add, and also you need to be aware off. Some of the basic queries, like creating a database, are using the connection parameters to connect to the database etcetera, because these are the stuff that we're going to differ from Dera Bester database. So we just need to know those basics like connection battle meters, being able to create a database, using a command land or some kind of an administrator tool that is specific to your database, etcetera. And that puts suffice. And the next thing that I want to make sure is that you have an I D set up integrated development enrollment, something like a clips on that beans. Now, if you've been working with real World Java projects, then you probably know how to use Eclipse. And if you're not very familiar with the clips and you know how to use net beans or any other I D, then I would recommend you to switch to reckless because it is the most popular idea out there. And it has a lot of features that no other idea can support. If not, no, at least at little point of time, you'll be forced to switch to eclipse I d. Because it's a wonderful tool. And let me tell you, no matter what idea that to use, they also the same purpose off easing your development process. So even if you're using an idea like Net beans, it should be a very easy switch for you to download and install Eclipse and start using it . And this is the tool that I'm going to use throughout this course. So if you want to fall along, install eclipse. It's pretty easy. And once you install it just to make sure everything is working, okay, just create a sample Java project with the sample hello world application and then try to run it, make sure it is working, and finally you would need the habit framework and the list off other related libraries. It's a lot of pain, too manually. Don't let all these libraries and and set up the enrollment. So what I'm going to do is I'm going to use a project management tool like Maven. Maven is the most project management tool out there to help you manage the dependencies, etcetera. This will make our job a lot easier. If you're not ever off maven, you can still fall along and even work with the examples that I'm going to walk it through . Or, alternatively, I have a great course on the same. Just drop me a message and I'll see if I can give you access to that course. And similarly, I have a course on post three sq as well. It's a wonderful course, and that course, not only talks about was great skill specifically, but also it talks about PG admin, SQL in general and Jerry BC, along with the mini project, which is basically a crowd application. If you need access to that course, drop me a message. Let me see what we can do. All right. Once you have everything in place, I'm going to demonstrate the last step, though. But just make sure that you have all these three set up and installed and make sure they are working. All right, See you soon. 45. 0805FirstHibAppPart1: hold it. Let's get started with our first Cabinet example. And for this purpose, as I've already mentioned, we're going to be using living as a project management tool. And so I'm going to create the project using the same. If you don't know maven, then just try to imitate exactly what I'm doing. Click on file New and then Maven Project Click Next in my Melvin course. I've explained everything about all this prompts someone to click next. I'm currently isn't the default archetype, which is made an archetype quick start here. We can give any coordinates off or choice, but I would recommend you to give the same coordinates that I'm about to give. That's because actually have ready made files that I'm going to add into our project. And these files are actually tuned according to the naming conventions that I follow here. So in here, I'm going to say, calm dot company, an artifact that is going to be hetch be hyphen project or project despair. AJ, you can give any name off your choice. You have to take care off, making those changes in your palm that XML file. If you don't want to take that burden, Just you. Exact same name, click finish. So this is going to take a while. And while it does, I'm actually going to walk it through. List off steps involved to write off first have been eight application. You can open this file with the name first broke Step start dogs within which I mentioned all these steps that will help you write your first cabinet application. So the first step in it is off course here to have a database set up, which are the data visitor using you need to have at least one database created in my case . I'm using post area skill and its default database, which is post Greece. So let me just log into the bulls, graze shell, and I'm going to enter all the para meters like the server database port number. No matter which database you use, it must be having some kind off a command crossing tool like this. And you're supposed to log in and enter your database. So I'm going to enter the user name and passport for the database with the name pose grease , which is the default database in Bosnia. Skill. So have long been successfully now I can actually go ahead and create a table. However, I would like to leave that job toe happen it so I'm not going to manually create a table. The second step is to create so called a persistent class or sometimes termed as an entity class. This is the class whose instances would get stored in the database by Harbin. It remember this diagram that we had talked in one of four previous examples. So here we have a job object with certain values assigned to these fields and having it is actually going to take care off storing all these values in its corresponding table in the relational database, this particular object must have bean an instance off the so called a persistent class. So how do you term a class as a persistent class is when that class follows all these rules Now, these are not hardened fast rules. You can break these rules if you wish. If you think it makes sense to do so. But these are the standard rules off a Poggio are plain old java object, so it must not have any public fields. All the fields must be private and all the fields would have, public getters are centers, and that class would have one default constructor, and that particular class should not extend any other class. That has some fancy methods, and that's actually quite obvious. We want to keep things simple, just plain old Java objects, and the class must not extend our implement. Any specialized classes are interfaces that has fans and methods with some pansy logic and optionally. That particular class can be see realizable. It's highly recommended that you make it see realizable because more often in distributed applications, this frameworks would actually use the mechanism off civilization to convert the objects into byte stream, store them in memory and then returned back as objects. It has a very significant role, especially in distributed applications, and it's highly recommended that you implement see realizable interface for your class. So let's try to execute this particular step. I have got everything ready for you. Go to the list off downloaded files from this course, and you must be able to locate this particular fold of the name first hibernate example inside which you can look at all these files. You see this file with the name employed or Java. This is what our persistent class would be. So let's see for project is ready in our eclipse and Roman it is would expand this and inside our source directory under a sourcing main Java. We have one default class. We can get it off it if you wish. But what I'm going to do is I'm going to simply drag this last file into this particular package and make sure that we don't have any errors. As you can see, this is a Poggio it implemented realizable. We have one default constructor. Along with that, we also have a parametric constructor which we're going to use to assign values to all these fields will take a look at it in a while and then we have set off feels that we want to correspond them with the relational database table field and then we have the corresponding garrison seras. If you're trying to create this class on your own, don't try to write all these ghettos and set us on your own. It's always better that to generate the court automatically to make it ever free. So you go to source and he choose this option get us and centers. Currently, all the fields in here have their own garrison centers, so I got this prompt. Otherwise, you would get to select all the fields for what you want to generate ghettos and centers. So we got there. Let's move on with our next step. So the next step is to create so called a Cabinet configuration file, which would essentially help. They hibernate to talk with the database. So this is the file, very would provide all the connection para meters so that have a net will know to which database do you want hibernate to talk to? So if you go to the list of downloadable are downloaded files, you'll be able to locate this file with the name have been it dot c of Gerard XML. So let's drag this into the resources folder. So let's create that particular folder under Main. Let's create this folder with the name Resources inside, which we're going to put our convict file. Let's drag this down to here and let's see what's inside it. It's a very simple XML file. With all these tags having it. Conflagration is going to be the ultimate route tag inside which he would specify The session factory. We're going to talk about session factory, incoming videos, and then you have to provide all of these connection battle meters. If you've worked with database before, you probably know what this perimeters are. You would provide the driver details depending on the database that you're using. Since mine is supposedly a secure, I'm pointing to the post Gaskill driver, and here's a euro to my database. The connection you are. Oh, wherever your database is installed, this is going to be that I p address and then port in which your database is installed and in the database. And here we have the that database specific you Zinnemann passport, basically credentials. And then we have something new here, which is called SQL Dialect. Remember, have mentioned that have been. It takes care of translating the Hatch girl or have been it query language to a database Pacifica Skill statements. Well, that is possible because off this dialect, so depending on the database that you're using, you have toe provide this particular perimeter accordingly, Proposed agrees. This is what I have to provide, but for safe you're using Oracle, then that's going to change to this, and if it is for my ask your then it's going to be this. So just do a quick Google search and then you'll be able to get the have been a dialect specific to your database, and you just have to mention it over here. What we have next year is couple off tanks. This is not really mandatory, but it's always good to set this to true so that when we see the output on the council, we can see the list of SQL statements that were executed by hibernate. So show SQL Flag would tell, have a need whether do we want to see the instruction that it is executing in our database and former. The skill would instruct hibernate to show those resulting queries in human readable manner so that quickly that gets displayed will split up into multiple lines, and it would be easier for us to read. So what we have here next is But this property were sort of instructing have been it to update the database according to the changes that are being introduced in our entity. So when I said this to update, this is what is actually going to create a table in case of the table is not present in the database. If I don't have this property set, then we should be creating the table prayer to creating or entities and running our application. We're going to talk about this particular field incoming videos because you need to be aware off certain terms, like session and Session factory to completely understand various options you can provide in here. So we're going to skip it for now. But for the time being, this is needed. Just keep that in mind. Let's continue from next video just for your psychological satisfaction and then we'll understand what this mapping means. See you soon. 46. 0806FirstHibAppPart2: hold it. Let's continue with the next step as part of step for what we need to create is so called a mapping it similar file. This is XML file that tells hibernate which persistent class and its fields would map to which relation or table and its columns. Let me just walk it through the XML document and then you'll understand better. So you have this file employees dotage, b m dot xml To make sure that whatever the persistent class name that should you hear, it has to be same name in here as well. I'm going to drag this into our projects resources. All right, let me pull it again. So here we have as part of resources, let's see what's inside it. These tags are pretty straightforward to understand. Actually, we have this route tag having it mapping inside which you would space for multiple class files, essentially depot systems, last files. So you have the stag in here and he would specify the name of the trance along with its package. So this is our post system class, if you remember, and we're mentioning, but what table name is the table in the relational database And then we're just mentioning those two properties deciding in that persistent class in our case there just age and name . And here are age and name and the map to the relation database table columns with the name an age. So you provide this attribute column that maps to the relation that the best table. So essentially, we're trying to map this particular tribute off entity are persistent class, but this relation database table call them. And in here we're providing the data type basically water. The data time that you provide in here, same goes here as well. And then we have this field, which is I D. Which is also against pacified as bottle Depot system class. Whether forget about all of these annotations, we're going to talk about it pretty soon. And here is I D and is actually the primary key off the relation that the best table and these attributes are pretty straightforward. Your provide the name, which is I d Whatever is specified over here and then and then the type data type off the field and it's corresponding column in the table employees and additionally can also include this particular tag which is generator. This is like generating the identified automatically and in here again have multiple options. This school of these options are somewhat similar to what you would specify a spot off a database SQL query. If you know about generating sequences in s cure, then you can easily understand various other options we can provide in here in my database course, we talked about all of them. Creating sequences are to implementing the values, etcetera. So once we're on our application would be able to see what this is going to do. And specifically, we're going to check to see what is the skill statement that happen. It has executed to replicate the same. Now, once you specify this mapping file and tell have been eight, which persistent glass and it's fields should map to which table and its columns you'd have to mention that mapping inside your Cabinet convict XML file, just as we did here. And by the way, this particular file doesn't necessarily have to be an XML file. You can also specify this as a properties file, so it would name it as hibernate dot properties. But make sure that the name is hibernate and nothing else. And when you're specifying your properties file, it's going to look something like this. You'll get it off all these tags and institute. Just use these names like Cabinet connection. Euro equals the Ural similarly, would provide all the other para meters have dialect except a pretty straightforward Now we're pretty much done with our application. The only thing that we need to do is to write a class file that triggers everything. And that class file is with the name. Just don't Java. Let's pull it into our project and to grab this to the source directory. And in order to understand what's going on in here, we need to know something about sessions and Session factory, which will talk in next radio. But before that, let's try to fix these errors. Can you guess why these errors are coming? I'll give you two seconds. That's because we haven't done anything to use have been it libraries. And as I've already mentioned, Maven will make our job a lot easier. But despondent XML file went open. This and the company that goes inside the Palm the XML file is going to be this. So let's copy all the country from here, and this is the reason why I had mentioned you better said the same corners that I had said so that he won't get any crashes. So here we have those exact coordinates. I'm going to copy this from the Lexx, Mo. File and pissed it in here. So what am I doing primarily here is have included all the dependence is that are required for our Cabinet application to run. Do they can note that these libraries not only wearing truth, having it libraries, but also a few other related libraries, And it's very hard? Or I would say it's impossible or pretty time consuming to do all this on your own. It's very tedious job to search and Internet and download those jar files and then point to that class file's directory, etcetera. It's a big mess, so Megan comes in very handy, and it's a great tool. And in addition to that, by default, the default compiler plug in that comes along with maven would use Java 1.5 portion. So when it explicitly said this para meters to use the job awash in that you are using. So whichever the Dow abortion that you have installed. You can specify that version number in here, so make sure that you change this. And if you haven't provided the same corners that I had provided do make sure that you change them over here. Let me say this file and make sure that we don't have those errors anymore. So let me just quickly upgrade the project. I gotta maven update project, and this is certainly going to take a while. So let me this positivity and then get back. All right, Here we are now. There are no errors whatsoever. So we'll talk about what's happening in here, you know? Next video. See you soon. 48. 0808ExploringTheMailLogic: hold it. Let's try to understand what's going on here in this code. Nominee tells him that this is the business logic off your application, and he wanted to perform some kind of a transaction with the database using have been eight . So the first step is quite obvious in it to create Decision Factory, and this is how you would do so. You want to create an instance off the conflagration class, which is provided by the happen in itself. This configuration class will help you create Decision Factory using the configuration details that you set in this Cabinet XML file. So whatever you provide within this session factory DAG will be fed into the session factory to create the same. So you would make a call to this method build session factory and by default, it's going to assume that the configuration file is with the name have been eight Darcy of Did or XML. And that's the reason why I had mentioned that need to make sure that the name is same and moreover, this is this method is actually duplicated. I'm going to talk about it in the end of this video, but this will essentially create Decision Factory. The next step is to create this session. Isn't this session factory object? And the way you do it is by calling this method open session. And from that point, you can use this session object to perform your transaction. And here's how you do it. Pretty straightforward. You're too. Session dot Begin transaction. And in here he would perform all the transaction steps that you wish to perform. This could be a banking transaction. Like transferring funds are letting the user log in to his account. Except right could be anything but a single transaction in here. I'm going to keep things simple by Justin Stan Sheeting are persistent class, which is employees and that I'm sending some para meters to the Parametric constructor reciting in that persistent class. And I'm trying to say that object in the session. And this is equal into inserting this two entries into the table employees. We're going to see the end result and you'll understand what it means. And once you're done with whatever you have to do, you're going to say get transaction and come it. This is what will make the transaction complete. For example, if there is some kind of an exception that occurs within the transactional instructions that none of the operations will get saved have been. It will just simply rollback the database to its original state before the transaction. Well, this is similar to some of the transactional concepts we had covered in order the best course, but his how you do it like you begin the transaction, perform what we want and then you commit the transaction. If there is some exception, then no changes would take effect in the database. And once everything goes well, you need to take her off closing the session. As of all the Dimension session is not 1/3 safe object, so you want to keep it as short as possible. And here's how you do it now it's time to launch our application. But before that, let me show you the database, and I wanted to show you that the employee table is not already present, so it's not there now. If I run this program I'm expecting have been, it will create that table and also add this entry into the table. So let's on the program and see how it goes. It's expand this console and we're done. Let's go database and see if things are in good shape. And sure enough happen. It did create the table and also inserted the entry. In fact, you can see the instructions that have been it has executed. Now these instructions are specific to your database. So this may differ depending on the database and the dialect that you had used. So it has created the database. Isn't the fallen DTL and it has inserted an entry? Isn't the insert query as well? We're able to see all these messages because we had said these two properties. Now, if you're running this application for the first time, you may not be confident that it would work. And in fact, it's hard to say that it will work in the very first girl. I don't mean to say that I have flaws in my code, but I mean, there are certain things which are not in my control. For example, if you're using a different database, then you have to carefully provide all the required configuration details. If you mess up with it, then things may not work just in case. If things don't work, then then you would get some errors on the screen on the console. Quite understand what it is trying to fix the problem on your own. If you're still not successful, then the lot off on land resources one is a stack overflow and the other is off course. Google. If you do a quick Google search, you would most likely come across with somebody who might have faced the same issue that you're facing. If you're still not successful, I'm the last option. Now, let me tell you something. I can solve your problem. But it may not be a good idea if you want to learn because the best form off learning happens when you do mistakes and then you try to fix those errors on your own. So do keep that in mind. And I guess I also need to mention that we may not be following the best practices to write this code. For example, this method in here Bill session factory is actually the abrogated. I mean, if you go to the documentation off this configuration class, you would notice that this method is actually marked as dipper gated and is no longer recommended to use instead with your dues the same method with this perimeter service registry. Also, we're not really wrapped in this court around the try catch block. Well, I did mention that happen. It is actually going to take care off handling the exceptions. In fact, it is going to take care off handling the exceptions that are related two sq and other database later issues, but it won't handle the exception that occur in our code. So we went to take care off, wrapping the scored around the try, catch block and follow good practices. There isn't why didn't follow those good practices right now is to keep things simple, because if I have to follow those good practices, the number of lines off court with increase exponentially and our code may look little complex, although in reality it doesn't. So just to keep thing simple have written the following code just for the sake of explanation. But I'm going to make the necessary changes in this code, and I'll walk you through the court in next video. See, assume 49. 0809ImprovingOurCode: hold it. Here is the improved Washington for code. Also the recommended way to write or code. So all the deal a significant increase in the number of lines of code. We're trying to follow some good practices here. So first off we have the static block within which were trying to call this method low decision factory. So in here we have the logic that does exactly the same. To load this session factory so that we can use the debt later point of time. And the significance off static block is something that I assume that you already know. This will get executed during the class loading time. But the key thing do not here is the way I'm creating the session factory. This time I didn't use that. Depreciated mattered, but I've done it in a different way. So I created the instance off configuration and that I'm trying to feed the conflagration xml file Do take note that I have no change. The name from hibernate to pose were skill. When you're trying to explicitly provide the name of the file like I did here, then you can give whatever the name off your choice. But If you don't want to specify the same, then you have to live it to have been a doxy of did or XML And what comes next is I'm trying to add resource the employee hatch b m dot xml. And this is basically whatever we give in here, same thing should go there as well. And since these two files are reciting in the Resources folder and not in the sub folder, I don't have to provide the complete part can just pacify directly the name of the file. Now here is the line that deserves some attention having it internally their so called so visas which are basically classes that implement certain standard interfaces. For example, we have connection provider, which is an interface that specify set off standard methods to maintain the data busy connections so that they have been it can actually acquired the connections and perform DB operations. And we have multiple implementations for that interface and each implementation different terms off how they manage the connections, etcetera. But all this implementation would ultimately solve the purpose off managing very busy connections because they all implement the same interface. So now then, what is this service registry in here. Well, service registry will actually manage. Those services that are used by the have been eight. And using this instruction, we're sort of building that service registry object and then feeling this object to the build session factory method to create our session factory. If this all sounds confusing, that's fine. These are all internal aspects off cabinet, and we don't presume have to bother too much about it. But, ah, you don't understand that you need to stop using the duplicated method, which is bill session factor, without any argument. But you should start using this approach, which is with the service industry, and the rest of the changes are pretty much Cordova concepts. You know what is static method, etcetera? And here's the same logic what we had seen in our earlier example. So I'm trying to get this session by calling this method get session and is essentially returning a session object and just off the code is pretty straightforward. And also, of course, I have put in a lot off try catch blocks in here to handle possible exceptions, and that's pretty much it. So for your convenience, I'm actually going to export this project and save it as part of the project files. So you should be able to download this and even import in Eclipse and Roman to take a look at what's happening in here. So living on this program and make sure there's working. But before that, I have actually deleted that table. So we get this error. Now let's run our program and save table gets created. And sure enough, it worked. All right, see you in my next video. 50. 0810IncorporatingAnnotations: In my interview, you have mentioned that one of the advantages with have been it is that it supports standard GP annotations and by using annotations you can actually get it off this mapping file that tries to map depot system class with the relational database table, and we'll see how it's done. In fact, I already have the cord ready. I just have to uncommitted. So inside my persistent class, I'm going to UN command this tree lines. And if you notice we have another here, we have support for these annotations from couple of packages. One is from the Java expert assistance, and the other is from the hibernate. So which one should I use? Can you make a guess? Obviously, it's going to be job expert assistance. That's because let me do control shift oh, to import the class files. So that's because has evolved, we mentioned. These are standard JP annotations as well, so two more at later point of time. If you'd like to switch to a different or M tool that also supports GP annotations, then it's easier for you to switch. If you use have been, it's best if it can irritations the new Mafia certain challenges while trying for all tornadoes. So here we have annotations, and these are pretty much self explanatory. In this a mapping file. We have the class tag. So in here we have had great entity tag. Now, if you're used to enterprise Java beans, this is the entity bean, and by default, the table that's going to correspond to this entity. Bean is going to be with the name employees unless you explicitly specified with another annotation at the table. We won't explore. Rest off the annotations involved incoming videos, for sure, but I would like to keep this video very simple. So we also have a couple of fields along with the identify air. So we do have the idea field, and along with that, I've used this couple of annotations. One is to mention that this field is the identify air, which will be the primary key. And just as we specified a generator here we do have the generator here as well, and whatever the options that you can provide in here can go in here as well. Regiment similar, and you don't have toe explicitly mention annotations in here to tell hibernate that these are also the fields in the database having that can figure it out automatically and would create columns accordingly. So now guess what? By introducing all these annotations, I can literally get it off this file altogether. It's not mandatory that you need to delete this file. We can use both if needed. But I see no point in using XML document, and I'm not sure if I would ever use an example document for mapping. We're going to be using annotations and are examples, unless I feel there's a real need to talk about some of the tags involved in decimal document. So for now, I'm going to get rid off this. So let's dilated. And as a next step, if you remember in our convict file, we have this set and this pointing to the mapping XML fire. So I went to get it off this let me just come in this out and interact with this. So I had the same dag mapping. But this time, instead of saying a resource like an example, document or properties file, I said it's going to be a class file, and I would point to the persistent last and in it to provide the complete package. And I'm going to copy this and use the same, you know, test our job as well. But this time I'm not going to add a resource. Guess what I'm going to add. A class had annotated fast is what I'm going to use inside, which had mentioned that class file and then dark class as simple as that. Now, before I run the program, let me show you that I have deleted the table beforehand, so there's no table off employees. Now. Let me run this program and we'll see it. Get well, say, taking effect. And sure enough, these two queries were executed and same thing got reflected in database as well. So annotations are pretty in to do to program us to code because right when you're defining your fields, a programmer can also take care off how they're going to be present in database as well. So it's like more natural and into the way to write a program and also get it off all the all the mess with the maximal documents. So that's one of the advantages also, moreover, we have lot off tools that would help generate this entity classes from an existing database. So in case if you're not using having it before, but you already have a database, then it can still start with have been it. And you can use these tools to generate this entity classes from the database like you do the reverse engineering and ah, you can and you can get your we're going. We're going to actually see an example of the same as well in future videos. But one does that want age, though with sanitation is that if there's any change that you introduce in the mapping XML document, then you don't have to rebuild the entire application. But if you have any changes that needs to be incorporated as part off annotations, then you have to rebuild the application because we need the dark. Last file with those annotations reflected not really a big concern, and I think annotations is definitely a better alternator. But maybe if you're using earlier Russians off hibernate and you were already using these XML documents, it may be a little bit off in afford to switch to annotations. It may not be as smooth, but still it's possible, and there are tools out there to help you out with the same. So with this, I think we have a fair understanding off Harbin aid. I think this is a good start as well and we have a lot of exciting concepts. Incoming videos, so stadium. 51. 0811HibernateAutoSync: we pretty much talked about all the components involved in our sample had been it application. But one thing I feel that we left behind is to talk about this property, which is part of the convict file here. We can actually provide multiple options so far, Reviews this option update meaning that we're asking Have Nick to check to see if there is any difference between the database schema and the scheme of that happen it is expecting, based on the per system class. Then we're asking have been made to make an update in the database to avoid any discrepancy is but we have multiple other options in here. We can also use create when he uses option create. This will essentially drop or destroy all the data in the database and is going to recreate everything from scratch when we initiate the application. So let me just demonstrate what this means. So in my database, I don't have anything at all, and I'm going to run this. So, as expected, it has created the table as well as it has inserted an entry. So now you should be able to see that limit on this program again. mid term net existing one, and then that's on it. So you see that happen. It has actually re executed all these instructions. That's because prior to these, it has actually dropped the table employees. So when you give the option as create, it's going to destroy everything, and then it will recreate everything from scratch, and update is similar to create. But it's not going to destroy anything. Only there is a need to upgrade the database schema happen. It will do that for us. The other option is validate, and it's pretty self explanatory. So this option will L. O. Have been made to check to see if there is any mismatch between the database and what it is expecting from the database. If there is a mismatch than happen, it is just going to try an exception. So let's make sure that we drop or database or rather, the table. So now employ Table is not accessible, so having it should ideally invalidate this and shows an exception. Let's on our program and see what's happening. And sure enough, it's a schema management exception and is pointing to this employee table and this saying it is missing and one last option that we can provide in here is to create drop. This is something interesting. This will create the schema when we initiate Decision Factory and when we closed the session factory is just going to destroy or drop off the tables in the database. So let's see an example of the same. And for this purpose, I'm actually going to close the session factory close. And so let's on our program before that. Let's terminate all existing process and run it, and here you notice that it has. It has dropped everything, and then and then it has created the table along with it. It has also added the entry as expected, but when session factories closed, it has also dropped the employee table just as expected. Although this is a very cool feature, we don't want to blindly rely on this in real world applications. We don't want to use this. Options like update, create, drop, etcetera. There's a little risk involved. So all this it's better that you use a safe option like validate, and then a database administrator will take her off manually, making sure that everything is intact. But for our examples It's absolutely fine. We can use any of these options and they work where it's moot. I hope it makes sense. See assume. 52. 0801SpringDataJPA: Okay, This chapter is about understanding spring data. So let's try to understand what a spring data from the official definition from the official website Spring drive. Oh, and here is what that to say, spring. There s mission is to provide a familiar and consistent spring this programming model for data access while still retaining the special traits off the underlying data store. It makes it easy to use their access technologies, relational and non relational databases, map ridges, frameworks and cloud based services. This is an umbrella project which contains many sub projects that are specific to the given database. The products are developed by blah, blah, blah. If you're able to understand at least 30% off this definition, that's great. Once after we take a look at a very beautiful example, offspring data will get back on this definition, and we'll see if this definition makes under person sense. But what they're trying to say is, spring data is there to simplify the data access layer often application. It's going to ease your efforts to interact with the database from the application when, as a database, it doesn't necessarily have to be a relational database. It could be a new SQL database on a cloud data service. Spring has a lot off sub projects. That's what they're trying to say spring. There is actually a number the project, which contains many sub projects. And here are day and you to choose the one there's gonna needs if you're using spring very busy. And here's a library that you need to use. And we had all the export spring Jerry busy in our previous videos. Similarly, if you're using any JP a framework, for example, we have Hibernate, which implements GPS specifications, and you can use this library to live rage the spring date of functionality and similar. We have one for no SQL database spring that among Body Be. And we also have one for Apache. How do but the one that we're going to be needing a spring data? J. P. A. Because we're going to be using Habit Net framework to interact with the database. And in our example, we're going to be using a member the database to demonstrate our example. So he wrote the list off things that were going to take care off in our first example is in spring data the first off, which is stabbed. The required dependence is, And since we're using spring boot, it's not really surprising if I say that we just need to add one single dependency and that will take it off everything. And next is to create the entity classes and this entity. Classes would correspond to the database tables and the classes that we're going to create , or student and student address, and these two are going to have 1 to 1 relation. Every student will have an address, and whenever there is an address, there has to be a student that corresponds to that address. We'll see how we can create the relation between these two. And then we'll go ahead and create the repository so that we can dependence, inject the repository into the control logic and then would be able to call the methods in it. And so we contract with the database and perform crowd operations, and ideally, we should also be having a service layer in between. But since that application is pretty simple, we are not introducing the service led yet, but yes, down the line wants to build a real time project, but would most definitely be falling all the best practices and introducing the service later as well, and finally would just try to run the application. So let's let's take a look at the Palm. The maximal file in our project, the only dependency that you need to add his springboard starter did our G p A. And this will also include the Harbin IT library, implicitly using the transitive dependency feature off maven. And since we're going to be using the embedded Hester database, we also need to add the dependency. If there isn't any other database like post DSK alarm, I ask your our mongo DB or whatever. You can just add their dependence in here next year's to configure our application or properties file. And if you're using is too embedded database and you want to leave the user name and password to the defaults, you don't have to add them. But otherwise, if you're using any external database or any other data ways, then you have to take care off providing those connection para meters. But in my case, I'm using a straight the best, so I'm good to go with this. We're gonna talk about this particular property in a while. Let's take a look at the entity classes. As I said, we're going to have a couple off entity classes the first off, which is a student and student address. But you're seeing a lot off annotations here. Well, these are all pretty much jp annotations. And when you're trying to use these annotations, do make sure that we import them from Java X library. You don't want to import them from the hibernate package that will make your application tightly coupled. The only hibernate, I mean. For instance, if you'd like to switch toe any other Orem tool that also implements the JPs specifications , then you have to make a lot of changes in your court. So as a precautionary action tried, import all the classes and interfaces from Java X package and let's bet understand what's going on in this particular class. This sanitation entity will say that this is an entity, and whenever you load this application, or whenever you're deploying this application, if you're not using spring boat, then having it will create a table in the database with this particular table name. That's because we made this as an entity and JP requires that you need to provide an empty constructor empty nor constructor and better that we make this private so that nobody would be able to create instances off this particular class. But we're going to be needing a parametric constructor because we're going to use the same entity class as our domain object so that we can populate the student object and then start off, tried to store using the depositor matters will take a look at it in a minute, and then we just have list off fields that first off, which is the ardent fire, and you would make one off the fields as I didn't fire. Typically, it would be a long type and you would admit it it with after it I d. And then we're saying hibernate that we want to auto generate the I didn't fire. We don't want to manually insert the identify because it's pretty error prone and then we have name. We're also trying to put some constraints that the name shouldn't exceed more than 65 characters, and we're also saying this field shouldn't be now and this is an optional annotation. We're just trying to be you and name, and this is going to be the name that you see in the database. Same is the case, but age and the description. And here is something new. We're having a one on one mapping with student address entity. Let's take a look at what's inside here. We pretty much have the same annotations with just one field that is, address to store the student address, and we also have off course one primary key. And here's the thing. We have one on one mapping with the student. As I mentioned already, we want it's goingto have an address, and whenever there is an address, it has to be a student associate ID with that address. And this annotation would so that purpose these attributes in here fetch type and casket type or more off JP and habit concepts of all. They talked about it in detail in my Cabinet or on Prem a course. If you have gone through it, that's great. I'm pretty sure that you're pretty familiar with this attributes, and we're trying to map with the student field, which essentially means that we want to map it with the field in the student address. So here we have one on one mapping inside the student address as well, and we want to join one column. So inside the table student address, you would see this particular column getting added, which is basically the foreign key, and this would be populated with all the identifiers off the students. I mean, whoever owns a particle address that students I d would be populated here. And we made this knowable to false because we don't want this feel to be an L value. Well, these are all pretty much happen. It's stuff. And again, we've talked about 1 to 11 too many, many to many, and many to one relations, etcetera in or have a net course. And I don't think we have room to talk more on have been made because that itself deserts, of course. But even if you're not familiar with hibernate, they should look something familiar to you. We're tryingto have on on on mapping between these two enter days and in addition to that, for each in every field, we have one getter and setter to set the values, and these methods would be used by hibernate in order to perform whatever we want to perform on this entities and do they can note that we're not setting the student address field with this constructor. We're going to populate it with the matter directly from our controller. Same is the case with student address. We're not populating the student right here when to use the settle method to set the student value. Next year's the repository. Now watch your guests. We want toe right. The class that's going toe have all the crowd operations, etcetera. Well, you will be surprised. Here is the student repository and here is a student address repository. And Thies, too interfaces basically is enough for you to perform the crowd operations. It may not sound too obvious, but let me explain. This is a feature offspring data when when you introduce an interface that extends the crowd repository and by the way, this is going to take a couple of para meters, the first of which the type of the entity and its unique ardent fire. Same is the case with student address. I've created a repository for student address and once he used this particular interface to extend your interface and provide this para meters spring will create so called a proxy object on the fly, and that object will have all the behavior to perform the crowd operations. That's the magic offspring data. Once you load this application, it will also create an instance on the fly or a proxy object that would perform the crowd operations. It's not really magical because we're just providing all the information required all the basic information required to perform the crowd operations. And since we didn't create the tables on our own, and we're letting the have done a deal with the tables using the entity classes, Spring also has the knowledge and how to manipulate the data with these entities. You may not believe it, but it's going to work. So here is our controller logic. Whenever we hit the your with hello when they get this particular logic can. Also trying to do here is we're just leveraging small the methods available in this repositories and of course not to mention a lot off springboard for just happening in here . Since we annotated this interface with Repository, this is going to be auto scan and so we're able to dependence, inject indoor controller and again this is not the best practice. We would rather want to dependents injector repository into a service. And we want to make the sobers into the control of logic. But for now, we can keep patrolling. So what I'm trying to do here is I'm trying to call this method bill It all. And that would just delayed all the entities managed by this repository just so that will have a clean database before we perform any operations. And then I'm just trying to create a couple of objects. One is student and the other is student address. And inside the student entity, I'm trying to set the student address. And why Sporza inside student address. I'm trying to set the student. And then finally, I'm trying to call the same method off student that will not only save the student, but also its corresponding entity student address as well. That happens because off this 1 to 1 relation again, this is having a topic, not something to be discussed now. And finally, I'm just calling this method find all and trying to display all the objects. And you're not restricted to perform, save their host of other methods with me explore You have count, delete, delete all well, it's all entities managed by the report story and they've already used it. You can also use find all find by I D and you would send in. I didn't fire. And this is the reason why we have to provide the island to fire as a perimeter in this interfaces so that it will have knowledge on what is the identifier for the entity. And likewise, you have all the methods required to perform the crowd operations. You can write your own logic, will explore that incoming videos, for sure. But for now, believe it or not, this is all you need. That's the beauty offspring data. Let's run the application and we should be able to see the student object getting fetched from the database. And if you explore the council in here, you would see all the statements, all the log messages stating what happened after the application loads. That's it. The oral and see what's happening. And sure enough were able to retrieve the entry. This is not readable. So little straight into juice. A two string mattered and by the gold is methods are auto generated from eclipse. Just as I'm about to show you, I would select all the fields. They said the fire and same is the case here, too. Get her and said, Uh, select all lips generate. Save the file and read on the application. Let's go ahead and hit the you'll. Okay, we seem to be getting some editors. Let's take a look at what's going wrong. Okay? We have to go all the way to the top to see the exception, and it's a it's a stack. ALS rather. Why did this happen? Oh, I see. Can you guess what the problem is? It has something to do with the toasting method. Alicia is we're trying to print student address, and this is going to call the to string method off student address. And inside this method, we're trying to print the student object, which will then again call back the two string matter of student and just goes back and forth, and eventually it's a stack awards ladder. So to get it off this, we can we have to get it off the object details from here, and, uh, I hope this will Self Islet of the fine and relaunch our application. So let's go here and reload the application. And this time it has indeed worked. Now let's go back to the definition and see if we can understand any better. It's spring. There s mission is to provide a familiar and consistent spring based programming model what this actually means. We're trying to leverage the spring data functionality. Like, for example, we don't have to provide implementation to perform the crowd operations. And this particular interface is provided by spring framework. It is this interface that makes it possible to create the proxy objects on the fly. And so that's going to use things for us and ultimately the goal offspring data is too easy . There access layer, and we're seeing it life. I hope it makes sense. 53. [email protected],NamedParams,IndexedParams: so far. We leverage the functionality offspring data and use one off its interfaces to be able to do card operations without having to write a single line of code, However, most often would like to go beyond credit operations and we to write something complex. For example, let's say we have the following record, you know, database and I would like to fetch a student whose age is 43. Well, I can certainly cannot use one off the methods available in Crab Repository, so we have to do something. They're a couple off approaches to solve this problem, the first of which is to use equity annotation. The query annotation would help us, right? Native SQL queries specific to a database. RJ, pick your specific to JP implementation. Let's take a look at an example and then we'll understand better. So I'm gonna introducing a method said nature in this form. But the key thing to note here is the sanitation with the query string, this is J. Pick your language. This is nothing new. This looks similar to ask you out. If you'd like to write a NATO SQL query specific to your database, then you have to add the following perimeter inside the query annotation and make the flag true. Now if I call this method, discredit would be executed and we would be getting back a collection off students and from inside my controller. All I'm trying to do is to call that method. Here are some of the return types you can use for the query method could use no all the basic types like integer long float bite. What not can also written an entity type and also it down a collection. You can also do it in the results in the form off a stream. All right, let's run our application and see how things are going and and it walked out were able to fetch a student record whose age is 43. And that's what this SQL query is all about. But sometimes we just may not be so simple. For example, we cannot heart cord age in here. We might be receiving this as a perimeter as a matter Param Eter. So in order to dynamically inserted value inside the query in a couple off approaches for that, the first of which is indexed para meters, let's take a look at how we can liver is that. Now let's say that I would like to search a record by age and I d as well. I really wouldn't do that, but just for the sake of example in the search by I. D. One, because I believe that's the idea being created. And I would like to pass para meters here. So the first off which age is going to be off type indigent age and the type long I D. So now we need to replace these with an index so this would correspond to the first para meter, and this would correspond to the second and from inside our method. That's parcels arguments for three and one. And, of course, we do perform the typecasting. Let's save our file and run our application, and this should fetch the record. Can it work? Another approach, which is recommended, is to use named Alamitos. Oftentimes, if your query is very complex, then indexing may get messed up. So instead, golf these numbers going to be using and named Param Eter. I'm going to say age and I D so names has to be responding to each other and let's run our application, and it worked. And just to make sure things won't work if we try to change the perimeters. You said the file relaunched the application, and we shouldn't see any records getting fetched. Sure enough, it didn't. All right. Hope it makes sense. 54. 0803QueryMethods: Another approach to go beyond card operations provided by the studio type intro Face is by using matter signatures so that you don't have to write an SQL query like we did in our previous Example is in the equity Annotation and hero smoked examples off such matters signatures. So that's part of the depositor interface. He could use one of these methods to perform charity off operations, for example, when we say Find by I D he provide the identify. Rare has an employee GIs. It would find the entity based on the Heidi, and this is one of the pre existing methods. But how about going beyond that? For example, let's I wanted to find an entity based on the title our description. So this statement in here is going to return list off movie entities whose title or description is given as the Method para meters. So if a there off this perimeters match, that particular entity would be fished from the database and stored in this list. And if no movie and myself found, then this matter would just simply return and empty list. Similarly, God, further examples we can count the number off records by age. So here I'm trying toe count number of students with a particular age, whatever the Parliament that we send. And this matter would return along value, which is basically number off records that will meet this condition. Similarly, we have a few other examples in here. Here. I'm trying to return distant students because I will use this war distinct in the method name whose age is given as another perimeter. Whatever the age that you provide as a matter perimeter, there's done that Distinct records are entities would be fished from the database. And if no student entities are found this method, Britain's an empty list. You can also limit number off records that can be fished by explicitly providing the number in this manner. Find 1st 3 So it's going to virtually the 1st 3 records and store them in the list by age and then ordered by name in ascending order. This looks somewhat similar to an a skill, greedy and in fact, behind the scenes. That's what it's going to do. It's going to generate an SQL query for us, and here's something complex, and what I'm trying to do here is this matter is going to accept couple off arguments, the description and the name, and we would like to return list off Students whose description match with the given para meter given description are the given name. So this is instant alternate away to write your creative methods. I'm going to make this file about the for you to download so that you can take a look at it . But in all honesty, if you'd like to write a query on your own, then I can defer to the spring documentation. It might take a bit off practice are trying better to get your matter working, but, uh, this might be a better option. But, however, if the method is going to get as complex as this one, and that's going to be not so readable in which gives him a better off go with the query annotation. So let's quickly take a look at a simple example of the same in a project. So I'm trying to fetch list off students by age and identify where I'm passing couple off arguments which would correspond toe age, as allows the I D. And from the controller logic, I'm saying age to before the three, because that's what I'm trying to populate and identify. I already knew that the I d off the field is one that's on your application, and it has indeed fish the record. So his official page, where you can just take a look at all the key words that you can use as part of the method signatures. And in all honesty, I think it's not what, while trying to experiment with each one of these hasn't been. You're quite right. A new method. You start exploded in Google, and in most cases, whatever the query that you're trying to write must have already been written by somebody. So you can make use off that. And in rare instances where you get to work on not so frequent queries, then you can mix and match this keywords and create the query matter. Hope it makes sense 55. 0804Sorting,Pagination,ModyfyingAnn: Let's take a look at few random concepts involved in query methods. The first off wish that were Inter discusses the sorting mechanism. If you're using matter signature approach to ride your query, then you can just simply send the sort object in this manner. He would send the field by what you want to sort and in which direction should be ascending or descending. And this particular matter said nature, would help you sort all the students by age in ascending order. If you're writing a query using the equity annotation, then here's a signature for that. You just try to fetch all the students, but you would send us as a perimeter the sort object. And in this case, we're trying to sort student list by name, and by default it would be in ascending order, meaning that it would be sorted in alphabetical order. Since this is a string, let's talk about imagination as well. Pagination is one of the key features for better performance off the application, for example, think about us not aware you'd like to fetch all the list off students that ever existed and populate them on the U. I. You don't want to populate all the students, like 10,000 records in one go right? You want to fetch a few records at a time that the user doesn't have to wait for all the students to get fished? Imagination is the answer for that. It would let you fetch a set off students at that time, and we can directly integrate this with the U I components and sort off populate and provide the pagination feature. So for that purpose, we just have to send the page herbal object with some set limit the amount off students we want to fetch at the time, and they've actually taken look at a great example off it. In our previous courses, we're trying to populate the fields isn't pagination. And finally, let's talk about the modifying annotation. If you're writing a query where abduction of databases required, just as we're trying to do in this case, we're trying to do need to SQL query and grind the past couple of para meters agent mean. But the key thing to note is a statement update, and when you're doing so, you have to annotate the matter with modifying, and this is going to return an integer basically amount off records that got impacted all right, hope it makes sense 56. 0805CriteriaBuilder: Sometimes you may be required to generate queries. Dynamical it because it may not selfies that you read a static equity. For instance, you're trained to fetch list off students whose name would match with Sunder our Bob, our Jon. And it would pass these as arguments to the method. Well, if you write a static equity, something like this, it may not suffice because you're actually sending a list off names. And you, too accordingly, create the query. For example, if we have one more name, then we need to add one more clause like this so you don't know ahead of time how maney like clauses you should put in that case, the solution is JPs criteria equity and here is how we would use it. So in order to demonstrate this have added couple off more entries and here all day, and I'm trying to save them all to the database. And I'm also creating a hash set to add all the list off names so that we can search the records accordingly. And I'm using a set because I wanted to avoid any duplicate names. And then I'm trying to send that set as an argument to this method. Find students by name, which is in this class you cannot provide a behavior inside an interface. And so I have to create another class market as their depository and then provide the logic . And what we're trying to do in all these statements is we're trying to build a query that will dynamically used these names, all the set names. So we're going to be needing a criteria builder object, which can be provided by the container. So I'm using this particular annotation persistence context so that this would be dependence injected by the container and makes it available for us to use in this method and using that object, I'm trying to get the credit a builder object to build our query. And I'm trying to create criteria quickly object, which essentially means that we wanted to perform very operation on this particular entity . And I'm doing quitted out from stood in our class. So this would represent the student entity, this particular object, And then I'm getting more specific and choosing the particular field in it, which in this case, is going to be name. And then I'm trying to look through all these names using this for each construct and I'm creating list off predicates in this manner. And after that I'm trying to build the query itself. So I want to select list off students where the falling clauses with all the predicates that we had populated. And then finally, I'm trying to execute the query and get back the results, which would be sent back to the controller. And I'm trying to just displayed with sort statement that's when our application. So this should ideally fetch the records that match with stolen name Sunder and John and here, aren't they? We got the record cinder as we last, and John, I hope it makes sense. 57. 0901Intro: okay, in this chapter, we're going to talk about spring security. Security is an essential feature for any kind of application. I mean, you cannot imagine a situation where you're able to send funds to a friend without having to log into your banking application. There has to be some kind of an authentication before you perform some crucial transactions , and spring security is meant to ease the process to introduce security features into your application. Let's take a look at the official definition from the official website, and here is what they have to say. Spring Secure is a powerful and highly customizable authentication and access control framework. It is the de facto standard for securing spring best applications. Spring security is a framework that focuses on providing both authentication and authorization to the job applications. And like all spring projects, the rial poor offspring security is found how easily it can be extended to meet customer requirements and heroes about the future is going to provide authentication and authorization. Authentication would describe whether or not a user can access a particular resource or not . I mean, talking about banking application only if your authenticated will you be able to perform any transactions. An authorization would describe. What are all the resources you can access? A user can axes? I mean, you cannot let them upset visitor to have access to an admin control. That's what authorization would describe its about giving rules to the user. And there are other security features that would protect your application from hacking or were these kind of attacks. And this chapter is about exploding all these features, and in this example, I'm actually going to show you how we can incorporate the future of authentication inside our application. So what I have here is a pretty basic application. This is a symbol. Hello, World spring, good application, and we send request this resource this is going toe respond back with Hello world Now. What I wanted to do is, whenever somebody tries to access this resource, I want them to log in first. Only then they can see this message. So let's take a look at the steps and mold do have that feature, So let's go to a project Step number one, as your guess is trapped toe dependency and has a future offspring boot. If you include this dependency, it's also going to download all the required other dependencies transitive Lee and do the Maven update off the project just so that all those dependencies would be available in the local depository. And once it's done, relaunch our application, and I forgot to mention that there is no Step Number two. This is all it takes to give your application the feature off authentication. You won't believe me. Let's go to a browser and clear the cachet that's control ship dilate in Mozilla and let's reload our application. And if you take a look at what's happening behind the scenes, I'm going to go to Network Tab. Let me try to access the resource. Hello. There is a three word to redirect happening to this location. The log in page. So just batting that dependency spring has made a fair assumption on the basic requirement . Often application is toe have authentication, but what is the user name and password that you need to use in orderto logging and access the resource well by default? The user name is user and the past, what is something that spring will print on the console If you're using any logging mechanism like lock for J. Then you have to check your logs to find password like this. Go to the browser and use this password and terrible tax the resource. But obviously, this is pretty basic mechanism I really don't want use it to be prompted with the log in page. Whenever they're trying to access a resource, for example, you don't expect the user to enter the credentials in other taxes develops at home page. So in order to customize all these, we have to introduce our own conflict file, which will take a look at incoming time. Also just in gifts, if you'd like to. All right, the default is in him. And whatever the password that spring generates, you can use this particular properties to declare your own museum and password inside the application properties file. Let's say user in the past, but is also going to be, say, user, save it and re launch the application. And this time, if you notice spring din, generate the password, let me clear the browser and it's going to be user and user. It worked, but do take a note that in real world applications, we don't rely on this properties this is only for testing purposes in real world applications. We would actually need to store the user details into the database using Jerry Busy driver or with an autumn, which we're going to take a look at incoming videos and will always explore a lot of other features that spring security offers. For now, this is definitely good start, and I hope that you got a sense off the simplicity that spring secure the offers in order to secure your application. I hope it makes sense. 58. 0902InMemoryDataStore: Okay, let's take a look at how we can override the default authentication provided the spring. And in fact, we're going to see how we can create our own users as well as the roles so note, explain or demonstrate the scenario considered the falling use case. Let's say that we have set off yours that end with slash admin, followed by any type off your and then we also have some Resource is that has slash user followed by any pot. We also have a couple off users. Sunder, who is having the admin role and Bob holds the user role as an Edmund cinder, must be able to access all these resources. But whereas Bob should be restricted to access only these Urals, that has slash user I mean he should not be authorized to access any off the admin Urals. So let's take a look at an example of the same by using so called on in memory database in Memory data store in Memory data store simply means that we went to store the users and their roles in an in memory, their store, meaning that we're not going to have any database or create tables are in such a course or anything of that sort. This is only for testing purposes. We can use the in memory data store, but first off you have to create a conflict file. And obviously it has to have this annotation. Alternatively, can actually make all this conflagration part off this spring boot application class itself , because internally, this is also treated as a conflict file. But it's not the typical way he would contribute a security conflagration in real world applications. We would often have the security conflict in their separate file, just as we were having mouth. And then you have to use the sanitation. And this annotation would tell spring that we want to provide our own authentication mechanism. And we wanted to all right, the behavior, the one that spring provides. And this is a class which is off significance. If you take a look at it, what's going on inside? It has a lot off methods with some default behavior, and this is what spring uses in order to provide the authentication mechanism. But what we're going to do now is we're going to all right, couple of the methods belonging to this class and then or read the behavior. One of the methods is configure that takes in this particular Param Eter. What indication? Manager builder And using this object, you can do a variety off things, but in this case, I'm actually going to create an in memory user along with their roles. And here's instruction for the same. I'm using this object to create a user called Sunder with some password, and then I'm going to send him the roll off admin. Same is the case with Bob, with the exception off role being user, not madman. But one thing you would notice here is I use this particular and quarter. It's no open Corder. The reason why I have to use this is by default. Spring will try to decrypt the password that is present in the database when it tries to fetch. Since we're not encrypting the password, there is going to cause problem when these air tries to log in and so have to specify this particular key ward. So that spring will disable password check. It would just try to map it with the plain text in this manner. So what this essentially means is we're trying to store and use this particular password S D. And another matter that went toe override to fulfill our needs is the configure method with his Should it be security argument and using this object, we can actually impose some restrictions. So what we're trying to say is we wanted to have authentication for each and every request that comes in and then on top off it, we're getting more specific and specifying some clauses in this manner. So a user. But the following rules user and admin must be able to access all the Urals that follows this Patton. And similarly, we've added yet another clause saying that a user with the role admin must be able to access any you'll literally. That's what this pattern Saiz and one thing that you to note is you need to start writing the closets from more specific to more generous. So it's it's not advisable that you write this first and then this. And finally we're also asking spring to show the log in page that we've already seen basically. So let's save this file. And another thing, that is what mentioning is inside or controller. I know have a couple of request map Ing's the one that, except you are rules. But the admin baton and the other is for the user Patton. And here I'm just trying to add a couple off para meters, which will be displayed on the browser with a template engine. So I'm just trying to display those perimeters and they just display the user and the role from where the request is coming, you know, to fetch the current user and the role I've used the subject security context Holder, which we can import it from the Spring Library. And with this method, I'm trying to get the user name. And with this I'm trying to get the role and let's run out application and see how it goes . So if you notice spring din gender, it the password, that's because we have ordered in the behavior with this class. Let's go here and tried toe access. The admin section. It would ask you to log and let's enter sooner and the password A s d you know, case at slog in and sure enough we're able to access, and since then there is an admin he must be able to access all the use of resources as well . And sure enough is ableto now. Let's clear the cachet and try to log in as Bob so I would type in Bob and then as d picking, certainly access the user resource. But let's change it to admin and see has expected his not about access an admin resource. So it's four or three, forbidden yesterday the response and has that mentioned before the in Memory data store, his only for testing purposes. In real time projects we would either used Adebisi are or I'm tool, so we'll take a look at such examples in coming time. I hope it makes sense. 59. 0903JDBCAuth: Okay, let's take a look at a similar example, but without using in memory Data Store instead would be using Jerry BC in order to connect to the database and store user data. And first obvious thing that you need to do is to include the driver has the dependence in your palms or XML file and optionally can also include the date of his hope. Your choice. Well, ideally, this is a default database, and if include, springboard started very busy. Implicitly. It will also include the extra data store. But I've added it anyway, just so that you know that if you're using any other edibles and you have toe actually explicitly include that date of his drivers in this manner. Apart from that, you also need to enabled us to database from your application properties file with this particular property. And in addition to that, we also need to create a couple of tables in the database. One is to store the user data, and the other is authorities, meaning their roles. And depending on the database that you're using, you need to write queries that would work with that database. In my case, I'm using extra database and these queries would work. And whichever the database that you're using, you have to have the following schemer. You have to have a table that has a couple of columns. One is user name and the other is password, and we also need to have one more column enabled that would describe whether this user is enabled or not. And you do have to have another table that has the following schema. Here's the name and authority where we would start the role. Information, along with Daddy, also need to have a foreign key constraint that would map with the user stable. I also populated the data or SQL file. We're in a manually sort off inserting couple of entries, so I'm trying to insert Sunder Data with a password. And again, we're not going toe. Use the password encryption. We're going to talk about password encryption in coming time for sure. And then the next instruction. We're adding data into authority stable, where we're specifying the role for cinder. Similarly, same is the case with Bob, but with these a role as a user and this time instead of conflict file, we're no longer using the in memory authentication, but we're using Jerry busy authentication and manual using very busy. You need to have data store configured since I'm using spring boot. The job off confident the data store has been done by the framework itself. But in because if you're not using spring boot and with a different database, he should manually configure the data source on your own. Apart from these were simply writing couple off queries. The first off, which is for authentication in the second, is for authorization. Both will take you. The name has the input, and then we'll fish the record. So these queries should map with whatever the scheme of that you have in the skimmer or SQL file. And not to mention that these two files should be with the same name and the boat should go inside the Resources folder. Once you have all that in place, condone your application and the result would be similar to that off the previous example. So let me just run it. Let me clear the broads of cachet and try to access the page this time the possibilities as DF and it worked. Everything works, sounds previous one. Nothing different only that now amusing Jetta busy, not an in memory data store. And with little bit off tweaks, you can accomplish the same task using an organ framework like hibernate. But I'm not going to walk it through an example off using an organ framework, because I'm going to demonstrating it as part off our project anyway. So when we get into learning creation off the entire area war project from scratch, we are going to incorporate the security feature and will have authentication authorization . Using an autumn tool. We're going to have a couple of tables with many to many mapping, etcetera. So all those complex scenarios would be demonstrated at that point of time. I hope it makes sense. 60. 0904PasswordEncoding: Let's talk about password, including mechanism supported by spring security. You don't want to start the password in it's raw format or in draw text format in the data base because somebody who is authorized to access the database console can actually take a look at the password. And if he's having bad intentions, then he can actually use that password to log in on your behalf and do all sorts off nonsense. And then, in the end, you will take the blame. The password and courting mechanism will actually store the password in such manner that the hacker won't be ableto either understand or use it. So let's take a look at how we can use this in our project. So here are some of them quarter supported by spring security. We've already talked about the nor password and quarter. This is basically to disable the password and according mechanism. So a password and quarter that does nothing. And as I mentioned this war, this is only for testing. India bowled applications. You want to use any of the other in quarters available. But one of the popular options, though, is big crypt, passport and quarter. So let's see how we can use it in order to use it. All you have to do is to add this additional statement where you would specify the password and quarter, and here you can specify one of those classes available. So I specified this beaker passport and quarter. Once you specify that, the expectation is that the password that gets stored in the database is encrypted isn't the same quarter now, since we don't have a registration form where the usable fill the form and then submit so that the encoding mechanism will happen automatically on the password before it gets stored in the database, I do have to explicitly stored the past four definitely in the encoded format. If you're wondering how I got the string, then with a quick Google search, I found this website. It's a browser ling dot com. Here I can actually create a password and quoted, Isn't that end quarter? So entered the password Here's DF in my case and then clicked on this button and got some string. Often we can also said the strength off this passport by entering some number more. The number the more string did of us, what is and once his best. Feel all this in here, whenever somebody tries to log in from a log in form, then let me enter Sunder and possibilities A as DF spring will actually try toe in court the entered password using the algorithm that you specify here. And then it will try to see if there is a match between the included washing off the entered password and the one that is present in the database. If they won't match, then user will be authenticated and will have access to the resource. Otherwise, it will just throw another saying that the indication failed. You can actually write your own and quarter. All you have to do is to create a class that implements password and quarter. It comes with a couple off methods. One is in court, and as an argument you would receive the raw password and inside this meant that you basically provide an implementation to encode the password, and then you have another method matches many into right logic that tells on what basis do you want to see if the two passwords are matching. I mean, the one that is available in the database as well as the included washing off the password entered by the user. In fact, if you take a look at the implementation off this class itself, you would notice those two methods. So here is where then quoting is happening. And here is the basis on which the match condition is satisfied. So that's how you use one of these in quarters, and definitely this is necessary for any kind of application. But obviously you don't want to manually store Thean courted password in this manner. If you have a registration form, then we want to sort of take that passed word and called it and then store it in the database. But for the time being, this will do what would make sense. 61. 0905CSRFAttack: Okay, let's talk about what spring does or see a sort off attack. See a sort of or cross site request. Forgery attack is one of the common at next number hackers. The best way to understand it is with a quick demonstration. So what I have here is a very minimal banking application which would allow me to send funds to my friend and many states. A banking application has a minimal security measure. It needs toe, have authentication in place. And also what are the forms that I use Had to make sure that I use them at the post, not get post is more secure combat to get No, it enabled your indication of added the security dependency, and this will automatically enable the authentication for our application. And here I have a form which goes inside the index file. So the moment I log into our application, this is a page that I would see. And once after I filled the form and submit the details, a post request would be sent to the following the source. So this is the map. Did that will be in worked, and all I'm trying to do here is I'm just adding the name as well as the amount as part of para meters and then trying to display them in the next page or the view. So money the Monterey wanted to send successfully send to the person that I wanted to send . So let's take a look at the quick demonstration off this application. Let's go to Broza. But before that, that start out application and copied this past for generated By spring, I would say User and I want to log in. I'm going to enter the recipient name. It's a Bob and I corn number blah, blah, blah. Whatever. Doesn't matter just doesn't matter in just any type in any random number. And the moon that I wanted to send them is 1 $20. So money 1 $20 successfully sent to Bob. Now, before I longer from this application, I was browsing other websites and suddenly I came across with something like this. Congratulations. You won a lot to your 50,000 click here to receive your $50,000. I'm very excited. Limit. Click it well, see what just happened? I sent 50,000 dollars to a hacker. This is exactly what is he a sort of attack? So let me show you what I've done behind the scenes. Let me show you this page first. Hacker Clickbait page dot s Tamil. It's a pretty simple as Tim Ill page. It has one link that would take you to steal money. Torres TML Let's go inside of what's happening in there. It just has pretty much the same exact form as we have in here. Except not all the fields in here. We're actually hidden. And these fields are actually populated with some default values. Basically all the hacker con details and the M own that he wanted to snatch and then, using JavaScript on with Jon Lord, method were able to submit the form the moment somebody visit this particular page. So, as a victim, I click this link. I would land in this page which would automatically submit this form and would send a request to this particular you on. And if you notice this is exact your with which were able to send a request to this controller to process a transaction, etcetera. So that's how hacking is done. How can we prevent this? The answer is see a sort of token provided best spring security. And by default, this protection is enabled by spring security. So in order to demonstrate you this, I have to go ahead and disable this year sort of protection. Otherwise I wouldn't be able to demonstrate you this. So let me get rid off this first, I can actually get it off the entire conflict altogether and looking. Stop the application. So this time, let's relaunch your application and see if the hacker can still steal the money. Let me go back. Enough course, the password would change with me. Copy this. I would go to the home page and try to log in again. You God. So Michael Number and they won $20 and the records would fail. That's because we don't have to see a sort of token inside off form. Hacker cannot still the money as well. So in order for the transaction toe happen from inside the application and not from the hacker, we have to add to see a sort of token inside our farm in this manner. So once you had this hidden talking, the moment you submit this form, this talking would become bad with the original talking generated by spring framework. So if they bought match than the farm would be processed, If they don't, then that means that it questions coming from a North resources. So let me say this file. They launch the application. Let me copy this password from here and user whatever the name that you wish to you. But before click submit, I guess I'm going wrong with the token that I added in the HTML. Let me pause the video and get the right token and I'll get back to you. Okay, Here we are again. Have corrected the token. It's supposed to be this. Now let's go ahead and try our application user and let me send funds to Bob 123 or whatever. I want to send him to all dollars and it worked. And this time, if I try to access the hacker page, it will not work because the form that we're trying to submit from the Hacker website does not have the CIA sort of token. Even if it does have see a sort of token, it does not match with the original one. So this will prevent CSR off attack. Hope it makes sense 62. 0906InstallingKeyStoreForHTTPS: the moment you send a request to the server all the data from the client, for example, all the data submitted with the estimable form will be sent in the form off packets and people with bad intentions I'm in. Hackers can actually sneak into your network and read those packets. And if you're using Sgtp, all the back of data would be in the text or the binary format, which can easily be translated into human readable language in order to have a secure connection went to make sure that we use or incorporate a mechanism where request can be sent through history. GPS protocol. Hester Libya stands for hypertext transfer protocol secure. It is exact same protocol, but it comes with the delis rapper Transport Layer security rapper that will ensure that the data that is being transported between these two entities client and server is encrypted using a mechanism called public and private keys so that even if the hacker somehow manages to read the data in the packet, he cannot use it in any manner. And when I say keys, they're not strings. They're actually certificates managed by the silver. I mean, it goes something like this, both find and Silver will have a handshake. I mean, the both understand that their boat are trusted parties, and once they know each other, so is going to send a public key to the client. Trend is going to use the public key in order to encrypt the data and on the silver end, once the requested received silver is going to use a private key in order to understand what's inside that encrypted data. So that way. So where is sure that the request is coming from the client and not from are not resources ? And also this will ensure that the hacker will not understand anything about what's being communicated. I've already talked about this protocols in detail in one off my previous courses, and talking more about this is definitely beyond the scope of this course. But we need to have some kind of a mechanism or a tool that will manage the certificates on the seller side, and that tool is a tool offered by Oracle. That's key tool. It's a command line tool. By just running a command, we can actually create a key store, and here is the command that I had drum. It goes something like this and you would be asked to enter a password that you will remember and to the password and just leave all the rest of the questions to the defaults. And once you do that, you have to configure some para meters our attributes inside your springboard application. And here are they. So this is a location where you're GKS file would be deciding the file that you sort of created with this command line have to provide exact same location and then the password to the key store. And I'm also conferring the port number. This is typically the port that is used for Esther DPS communication. I'm ordered in the default port of the Tomcats over and now I'm starting to use this. And from this point, don't wants to do that. Go to the browser. Now you can access our send requests with us. Should EBS protocol and all the communication would take place in secure manner. Hope it makes sense 63. 0907LdapIntegration: organizations always strive to improve the performance off the application. One of the areas where it can be improved is authentication. I mean, you know, after these the logs into his account, we have to check for authenticity for each and every subsequent requests. And that's going to cost a lot of performance because we have to actually fight acquitted to the database and check the records if the user has a permission to access a particular resource or not. And in this case, most of the time we're performing Read operation. We're not updating any records, and the way the RTB amiss works, it's not very efficient for this purpose. I mean, if you're performing a lot off read operations than RTB, Miss may not be the best choice. The better alternative is to use a director service. Let me explain, if you don't know about L. Dap, here is a quick tutorial on the same, but definitely we're not going to dive deep because this deserves a little course for itself. But I'll try to give a quick crash course on L Dap. Let's talk about the term that tree service you can think of better service as a location where we would start the data in the form off key value pairs when you can think off it as at telephone directory. If we were to store the data off users, then we would have a key called name that corresponds to the use the name. Similarly, we may have an email I d. That corresponds to the user's email. I d. Similarly, we might have an address that corresponds to the user address, so on and so forth an example off which can be seen in here. It looks something off this sort. And L dap is a protocol using which we can actually communicate with the directory service so that we can do a variety off things. An open and lap is a software that will enable the doctor service so that we can connect to the server and perform, read, write operations, etcetera. The LDF or held up data interchange format is the file type. Where would store the data? Just as you're seeing in here, an entry is similar to a row in our day. Bms. I mean, all the sections that you're seeing in here is kind of like an entry and each entry can be synonymous to a record in rd BMS. So we have entry for Bob with all his details. And all these individual units are called attributes and they would correspond to a column in the database. Well, sort off. The deity is a debt information trees, and that kind of explains how the data is stored in the Elapsed server and why it is so efficient to perform read operations. This is kind of synonymous to a file system where you would have a folder, and within the four, we will have multiple other folders, etcetera. It's sort off like in a tree. Former and it is this tree format. You shall make it efficient to first the data to perform read operations. So that means elop is not the best choice if you're performing lot off right operations, this is only meant for read operations. And this is perfect for storing user data because when it comes to use us, we're really making it. It's most of the time we would perform read operations, so that's a quick, rough introduction on L dap. If you want to explore more the lot of resources. But we're not going to discuss any for their own L. Dap. That will be beyond the scope of this course. But let's take a look at an example where we can use the elder up services. So what I have here is the elder file with all the details. And obviously, just as you wouldn't mess with the data in the data best directly, you don't want to make edits here in this file. We would usually populate this from our code, have corporate, told us from the official website spring dot i war. And next, as you would expect, we're going to be needing the dependencies. In this case, I'm going to be using an embedded adapts over. And he wrote, The dependence is for the same. And once you do that, have to configure certain attributes inside the application or properties file. The first off, which is the class month to this file. The elder file the 2nd 1 in here is so called a distinguished name. You can think off it as a directory or generalizing set off entries. I mean, if you go back here, all these entries would fall under one distinguished name. So all these entries would be categorized into one general category or a distinguished name . Hope you're able to connect the dots. And then this is the port number where our l'd observer would be running our embedded elapse over. Next thing is off course, we want to all right, the default security behavior and connect to a silver and that will happen inside the security contract file by all writing this method with this perimeter authentication manager builder. And here are several statements which he had to have that would. I love you to access the elapse over for authentication. It has done that link for Dell Demps over these are all specific to L DAP. If you have some knowledge on using L dap, you're probably familiar with this. So let's go toe browser and try to log in with one of the users available. Bob and the password is Bob's password. Basically, whatever the store in the elapse over Have you called the credentials wrong? Hopes. So that's Bob. We will be S b S S w o r d. And it seemed to have walked about. So that's about l dap and how you would use it in spring application Hope it makes sense 64. 1001CreatingEndtoEndApplication: let us talk about the spring application that we're going to create. Here are the requirements for the same. Basically, what we're going to do is we will create a to do application with logging authentication. And here are the requirements. So we're gonna have a user registration form where they use the contagious trader as an admin or as a customer, and the fall must have the following validations. The text has to be between 6 to 32 characters, and we must check to see if the user is already existing. If so, then we shouldn't allow the registration. We also check for the password confirmation and also for the empty string. That's what the decision form. Similarly, we have a log in form and use the needs to be authenticated with the log in form. So we're gonna have a page which will be displayed the moment somebody visits a website and we're going to have a validation in there as well. Where will check to see whether the user name and password would match or not? And based on that, we need to authenticate. And here is a key part. We're going to have a to do management. So once after the logs in, they must be ableto manage a list off to does so we must be able to display a list off to does. And, of course, they must be ableto add it to do the leader to do or updated to do. And while adding the to do or while updating, they must be prompted with the text field along with a date picker. We're also going to have a use of management section we're in will display all the list off users with the delete functionality. We're also going toe incorporate member roles, and in our application, we're going tohave an admin role as villains, a user role regardless off their role. Everybody must be able to access these two pages and only admin and the user doors can access the to do management. But not these of management, and the use of management must be made available only to admin role. So before we take a look at how on application is going to look like, let's talk about various technologies that we're going to be using to develop or application on the front, and we're going to be using JSP along with the Bootstrap Library. The Bootstrap library will give us a lot off comfort so that we don't have to type in all the styling aspects off our application. By just using this library. We're going to save a lot off. Afford required to write JavaScript are cascading style sheets. I'll show you how we can use this library. And of course, we're going to be using spring framework. And not to mention that a lot of components involved. We have a controller and model a depository, a Soviets, etcetera. And here are some of the modules which were going to be using. We're going to obviously need the Web module. Rosalind need security and a few other dependence is We're also going to be needing a database, and in our case, we're going to be using Hester database and not to mention that we're going to live with the functionality offspring boot in order to create our application. So let's quickly take a look at our application and get a sense off how it feels like. So here is the log. Inform the moment you launch your application and you hit this. Your local host call an 80 80. Then user must be prompted with the log in prompt in this manner. But before you're able to log in, you have to register yourself, either as a user or a Sen Edmund. Let's try registering as a user. So here we have all sorts of validations. If I enter some text. Suppose, for example, let's say User, let me copy it So we have a validation agile, testable between 6 to 32 characters. Let me change this to use a name, but then I'm going to make sure that there's a password mismatch. And so we have this particular error message that's made them seem and sign up as a user. The moment is the signs up. He must be able to see this dashboard, and once he clicks this link there be able to see the to do manager. I want to add it to do so. It has to be some description. We don't have certain validations here. Description shouldn't exceed certain characters, and it has to have a minimum off 30 characters. So let me just quickly type in something. I want to do something today. Our tomorrow are day after tomorrow. Whatever you want to write basically. And then you would choose the target date. Well, I really don't want to set it to do like this. That's very de motivating, But But for the time being will let it go. So here we have it to do similarly can add yet another to do if you wish. Save has tried to living the to do there you haven't. You can also updated to do I want to do something today and blah, blah, blah, whatever. So we're able to edit that to do? Basically, we're able to perform all the crowd operations. Let me long go from here now and try to Okay, I guess you're not able to see the log out button. Let me minimize the window. Let me know. Try to register as an admin. So admin user. I'm going to use the same string as a password and has an admin. He must be able to see the list off users and should be ableto also delete the user If he wanted to let me log out as an admin and and see if a user would be able to access the list off users. Ideally, he shouldn't have the permission to do so, so that's re create an account as a user name and a straight access that link list users. And there you have a narrow page. So let's go back. So that's the basic functionality off this application. We're going to explore how we're going to create this application from scratch. Stay tuned. 65. 1002DependencyWalkthrough: Okay, let us take a look at various dependence is required in our project. And I assume that you have a The created a simple maven project are a project using a spring tool suit. In my case, I've used spring to a suit to create the springboard project. And by default it comes with few dependence is. But in case, if you're using just a maven project, then you can add this dependency that would enable you to use all the springboard functionalities along with this dependency. Also need to take care off having this particular maven plug in to live rich all the springboard functionality. So once you do that, he can no add. The dependence is depending on the technologies that you need in your project. You no longer have to think dependence is as a library. You can think of it as a technology. I mean, for instance, just bad. In this dependency, spring boat will instruct maven do not only Donald this dependency, but also the dependence is that this dependency depends on our transitive dependency is so ultimately Melvin would download all the libraries that you have a need in order to use spring J. P. A. And we're adding this dependency because we're going to be using hibernate to interact with the database. And in our case, we're going to be using an embedded Hester database. And not to mention that for every spring embassy project you would need this dependency. Spring would start a web, and if you're performing jana testing, then you would need this dependency. But at the moment, we're not all that interested in this module. Maybe down the line will be using it. We also need spring security as we wanted to introduce authentication, authorization and a lot of other security features and secure justice for testing spring security applications. And again, this may not be needed at the moment, but maybe down the line, we're also going to be needing an embedded Tom gets over and the JSP library specifically j a steal because we're going to be using some standard tag libraries off Jsp to design our view layer. And we need this particular dependency Jasper, in order to compel just be files. Along with that, we also including some of the dependency, is pertaining to the view layer. Those are J query and bootstrap. I can't mentioned before. We're going to be using the Bootstrap Library to simplify things for us. And that's all. All the dependencies and these are all the dependence is that we would need in our project . The next thing that we need to do is to start working on our project. 66. 1003SpringSecurityFeatureBackend: the way I have decided to start working on our project is by introducing the creature off security. I mean authorization and authentication. And since we're not going to be using the default spring security feature, we do have to take care off, introducing the require entities repositories. So this is etcetera so that spring can now use our code to manage the user data. So the person that we need to do is to introduce couple off entities JP entities, when his user and the other is roll, ignore the type of, By the way, the user entity will hold all the users, and the role would hold all the rules available in our application. And in our case, we're going to be needing only couple off rules. One is admin that there is user, and a single user can actually have multiple roles and wise worser a single door can be mapped to multiple users, so that's basically many too many mapping. So we have to create some kind of an association between these two using JP annotations. The next thing that will do is to introduce the depository layer. This is kind of like the data access object are dolls when toe have a user repository as well as a role repository. And not to mention that we're going to be using Spring Data's feature and used the creative methods and interfaces so it will save a lot off typing. Next layer that we're going to be introducing is a service layer. Well, we will write our business logic and in here we're going to dependence, inject the repositories and use its map that so we will need a user. So this, and then notice that we really don't need the role service, so we're going to ignore it. But what we need, though, is a service that will let the spring prima cues to access the user data. I mean, since we're not using the default spring security feature, we have to somehow let's spring know how axes available users and rolls. For that, we have to use one of the interfaces provided by spring. That's user details. So this we're going to provide implementation for this interface, and this interface has only one method. Inside Butch. We'll fight acquitted to the database to fresh the user as well as the USA's corresponding roles. We'll see I would have done in a while. And of course, we're going to have Controller Layer and Bueller as well. But we won't talk about it right now. We'll talk about it when you try to understand the complete flow from start to finish. So let's try to explore what we're doing for all this competent, he does the user entity that I've introduced, and this is going to go inside the entities directory or the package and all you're seeing Here are few JP annotations. If you're aware of how to use Hibernate and J. P. A friend book, all this would look pretty familiar to you. We're going to have a table called User, and here is the unique identifier for that table, and we won't have a couple of fields, user and user name and password. And we have yet another field called password Confirmation used for confirmation. And it's not require that going to store this in the table. So I'm going to make it as a transient by using the sanitation and here, as that mentioned before, a single user can have multiple roles and wise worser So with the sanitation, many to many on trying to create that relation with the role entity. The rest of the stuff are simple. I just used a clip switches to auto generate Garrison Sarah's for all these fields. Scott, take a look at what's inside the role entity. It's pretty much the same stuff, except that you have different fields, and I didn't fire as well as the name off the roll. And we're using minute too many mapping with the use a table. When we lowered this application happen, it will actually take care of creating the tables based on all the details that were provided for both user and the role tables or entities. And it's also going to create yet another table with many to many mapping. Next thing is, of course, to have repository that corresponds to each one of these entities. And here are the query matters that would be needing my default. There are certain methods which are provided by the JP repository that will let you perform all the crowd operations. In addition to that, I found out that we would be needing this particular matter that would find a user biz don they use the name. We'll see how we're going to use this down the line. And similarly, we also have a repository for role as well, with one additional method. We're trying to find the role by name and use. A service is pretty obvious here. We're going to have the business logic required. And again, these are all driven by our requirements based on our application needs. I had introduced few methods that would selfies are purpose. I'm going to walk you through each one of these methods when we try to understand the complete flow right from scratch. And here is the interface that I was talking about that went all right. User Details service. It comes with only one mattered Lord user by user name. The goal of this mattered his. It's going to take in the using them as a perimeter, and we have to somehow populate the user. Details object based on the data available in our database. So we're trying to fetch the user by user name by using the user repository and then trying to assign all the stop authorities that are associated with that particular user and then finally were populating the user. Details object by calling this method which is part of the spring framework and returning it. This will not only be used by spring framework to sort of get the user details, but will also be used by us in our project. The next thing is optional. Since I'm going to introduce the auto log and functionality, I mean going back to her application the moment somebody registers. I guess our application is not running of me. Quickly run it. Here's a name. So without having to log in the woman somebody registers, they're able to see the dashboard That is possible with this map that auto log in. And here we're trying to make use off some security classes available in spring framework in order to authenticate the user. So first thing that we're doing is to fetch the user details, object again by using this mattered, and we're going to feed this into this user password authentication token, along with some additional details, basically the details that user enters. And then finally, we're trying to authenticate that token. We're checking to see if the talking is indeed authenticated, and finally, we're just simply asking spring talking to get the user and let the user access the resource. That's what we're trying to do here. So so far we have created enough infrastructure required to use a spring security feature, and all the additional stuff would come in the controller as well as the View layer, which will take a look at in sometime soon. Hope it makes sense. 67. 1004BackendComponentsForTodo: Just as we have various components for security feature, we do need set off components for to do feature, and all we went need is one single entity that corresponds to the to do stable. And it has a couple of feels, along with unidentified air, which will be auto generated by hibernate. And we have a user name, field and a description field as well as target date. So while adding the to do in our application, we entered the description and the target date. That's why we have these fields in here and use the name is to create that association between a user name and a to do so down the line we went to fetch set off to disassociated with the user name. So we're going to be needing this. The rest of the stuff are pretty standard. Get us in that US methods along with a couple of constructors, and similarly, you also need a repository that corresponds to this entity. And we have a couple of extra Matt. That's which will be needing in our application. We also have a service layer for to do, and here are the set off methods that will be using. And as that mentioned before, when we go through the complete flew off the application, I will walk it through how these pieces off court. One thing that you should remember is whenever you're writing a service, all the strait of First introduce an interface and then implement that interface to provide the behavior. It's just good practice. So everywhere you use the service, you're gonna have the reference type as the interface. Hoping makes sense. 68. 1005JSPFFragments: Let's get into understanding the view layer. There are certain things that will remain common in all the pages. For example, ones that use the logs in the user can actually see the header with all the navigation and also the footer. And once after the user clicks on one of the links is the same stuff which will remain common again. The same Hedda, same navigation and the same footer. Well, in such cases, it may not be wise to have the same court reflecting in each and every page, instead going to create some kind of a template or a fragment that weaken the SIM port in all the pages. So let's take a look at the GSB a file. Our JSP fragment files. Here's the one for the footer, so basically all the stuff that you're seeing in here well written in this manner. Similarly, we have a header field to introduce the head bag, which will also include the bootstrap CSS file. This will have all the styling aspect for our application and in order to use this, you have to include that dependence in your moving from the XML file, and you have to obey the products that the Bootstrap library would be imported into the local depository, and you should be able to see that in the class part as well, inside your project. So here it is. This will have all the bootstrap library, the styling, Jake really etcetera. And here's the part that you to use to access its files. And since I made, despite all the jsp file, all this code would remain common very grind through this fragment initially. What? I mean, if you go to, for instance, the list produce jsp Page have included the stag header. So this essentially Samos, I copied the score into this file. Similarly, we also have another fragment called Navigation. I mean, all the navigation that you're seeing in here home to do is etcetera would come from that fragment. And here's the cord for that. And I believe that you're never off esteem ill. I also believe that I don't have to walk you through which one of these tags They're pretty straightforward. All the styling classes, we're actually part of the bootstrap. CIA says that we had included hope it makes sense 69. 1006LoininLogoutFunctionality: Let's talk about the logging and lager functionality in our application and for this purpose have actually created a user account as Ola's on admin account, already going to talk about the registration process in some time. But for now, let's focus on the log and functionality. One thing that you would notice is that in this page, as well as in the registration page, we won't be needing those JSP fragments. I'm in the header footer, etcetera. So inside our just be filed for log in, I don't have them included. We also need to make sure that when authentication fails, there's an error message that gets displayed, for example, that Malaga in as a user and provide a random password which doesn't match with the user name. So we should be able to desperate this particular message and of the user does log in. The user must be seeing a dashboard in this manner, and when these alongs out, when it longer from the application and this message should be displayed, if it is admin who's trying to log in, then admin must be seeing a different page called list users to manage list off users available so let's see how we can introduced this functionality. The first and foremost in that way to do is to let spring know where our log in pages somebody for when you had this particular you are. We would instruct spring that we need to have our user authenticated with this particular resource and the way we tell spring the same is with the security configuration security configuration. As you might know, where l a was toe. All right, the default behavior provided best spring. And in this case, I'm specifying that it needs to go to this particular resource in order to have the user authentication. So it is expected that will have a log in form in this resource. What this means is the moment you try to access the application, spring will redirect to this particular resource. And inside our user controller, we do have a get mapping for that very resource. Spring is also going to send few arguments. We'll talk about it in a minute. But these conditions won't be met for the first time. And we're trying to return the name of the view that we want to render, which in this case, is log in. So it's this page we're rendering and it is expected that will have couple of feels one is user name and the other is password. And you to make sure that the name would map the water, the name that you would give inside the entity. Here's the name and the password. So there's a couple of input fields. We also have a CIA sort of talking for security reasons. We was we talked about it in our security chapter. So once up somebody enters the log in details and clicks on the submit button, we're going to submit this form. Basically, we're sending a request in the form off forced to this particular resource. But we don't have a post mapping for this for this particular log in string. That's because Spring is already going to handle the Post requests that come from the log in page, and it will make use off the method that were introduced Lord user by user name to fetch all the user details and so it can go ahead and authenticate the user. If there is some kind of an error. For example, user name and password didn't match, for instance, then it's just going to render the same page again for what we already have and get mapping . So it is this method which have been walked. But this time since user name and password didn't match, the string would be populated with some error, and here we're checking to see if it is not now. And we're trying to populate the model object, which will be sent back to the log in page. And we're trying to display that message in here. So that's what whenever somebody tries to log in with invalid credentials there seeing that message, however, the authentication is well, and good spring will by default, go to the context spot. That means the default application part without any mention of the resource. And we have a handler method to handle that very request. So whenever there is a request, get request two and no resource, then this is the method that gets called and inside here we're trying to check to see the role of the user because we want to render the page accordingly. If there's an admin, then we want to render the list user's page. If it is a normal user, then we want toe populate the dashboard. The welcome to DuPage. I'm in this page and inside this mattered get current user roles. We're trying to access the security context and thereby we're getting the user roles associated with the current logged in user. And the reason why Spring has this knowledge is because we already told spring how to access to user details. With this particular method, we will talk about how this user list is populated in a while, But let's take a look at the law. Got functionality as well. The law goat is bottled the navigation bar, and so we have it as part of the JSP file GSP fragment file. So that's inside navigation. And inside here we're trying to play a little trick. Whenever somebody clicks this link, log out, we're going to call a JavaScript method submit and we're trying to submit ahead and form. This one won't be seen by the user, but the purpose off it is is to send a request a post request to the log out resource which will be received by the spring security and it will longer. These are from the context and will render back the homepage which will, of course, be redirected to the log in the source and would ultimately end up here. But this time the string would be populated with the law. Got message, and we're checking to see if it is not now. If it is not know we want toe populate the model object with the name message. And ultimately we're asking to render this particular view, which is this. And so the message would be rendered accordingly, in case often, ever of the credential fails. We're trying to render and adder. Otherwise, it's a message. All right. I hope it makes sense. 70. 1007UserRegistrationAndValidation: Let's talk about how user registration walks. You can make the register as a user or as an admin. We have a couple of hyperlinks as part of the log in page itself. And depending on the link that you click as best we get, records will be sent. So we have a JSP page associate ID with each one off these links. If you click on user, that's going to send requests to the server. But this popular you are. And if you click this link that's going to send request with this your whole admin registration. We have get mapping methods inside the controller toe, handle these two requests. So let's take a look at to get mapping for this. It is a mattered I was talking about. And all we're trying to do is to populate the model object with an attribute, essentially a command object. We're going to use the same entry class as the command object. But this name, we're going to use this name inside off form. So we're asking spring to render this particular view, which is this. And here we have this user form. Well, we're trying to populate all these renter data. Once the data is populated and clicked on, submit button. A request will be sent in the form off a post request to the same path, so that will ultimately end up in the post mapping matter. And here we have the use of form object, which will hold all these renter data as well as the binding result will talk about it in a minute initial. What we're trying to do is to perform validation. Let's take a look at what's inside this particular class. Validation hit a tous. It is a class that were introduced that will implement were not the interpreters of Alba last part of the spring framework by the data. It will give us a lot of convenience to provide the validation feature for our forms. So this is the matter that we're trying to call. And if you notice we're sending couple off arguments, one is the user form. Other is the binding result object, and so we're able to receive them in here. The address is an interface, and finding result is an implementation off the interface. So it's possible that we send the binding result object to here and initially were trying to convert this object in tow, the user object, and then we're liberating some of the validation framework available in spring to perform validation here. We're trying to see if the value entered in the field user name is empty or with white space. If so, then we wanted to display message. Well, this is a key that we're sending. It corresponds to a message. This is the validation or properties specifically for this purpose. So essentially, when you say no, empty, not empty, spring is actually going to take a look at this resource bundle and fresh the value this well is required. And we're also mentioning the field name. That is where the center would be displayed at later point of time. So for each and every field, we have this error object to see if we have another. If so, then we wanted to render it. Similarly, we have a few more checks. We're checking to see if the user enter data or the user name pause in between 6 to 32 characters. If not again. We wanted to display particular message, which is this and it corresponds to the is the name field Likewise we have one for double Get use the name and guess if the user enters the same user name that was all that existing in the database. Then they will see another. We pretty much have the same kind of validation for password field as well. So once about addition is done, we're going to check to see this object binding result and see if it has another. So if any of these conditions are not met, Spring will populate that where the object with errors and we're checking to see if it has intercepts. So then we're trying to render the same page, which is this. And this time, since ETA has some object and the status, we're going to see the error message in case of their own lawyers. Everything is well and good will go ahead and try to save the user. Enter data. This time we're using the user service object, which is dependence injected. And we've already seen some of the methods in the world as part of the he was a service. Let's take a look. So here is the same operation we're trying to perform, and all we're trying to do here is we're trying to encode the password isn't the decrypt password and quarter We wanted a scene, an example of the same in our spring security chapter. And then we're trying to access the user role from the subject and then trying to set list off rules that this user should be associated with in this case, the one days of tohave. Only this role and not to mention that use the repository has this very method which will help us fetch the whole object from the role table here. I should also mention that have manually populated the role table with couple off roads. I'm going to show it in a while and finally I'm setting the set off roles. If you remember, we have one too many mapping. We have a set off roles inside the user entity answerable Toe said it ultimately very isn't the user repository object, which was dependence, injected and calling it smothered, save to save the user into the database. And once the user registers, we're also trying to perform an auto logon. I've only walked you through the logic off the auto log in, but let's take a look at it again. All I'm trying to do is I'm asking spring to manually attend to get with my chord in this manner. I'm trying to fetch the user details, trying to create a talking which will hold all the values. Print authenticated is in one of the spring provided methods and then ultimately, I'm checking to see if it is if it has authenticated the users successfully. And then we're telling spring that the user result indicated Finally, we're redirecting toe this part of your page so it would send a get request to welcome which will take us to this particular mattered. And based on the user role, if they use it all is admin. It has to be this page which we need to populate. Otherwise we want to populate the welcome to do so let me enter to use the name. Hold that existing hopes. So this is the page that I was talking about to go here. You should be able to look at that particular view and here it iss We have pretty much the same procedure, our same flu for admin registration as well. Except that we're sending the role as an Edmund and we're trying to redirect toe list off users, so that would send the request to this particular mattered. And inside here, we're trying to get all the available users by using the service object. And I'm using the report stir method to find all the available users populating the list off you, the SAS part of the attribute users and the mosque in spring to take us to this view, which is this We're gonna talk about this at later point of time. But here's the floor for registration. Have you also show you the SQL statements I was talking about? I populated this file data or SQL with a couple off instructions to populate couple off rules in this manner. If you're using extra database and if you name this file as Daryl or SQL, this would be picked up automatically and will be run on the database and not to mention that have been It will actually create tables on our behalf once you create those entities so we don't have to have DDO statements. All right, Told would make sense 71. 1008ViewAddTodo: Let's take a look at how we can manage studios corresponding to a particular user. Once these, the logs in there be able to say this page, and all it has is a link which would take them toe list off to does. So it is a page, a welcome page with one link, which, when clicked, it would send a request to the server asking for this resource and inside the controller. We have a get mapping for that, you little Patton, and our goal is to fetch list off to ruse, associate ID with the current logged in user. And so we're trying to get the current logged in user by access in the security context and ultimately were able to retrieve the current logged in user from the context. Once we get the name of the user we're trying to fetch list off to does associated with that user. So let's take a look at did mattered inside the to the service. So here we're using one of the creative methods available in the total repository, and here it is. This would fetch all the to do's associated with the given user name and would written a list off to does. Ultimately, the list would end up here, which were populating in this particular attribute, and we're asking spring to populate the following view. The studios, which is this but we don't have any to do, is to be populated, and so we won't see anything here. So let's add it to do this. Particular page also has a link that would send a get request to add. To do so, we have to get mapping for at to do. And we're trying to add a moral attribute, which is basically a command object off to do that we wanted to populate, and this object is going to store whatever the whatever the date entered by the user. And this will take us to this page to do door GSP. And here we have all the form fields that you're seeing in this page once. These, if it is a form and clicks on save, it's going to send upholstery quest to the same. You are basically, since we didn't mention since we didn't mention any action in here, it's going to send the post request with the same your so it would end up in here and our goal is to add that to do into the table. But before that, we're trying to do some validation. If you notice inside our to do entity, we have this validation specified. This sanitation is part of the job X package. And what we're trying to say is, whatever the data are, the string that we're trying to store should have a minimum off 16 characters. And with this annotation, we're sort of enabling that validation for this particular object. And in case if there are any others were trying to populate the same page again. And we have a narrow field that corresponds to the description field inside the to do class . Essentially, what this means is if the user enters the description that doesn't exceed minimum off 16 characters, they would see and ever let me just quickly demonstrate it. Okay, I'm which was the date and save. This is what I was talking about. And in order to provide this particular date choosing capability, I'm using the bootstrap library for the same. And that's what I'm trying to do in here. Once the user chooses the date as well as ads in some text, I will try to store this to do object, which currently has all the user enter data. Along with that, we also need to populate the current logged in user with one off the settlement that's available. And finally, I'm trying to save the to do, like so we're calling the same method off to the repository and then trying to say that to do along with the user. Finally, we're trying to redirect to the distintos page, which will render list off to loose. So let me just copy this. And so this is what I'm talking about, all right? Hope it makes sense. 72. 1009UpdateAndDeleteTodo: Let's also explore update and delete methods. Here is a list of this page and for each and every entry we have bought those buttons. One is Rob date and the other is for delete. What's the clicks on update? We're sending a request with the following your along with that. We're also sending the identify air that corresponds to that particular to do. So it would, uh, send a get request for this particular your girl. And inside here, we're trying to fetch and existing to do from the database with this instruction and then trying to populate in the model object and then trying to render the page to do with this object. What this means is, is a name session got timed out spring security feature. We want the data to be pre populated, and that we were sending back the same object pitch from the database back to the view said would render the fields with that data. The ones after use the perform, summit it and click on Save It would send a request to the same you are and would end up in this method whilst mapping, just as with adding it to do We do have some error checking here. If everything is well and good, we're trying to fetch the user from the context and they were trying to call. They have great to do matter, off to the service and internal. It's going to call the total reponse story save and internally have been. It will take her off updating this record. Finally, we're redirecting toe the list of those paid again. So that will see the updated information like so the delete functionality is pretty straightforward. All we're trying to do is that we received the identifier for that particular to do item and sending it as a perimeter. Ultimately, we're calling the deal. It matter off the to do repository, and we're passing the identifier. But before that, we're making sure that the recorder's indeed present disturbed. What any kind of exceptions? That's it on update and elect hope it makes sense 73. 1010EnforcingAuthorization: there are certain resources that we want only admit to access, and there are certain resources that we want every user to access. For example, we want everyone to access the log in page or registration page, and we don't want any authentication in that case. And we don't want any user to be able to see list off users available and manage them. That belongs to only admits, so we can add a security tool in this manner. We can override the configure method. We had already talked about this in our Prince Security chapter. So in here, what I'm trying to do is we want the request. With the falling you are baton must only be accessed by a user with the admin drawer. Do take note. That wouldn't say roll underscore admin because this particular string role will be upended by spring. We don't have to do that, and we're also saying that all the content that is available in the static folder as the last the Web jars This is where the bootstrap libraries are present and registration and Edmund Registration should be accessible to all the users who visits the website and the user with the golds user and Edmund must be able to access all the rest of the resources, and that's how we have restrictions on who can access more hope it makes sense. 74. 1011UserManagement: If it is, Edmund Ho just logs in. Then that man must be able to manage the users. And in our case, we're just providing the functionality off the leading the user. A steak. Look at the corn. Once the admin registers, we're trying to read at it to list users. So the request would end up in here, and he was just populating the model. Attribute what list off users available in the database and trying to render this view. And inside here we're using a forage construct A J s steel dag to sort off, loop through and populate all the users. We also have a delete button associated with each user, just as with Trudeau's and once the admin place that delayed button, the call would go here. We're trying to date a user by unidentified air, but one thing that you should note is that you go to this implementation when you're trying to delete a user, you must also take care of dilating the user's to do list. It doesn't make sense to keep that to the list when their corresponding user is not present . So for that reason, have created equity method inside the to do service that would delete all the list of entries associated with a given user name. So once off tried to let this user and I tried to log God that particles that can no longer be able to log in because he's no longer present dilated by admin, I hope it makes sense. 75. 1012ProjectStructure: let's talk a little bit about the project structure we're trying to follow. Hollow Core would go inside the SRC directory. The Resources Directory will hold files like the Properties File or Doris Kill Files. In our case, we populated some properties inside the application or properties based on our requirements . I'm trying to enable us to database. And what I'm trying to say here is, every time we load the application, we want the tables to be created from scratch. And here are some JSP specific tags. The rescue revolved to seen its purpose and by the addition dark properties. Inside the Java directory, we have all the Java source code. The conflict would have the security contract or any conflict file that you wish to have Constraint. We have one in, um, constraint that would specify the roads. And similarly, we also have a bunch of controllers that go inside the control of folder or the package. We have set off entities, repositories, services while the daters in our case, we just have only one. And last but not least, we have the starting point to run our application using spring boot and since Syria's and just be not a template. Injun like time leave. We do need the buybacks directory inside which you will let go all the GSP pages and things that are going to remain common in all these pages you want to give them in the common folder. It's not mandatory but assessable practice. So we have all those jsp of files in here. If you have any static resources, it can make them part of this particular folder. In my case, I'm using the bootstrap library for my CSS and JavaScript needs. So I don't have to put anything in here. But that's how we're trying to organize our project. Hope it makes sense. 76. 1101SpringBootActuatorIntro: okay, In this chapter, we're going to talk about springboard actuator. But before that, let us try to understand what is a production environment production and Roman is. A system very would deploy the application. So the end use of the stock years in the application and it is the same enrollment used by tester, sometimes in order to detect the bugs which couldn't be found in the development and Roman . And when you have your application deployed on production in Rome, and you need to actually have some additional tools to monitor the health of the application or to gather some metrics, for instance, maybe you're interested to do the following list off things. Maybe you wanted to check the health off the application, see if there is enough this space or received. The silver is up and running. Etcetera are. You may want to check the can't use the sessions that our act to you may want to get the list off beans. Single done beans that are created are you may want to get access to all the configured application properties or take a look at a list ofall that request map ing's for our application or Maybe you want to take some action, for example, to perform it thread, dump our check, the logging status, the long levels, etcetera. Or you may want to gather some metrics. For example, maybe check the number of Tom get sessions created, etcetera. In order to incorporate these features, you have to install some additional tools or perform. Scan off your application, etcetera, which will be quite messy. But luckily with spring boot, things will become a lot easier. So easy that all you have to do is to add the actuator dependency in your Melvin or Griddle projects in my case I'm using may have. And so I just have to add this dependency. And, believe it or not, that's all it takes to gather all the information that I just mentioned, if not more so, by adding this dependency, Spring is actually going to expose, few has to depend points. No, en Pointe is a concept off Web service. Since we didn't talk about it in this course, I'm assuming that you don't know what is a Web service, but it's not needed that you to know Web services. All you have to know is to how to send request and gather the data so you can send in extra dippy request to an end point and that will respond back with some Jason Data, which will be rendered back in our browser. In our case, the best way to understand it is with a quick example. So since we're trying to gather some metrics, we to have an application that has something's happening, I mean, we can't gather metrics are off a hello world application, right? Were to have some meaningful application. You need to have enough stuff in your application in order to see those data. Only then will it make sense, right? So I'm going to be using the to do application that we had created in our previous chapters and see how we can make use off actuator with now project. So I'm maternity to do application, and I've added this dependency. The next thing I do is to go the application or properties file. Well, I'll talk about this in a minute, but its launch our application and go to browser If you go to the spring documentation. Here are the list off endpoints supported by spring actuator, and each endpoint would solve a specific purpose. For example, if you like to take a look at all the list of beans available, you have to send a request. With this I d. Or if you'd like to get the health of the application, you have to use this I d. So on. Application is up and running. And since we added this dependency, you can now start accessing these endpoints. So let's fire yesterday request to one of these endpoints. But one thing that you should know it is that whatever or the security rules that apply are also applicable for this endpoint. What I mean by that is, for example, if you would like to gather the health off the application, you have to