spring notes imp.docx

Share Embed Donate


Short Description

Download spring notes imp.docx...

Description

The JDBC support in the Spring Framework is extensive and covers the most commonly used features, but there are some new usage scenarios like type-safe queries that warrant some extension to be provided. The core part of the Spring Data JDBC Extensions project provides this type of extension and it can be used together with any supported SQL database.

While integrating spring and hibernate, we won’t create hibernate.cfg.xml file. We give this file information with in spring configuration file. It is recommended. We will configure all information to localsessionfactorybean of spring framework.

Singleton pattern controls the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, driver objects, caching and thread pool. In Factory pattern, we create object without showing the creation logic to the client and refer to newly created object using a common interface. MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns. Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes. View - View represents the visualization of the data that model contains. Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate. If you give my application there is a method/service called “is Authorized” in TLBaseAction class. While extended with base class on sub action classes. We have to override the service in sub action classes (UpdateHWDataModAction.java ...) .but all sub action classes have different implementation of this service. This is called as polymorphism.

Comparator vs Comparable Parameter

Sorting logic

Comparable

Comparator

Sorting logic is in separate class. Hence we Sorting logic must be in same class whose can write different sorting based on objects are being sorted. Hence this is different attributes of objects to be sorted. called natural ordering of objects E.g. Sorting using id,name etc.

Implementation Class whose objects to be sorted must Class whose objects to be sorted do not implement this interface.e.g Country class need to implement this interface.Some

needs to implement comparable collection of country object by id

to other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

int compareTo(Object o1) int compare(Object o1,Object o2) This method compares this object with o1 This method compares o1 and o2 objects. object and returns a integer.Its value has and returns a integer.Its value has following following meaning meaning. Sorting method 1. Positive – this object is greater than o1 1. positive – o1 is greater than o2 2. Zero – this object equals to o1 2. zero – o1 equals to o2 3. negative – this object is less than o1 3. negative – o1 is less than o1 Collections.sort(List) Collections.sort(List, Comparator) Calling method Here objects will be sorted on the basis of Here objects will be sorted on the basis of CompareTo method Compare method in Comparator Package

Type Declarative Transactions

Programmatic Transactions

Java.lang.Comparable

Java.util.Comparator

Definition If your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure. When using the Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction management is greatly reduced.

Way of implementing Using annotation

@Transactional

Using xml based aop configuration to have a transactional advice

Programmatic transaction management is Using usually a good idea only if you have a small PlatformTransactionManager number of transactional operations. For example, if you have a web application that Using TransactionTemplate require transactions only for certain update operations, you may not want to set up transactional proxies using Spring or any other

technology. In this case, using the TransactionTemplate may be a good approach. Being able to set the transaction name explicitly is also something that can only be done using the programmatic approach to transaction management.

Spring MVC Flow 1. When a request is sent to the Spring MVC Framework the following sequence of events happen. 2. The DispatcherServlet first receives the request. 3. The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request. 4. The Controller process the request by calling the appropriate service methods and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name. 5. The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke. 6. Now the DispatcherServlet will pass the model object to the View to render the result. 7. The View with the help of the model data will render the result back to the user.

User's request life cycle in Struts 2 as follows:      

User sends a request to the server for requesting for some resource (i.e pages). The FilterDispatcher looks at the request and then determines the appropriate Action. Configured interceptors functionalities applies such as validation, file upload etc. Selected action is executed to perform the requested operation. Again, configured interceptors are applied to do any post-processing if required. Finally the result is prepared by the view and returns the result to the user.

Difference between hashmap/hashtable/concurrentHashMap:

How does request flow happen in Spring MVC? Shown below. DispatcherServlet acts as the front controller. Simplified actions taken by DispatcherServlet are listed below.

  

All requests arrive at the DispatcherServlet (Front Controller) - STEP 0 in Figure DispatcherServlet resolves theme and locale as configured. Find’s appropriate Controller (Handler) to handle the request. (pre-processors and postprocessors, if configured) (STEP 1)

  

Redirect to the Controller (Handler) - STEP 2. Controller executes the request and returns a view name and a view model object. (STEP 3,4,5) DispatcherServlet resolves the view name and redirects to the view template. The response html is returned to DispatcherServlet. (STEP 6) DispatcherServlet send the response back to the browser. (STEP 7)

Can you list a few advantages of using Spring MVC framework?  In Spring Web MVC, any POJO can be used as a command or form-backing object.  Highly flexible databinding – If there is a type mismatch, it is shown as a validation error on the screen. Business POJO’s can directly be used as form-backing objects.  Flexible view resolution: Controller can either select a view name and prepare model map for it or write directly to response stream.  Supports JSP, Velocity and Freemarker view technologies.  Can directly generate XML, JSON, Atom, and many other types of content.  Highly convenient tag library. Give examples of important Spring MVC annotations?

