-
Notifications
You must be signed in to change notification settings - Fork 0
/
fundas.txt
336 lines (246 loc) · 13.9 KB
/
fundas.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
ORM Concepts:
- Used for saving data to database without any queries
- Java ORM
Class --> Table Schema
Objects -> Rows
- 3 steps to build hibernate application:
1. Add the configuration(xml) file
2. Define the entity class
3. Define the main or application class to perform DB operations
Spring 5:
- Component/Bean based programming
- Dependecy Injection : Giving the control of object creation to Spring so that dynamicity is achieved. It is done
through auto wiring
- Autowiring : When an already dependency injected class/[NOT interface] has objects from another class then we
don't instantiate it using new keyword rather we annotate the another class with @Component and it's object
in the present class as @Autowired so that the object creation control is given to Spring.
- autowiring setters and construtors are different cases. U have to autowire the setter and not the object
in order to reflect the new changes but incase of constructor u don't need to autowire the constructor
rather u have to autowire object.
L-373 : Autowire Scenerios
- @Qualifier("Component_name") -> u can specify which specific compnonent u want to autowire to in the
"Compnent_name" to reduce ambiguity between several component. This is used for java files which are not the
main or app.java. In main file we used context to distinguish between components.
- Bean: Java Object created by Spring
- @Bean : Now u can remove the component annotation from different classes and use the @Bean annotaion for
all of them in a single file i.e AppConfig.java
- Constructor Injection : If two classes implementing the same interface are very similar, then u can combine
them into one and use parameterized constructor to differentiate them
- Server multiple context issue : https://stackoverflow.com/questions/7239613/multiple-contexts-with-the-same-path-error-running-web-service-in-eclipse-using
- Converting Dynamic Web Project to Maven : L384
- When creating maven project:
1. group id -> package name
2. artifact name -> project name
Spring MVC:
- In src/mainController.java
@RequestMapping("displayname") //default method is get so we don't need to specify method and when there is
//only one parameter, it defaults to value
//displayname is same as the name given in action param of form tag
- @RequestMapping() -> Responsible for handling URLs get and post request
- @RequestParam() -> Acts like bodyparser in node.js. Relieve us from using the legacy HttpServletRequest request.getParameter()
method.
- U have to use model.addAttribute() now instead of request.setAtrribute()
- U also have to use ${} instead of <%= %> in ur view file now
- ModelAndView can be used instead of model and is the better approach although both do the same job.
- @GetMapping() -> Handles Get request Specifically
- used jstl core tag <c:> </c:> for implementing foreach loop in jsp view file -> L-387
-u have to specify required taglib tag for using the core tag at top:
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
***SPRING FORM ELEMENTS***:
*****************************
- spring-form JSP Tag Library : https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/spring-form-tld.html
- SPRING FORM TAGLIB: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- ModelAndView : Can be use for both model and views.
- U can add a class object here to pass it to your view path and later again pass it to different
route view but now with some data in it.
- i.e u can use ModelAndView to pass object or model to different views.
- How form works:
-By path : u specify the class fields in these paths attr of forms so that they can be fields are given values
when u submit the form. These are done automatically by spring. U have to specify getter and setter
for this to work in ur model class
- U can also use a Map<> to represent the classfields of model so u don't have to manually specify multiple
classfields for multiple paths as in Project : Spring Form Radio Buttons
- in case of Map, the value is displayed to the user while key is assigned to the classfield.
- Adding External Resource to Eclipse like Spring IDE:
- now u can display without creating route for it and also access local files using the spring mvc plugin or
namespace:
- Project : Spring Add External Resource
- L-398
- ${pageContext.request.contextPath} -> for getting the current context path for accessing local files
- equivalent to __dirname.path in node
- Form Validation Using Hibernate:
- Add hibernate validator to your maven
- Add the condition to your model class
- Add @valid and BindingResult parameter to your @PostMapping Function
- Project : Spring Form Validation using Hibernate L-402
- How to let the user refill a form if the hibernate validatpr condition are not met:
- Simply create a ModelAndView object and return if BindingResult has error
- Project : Spring Form Repopulate; L-403
- Alternative to ModelAndView :
- U can also use ModelMap to pass values to views L-404
- Making the controller more simpler:
- By shifting the map objects from the controller directly to the view files.
- U should do this if u r dealing with STATIC values
- STATIC CONTENT GOES TO VIEW FILE
- DYNAMIC CONTENT WHICH REQUIRES LOGIC AND DATA FROM DATBASE SHOULD BE DECLARED IN CONTROLLER AND THEN
PASSED TO THE VIEW.
- L-404
- How to add error message:
1. Add @ModelAttribute("objectName") to ur ModelAndView object returning Post class
2. Add <form:errors path="name" /> to ur form
3. U can add a custom error message in the validator annotation parameter in ur model class
- Other validators : https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/package-summary.html
- most used - @Email for a correct email address; L-406
- Spring Database Concept:
- Web Browser --> |Security Layer - Controller - Service Layer - DAO(Data Access Object)| --> Database
**RESTful Api(JAX-RS)**:
***************************
- REST -> Representational State Transfer
- Resource based URIs
- HTTP Status Codes:
1xx -> Informational
2xx -> Successful
3xx -> Redirection
4xx -> Client Error
5xx -> Server Error
- HTTP CRUD
GET --> READ (Read) Safe/Repeatable (Idempotent)
DELETE -> DELETE (Write) Safe/Repeatable (Idempotent)
PUT --> UPDATE (Write) Safe/Repeatable (Idempotent)
POST --> CREATE (Write) NON REPEATABLE (Non-Idempotent)
- HATEOAS -> Hypermedia as the Engine of Application State
- Hypermedia(links to other media) derives the application.
- Richardson Maturity Model -> categorisation of restful APIs.
- L-442
- Level 0: Not a RESTful API
- Level 1: Multiple URI and Single verb (POST) (Partially RESTful)
- Level 2: Multiple URIs and Multiple Verbs (HTTP Methods) (Partially RESTful)
- Level 3: URIs, HTTP and HATEOAS (Fully RESTful)
- RESTful API are agreement between client and server
- PATH Params can be specified in a URI by
..something/{path_param}
public String func(@PathParam(path_param) String x){
return x; //x == path_param
}
- A REST API
1. Produces : return some response like GET
2. Consumes : u must provide data in XML or Json format to perform operation in the server like POST and PUT
- For REST API to return XML response:
1. Annotate the entity or the db schema class as @XmlRootElement
2. In the controller or resource class, annotate every xml response returning methods as
@Produces(MediaType.APPLICATION_XML) or @Consumes(MediaType.APPLICATION_XML)
- For REST API to return JSON response:
1. In pom.xml file uncomment:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
2. No need to Annotate the entity or the db schema class.
3. In the controller or resource class, annotate every Json response returning or consuming methods as
@Produces(MediaType.APPLICATION_JSON) or @Consumes(MediaType.APPLICATION_JSON)
- For Rest API to handle filters ie /.../..?name=car
1. Add @QueryParam() to ur resource method and change service and dao layer accordingly
- Reading header and cookie values using @HeaderParam & @CookieParam:
L- 469
- Both header and cookie values as well MANY OTHER IMPORTANT VALUE like the uri path etc. can be retrieved
using the @Context annotation : L-470
- For setting the auto-increment Id of an entry properly annotate the id field in the entity class with:
@GeneratedValue(strategy=GenerationType.IDENTITY)
- How to add the location i.e the uri path to the header of an API response:
L-472, Project: Rest Location Header
- To return multiple type of mediatype responses:
@Produces(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON)
- To map a Generic Exception Class method to any other class use the annotation :
@Provider
- The generic exception mapper can be called by any exception. U can also build specific and custom
exception mapper but it can be called only by the specific Exception.
- How to explicitly tell hibernate that a class field is not a database column:
@Transient
- To build a url for another class resource from a current class resource u can use .path() for class and method
level paths:
uri.getBaseUriBuilder()
.path(ProductsResource.class) //to get the class level path
.path(ProductsResource.class, "getProductsByBrand") //to get the method level path
.resolveTemplate("brandId", brandId) //to resolve a dynamic or variable path value
.toString();
- Jersey Moxy Maven : Helps to convert object to Json
- Alternate to web.xml configuration -> annotaion based java config file : L-484
- MessageBodyWriter is for making the server understand our code which may have different codebase.
- To make an object last longer in the memory i.e not creating new object everytime for get requests, use the
annotation:
@Singleton
- When u use @Singleton, then class level variables and annotations values should be initialised beforehand,
but method level annotation values need not be initialised as they are just placeholder
SO if u want to use class level annotation variables in ur methods don't use @Singleton annotation.
- If u want to incorporate the value of query params into class object using its constructor then u have to
use paramConverter and paramConverterprovider:
L-490,491
- U can also implement the logic in ParamConverter directly inside ParamConverterProvider so that u will
have only one file for converters.
***Spring Boot***
====================
- How to generate web.xml files:
1. Right click on ur project folder
2. Click Java EE tools
3. Click Generate Deployment Descriptor Sub
- SpringBoot app creates a embedded local tomcat server. So ur application will run on browser even if u stop or delete the server
- To incorporate jsp support to your springBoot app add the maven dependency:
tomcat-embed-jasper
-THE VERSION MUST BE SAME AS YOUR LOCAL EMBEDDED TOMCAT. SO FIRST CHECK IT ON UR MAVEN DEPENDENCIES FOLDER
- If u want to move ur view files from web-inf to another subfolder of web-inf say views then u should specify the
prefix and suffix values inside ur application.properties which is in src/main/resources:
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
-application.proerties is for overriding the springBoot defaults, see which properties u can override:
https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/html/common-application-properties.html
- HOW TO EXTRACT A WAR FILE FROM A MAVEN PROJECT:
1. run as maven clean
2. run as maven install
3. Refresh ur project
4. If no errors, .war file should be in target folder
- to tell springboot that a value is a variable in the url use the annotation:
@PathVariable like @PathParam in jersey
- To make an object or variable singleton i.e only a single copy can persist, so that it can be retain by
the server temporarily declare it as STATIC
- spring doc for database connectivity : https://spring.io/guides/gs/accessing-data-mysql/
- if u don't have ssl functionality and want to avoid the warnings then in ur application.properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false
- Easiest way to select port for a spring boot app:
On ur application.propetries:
server.port = 8081
- how to communicate between microservices:
1. Create a rest template
2. Store the result from another microcservice rest api in rest template
3. add the result in a ModelAndView object
4. Display the model and view object on a jsp file.
- How to redirect to a using ModelAndView:
return new ModelAndView("redirect: /error");
- How to suppress spring boot default error:
In ur application.properties:
server.error.whitelabel.enabled=false
- To mark an application as an eureka server:
@EnableEurekaServer
- To prevent eureka server from registering itself, on application.properties:
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
- How to @LoadBalanced when u have 2 instances of the same application:
1. Add the eureka client maven dependency in ur pom.xml
2. Add the annotation to the rest template class because it is the consumer.
***Java***
===========
- Static variables, methods or classes can be accessed without object.
- Nested interface are by default static, so they can be accessed without creating an instance of outer
class or outer interface.
- Similarly a nested class defined under an interface is static
- Factory method
The method that returns the instance of a class is known as factory method.
- In java, garbage means unreferenced objects.
- There is only one instance of java.lang.Runtime class is available for one java application.
The Runtime.getRuntime() method returns the singleton instance of Runtime class.
- Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
***JUnit***
=============
- Junit4 --> Junit5
- @Before() -> @BeforeEach
- @RunWith(MockitoJUnitRunner.class) -> @ExtendWith(MockitoExtension.class)