Important Spring MVC annotations are listed below.   

@Controller : This class would serve as a controller. @RequestMapping : Can be used on a class or a method. Maps an url on the class (or method). @PathVariable : Used to map a dynamic value in the url to a method argument.

Example 1 : Maps a url “/players “ for the controller method. @RequestMapping(value="/players", method=RequestMethod.GET) public String findAllPlayers(Model model) { Example 2 : If a url /players/15 is keyed in, playerId is populated with value 15. @RequestMapping(value="/players/{playerid}", method=RequestMethod.GET) public String findPlayer(@PathVariable String playerId, Model model) { Can you explain the concept of Interceptors in Spring MVC? Handler interceptors are used when you want to apply specific functionality to certain requests. Handler Interceptors should implement the interface HandlerInterceptor. Three methods are defined: 

preHandle(..) is called before the actual handler is executed;

 

postHandle(..) is called after the handler is executed; afterCompletion(..) is called after the complete request has finished.

Interceptors can be configured using the interceptors property. How do you schedule tasks with Spring? Spring 3.0 introduced TaskScheduler abstract to deal with scheduling jobs. Spring has support for Timer (Jdk) and Quartz. Sample methods in the interface TaskScheduler are shown below: ScheduledFuture scheduleAtFixedRate(Runnable task, long period); ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay); Scheduling can also be done using an annotation @Scheduled(fixedDelay=5000) public void doSomething() { // something that should execute periodically } Below example shows scheduling with xml configuration

How do you integrate Spring MVC with tiles? Tiles helps us to define the layout for a web page. We can integrate Spring MVC with tiles by configuring TilesConfigurer and setting up appropriate view resolver. How do you configure Spring MVC web application to use UTF-8 encoding for handling forms? Using org.springframework.web.filter.CharacterEncodingFilter. Shown below. encoding-filter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 encoding-filter /* How do you enable spring security for a web application? Spring Security is used to implement Authentication and Authorization for a web application. We can enable spring security by configuring an appropriae security filter. Example shown below. We can create a separate security-context.xml to define the authentication and authorization roles and accesses.

springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain /* How do you define transaction management for Spring – Hibernate integration? First step is to define a a transaction manager in the xml.

p:sessionFactory-

Next, we can add the @Transactional annotation on the methods which need to part of a transactions.@Transactional(readOnly = true) public class CustomerDaoImpl implements CustomerDao { How do you implement pagination with Hibernate? We can specify the First Result and the Maximum No of Rows that needs to be returned from a query. Query q = sess.createQuery("Some HQL Query"); q.setFirstResult(50); // 50th row would be the first result q.setMaxResults(100); // 100 is the maximum number of rows List cats = q.list(); How does Struts (Struts 1.x) handle requests? Can you explain with an example?

       

User clicks on a link in an HTML page. Servlet controller (ActionServlet) receives the request (Front Controller pattern) , forwards it to RequestProcessor. RequestProcessor looks up mapping information in struts-config.xml, and routes to an action. Action makes calls to populate the Model. Action forwards to a View resource (JSP page). RequestProcessor looks up the mapping for the requested resource and forwards to the appropriate JSP page. JSP file is invoked and sent to the browser as HTML. User is presented with a new HTML page in a web browser.

How do you implement Authentication with Struts 2? Authentication can be implemented by creating an Authentication Interceptor. We can assign this interceptor to be executed with every request.



What is a REST Web Service? There are a set of architectural constraints (we will discuss them shortly) called Rest Style Constraints. Any service which satisfies these constraints is called RESTful Web Service. There are a lot of misconceptions about REST Web Services : They are over HTTP , based on JSON etc. Yes : More than 90% of RESTful Web Services are JSON over HTTP. But these are not necessary constraints. We can have RESTful Web Services which are not using JSON and which are not over HTTP. What are important constraints for a RESTful Web Service? The five important constraints for RESTful Web Service are     

Client - Server : There should be a service producer and a service consumer. The interface (URL) is uniform and exposing resources. Interface uses nouns (not actions) The service is stateless. Even if the service is called 10 times, the result must be the same. The service result should be Cacheable. HTTP cache, for example. Service should assume a Layered architecture. Client should not assume direct connection to server - it might be getting info from a middle layer - cache.

What is Richardson Maturity Model? Richardson Maturity Model defines the maturity level of a Restful Web Service. Following are the different levels and their characteristics. 

 



Level 0 : Expose SOAP web services in REST style. Expose action based services (http://server/getPosts, http://server/deletePosts, http://server/doThis, http://server/doThat etc) using REST. Level 1 : Expose Resources with proper URI’s (using nouns). Ex: http://server/accounts, http://server/accounts/10. However, HTTP Methods are not used. Level 2 : Resources use proper URI's + HTTP Methods. For example, to update an account, you do a PUT to . The create an account, you do a POST to . Uri’s look like posts/1/comments/5 and accounts/1/friends/1. Level 3 : HATEOAS (Hypermedia as the engine of application state). You will tell not only about the information being requested but also about the next possible actions that the service consumer can do. When requesting information about a facebook user, a REST service can return user details along with information about how to get his recent posts, how to get his recent comments and how to retrieve his friend’s list.

What are the best practices in designing RESTful APIs?  While designing any API, the most important thing is to think about the api consumer i.e. the client who is going to use the service. What are his needs? Does the service uri make sense to him? Does the request, response format make sense to him?  In Rest, we think Nouns (resources) and NOT Verbs (NOT actions). So, URI’s should represent resources. URI’s should be hierarchical and as self descriptive as possible. Prefer plurals.  Always use HTTP Methods. Best practices with respect to each HTTP method is described in the next question. What are the best practices in using HTTP methods with Restful Web Services?  GET : Should not update anything. Should be idempotent (same result in multiple calls). Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST)  POST : Should create new resource. Ideally return JSON with link to newly created resource. Same return codes as get possible. In addition : Return code 201 (CREATED) is possible.  PUT : Update a known resource. ex: update client details. Possible Return Codes : 200(OK)  DELETE : Used to delete a resource. Can you explain a little bit about JAX-RS? JAX-RS is the JEE Specification for Restful web services implemented by all JEE compliant web servers (and application servers). Important Annotations:    



@ApplicationPath("/"). @Path("users") : used on class and methods to define the url path. @GET @POST : Used to define the HTTP method that invokes the method. @Produces(MediaType.APPLICATION_JSON) : Defines the output format of Restful service. @Path("/{id}") on method (and) @PathParam("id") on method parameter : This helps in defining a dynamic parameter in Rest URL. @Path("{user_id}/followers/{follower_id}") is a more complicated example. @QueryParam("page") : To define a method parameter ex: /users?page=10.

Useful methods:  

Response.OK(jsonBuilder.build()).build() returns json response with status code. Json.createObjectBuilder(). add("id",user.getId()); creates a user object.

What are the advantages of Restful web services?  Lightweight : Easy to consume from mobile devices also.  Easy to expose : Little or no restrictions on output format and communication protocol.  Most Restful services use HTTP protocol : Entire web is based on HTTP and is built for efficiency of HTTP. Things like HTTP caching enable Restful services to be effective.  High Performance : Less xml & soap overhead and More caching enable Restful services to be highly performant.

What is the difference between REST and SOAP Based Services? First of all, REST is a set of architectural principles defining how a RESTful service should look look like. SOAP is a message exchange format. SOAP defines the structure of message to exchanged. How should the header be? How should the request content be? So, there is no real comparison between REST and SOAP.

To get a real comparison, I compare two popular implementation of these concepts.  

Restful Sample Implementation : JSON over HTTP SOAP Sample Implementation : XML over SOAP over HTTP

All comparison is between the Sample Restful and SOAP implementations described above.     

REST is built over simple HTTP protocol. SOAP services are more complex to implement and more complex to consume. REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached. REST permits many different data formats (JSON is the most popular choice) whereas SOAP only permits XML. SOAP services have well defined structure and interface (WSDL). SOAP is based on well-defined standards (WS-Security, WS-AtomicTransaction and WSReliableMessaging).

Application Server vs Web Server:  Application Server supports distributed transaction and EJB. While Web Server is only supports Servlets and JSP.  Application Server can contain web server in them. Most of App server e.g. JBoss or WAS has Servlet and JSP container.  Though it’s not limited to Application Server but they used to provide services like Connection pooling, Transaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.  In terms of logical difference between web server and application server. Web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.  Application server is heavier than web server in terms of resource utilization.

Collection

Ordering

Random Access

Key-Value

Duplicate Elements

Null Element

Thread Safety

ArrayList

Yes

Yes

No

Yes

Yes

No

LinkedList

Yes

No

No

Yes

Yes

No

HashSet

No

No

No

No

Yes

No

TreeSet

Yes

No

No

No

No

No

HashMap

No

Yes

Yes

No

Yes

No

TreeMap

Yes

Yes

Yes

No

No

No

Vector

Yes

Yes

No

Yes

Yes

Yes

Hashtable

No

Yes

Yes

No

No

Yes

Properties

No

Yes

Yes

No

No

Yes

Stack

Yes

No

No

Yes

Yes

Yes

CopyOnWriteArrayList

Yes

Yes

No

Yes

Yes

Yes

ConcurrentHashMap

No

Yes

Yes

No

No

Yes

CopyOnWriteArraySet

No

No

No

No

Yes

Yes

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF