Ads Here

Wednesday, June 29, 2022

JAVA Viva Questions and answers GFT ASA

GFT

JAVA

● OOP: Any programming language which follows these concepts is known as OOP:

○ Class and Object:

■ Class is a way to bind data and code together into one unit. Object is

something that is derived from the class. It is the instance of the class. It

has ->state(what property it has. Represented by data members) and ->

behaviour(what actions it can perform. Represented by member

functions).

■ The object will be created in the heap memory after it is instantiated. The

reference variable will go inside the stack memory. And the reference

variable will point towards the heap section containing the data inside the

object.

■ Eg:

● class Employee {

● private String employeeID, name;

● private double salary; //data

● public takeTest() {}

● public fillTimeSheet(){} //code

● }

○ Encapsulation: Wrapping up of data and code into one unit.

○ Abstraction:

■ Showing essential features and hiding implementation details or

unessential features by using Access specifiers.

■ private : only accessible within the class

■ default: accessible within the same package.

■ Protected: accessible within the subclass only.

■ Public: accessible everywhere.

○ Inheritance:

■ mechanism of deriving new class from already existing class.(reusability)

■ Eg: class Employee {//data+code} class TeamLead extends Employee {}

○ Polymorphism:

■ many forms.

■ Method overloading: same method name but different parameter, return

types, data types.

● Constructors:

○ Special member functions cuz it has the same name as of the class name.

○ Used to initialise the data members of the class.

○ They don’t have a return type.

○ Two types of constructor

■ default

■ parameterized.

○ Constructor is invoked when the object is created.

● Constructor chaining:

○ When the child object is created, the parent class constructor is called first then

child class constructor.

● final: can use it only with variable name, class name(but not with sub class) or

methods(but you cannot override).

● Abstract class: which has at least one abstract method(method with no definition).

Cannot be instantiated, have to create a sub class and instantiate it.

Subclass has to override all the abstract methods from parent class.

Can have methods and data like a normal class.

● Interfaces: it is a pure abstract class.

○ Data members: public static final in nature.

○ Member functions: public and abstract.

○ Through interface, multiple inheritance is possible.

● Exception:

○ Hierarchy:

■ Throwable Class, Inherited by Exception and Error.

○ Exception:

■ Checked:

● to be handled at compile time.

● eg: filenotfoundexception, classnotfoundexception

■ Unchecked

● to be handled at run time

● eg: arrayindexoutofboundexception, nullpointerexception,

arithmeticexception.

○ To handle the exceptions, these keywords are used: try, catch, finally, throws and

throw(throwing custom exceptions).

● Try with resources

● Collection Hierarchy(Interfaces) -extends> Set, list(arraylist, vectors and linkedlist) and

queue

● Map -extends> SortedMap

● Set <implements- HashSet, LinkedHashSet, TreeSet

● Comparator(has compare, multiple fields) and comparable(has compareTo, single field).

● Multithreading:

○ Process is a program in execution

○ Thread is a part of a process which has its run time stack and shares the process

resources.(A process may have multiple threads).

○ Since java supports multithreading, jvm creates multiple threads, that is tasks are

threaded and all threads run parallely (concurrency).

○ Thread creation (Thread.currentThread().getName()):

■ By extending Thread class

■ By implementing Runnable

● Synchronization

● Serialization DeSerialization (obj to byte and byte to obj conversion (kind of encrypting

the data into binary code))

● Thread joining

○ Using td.join() : halts all other threads till this current thread is executed

JAVA 8:

● Supports default method in interface

○ Adding default methods in interfaces.

○ Cannot use default keyword in method in child class

○ No matter static or dynamic binding, the output will be same from child

class

○ Multiple inheritance is possible and if same methods, should be

overridden using InterfaceName.super.methodName();

● Supports static method in interface. (No need to create object to access

methods)

● Supports functional interface.

○ eg: Runnable

○ If the interface has only one abstract method, default and static can also

contain along with it.

○ It is also a functional interface when methods from java.lang.Object are

overridden in this interface.)

● Supports lambda expression, better than anonymous inner class: declare and

instantiate at the same time. Can be used only once.

○ Functional interface is the heart of lambda expression.

○ Used to define the method from the functional interface.

○ ‘->’ is the lambda operator

○ Syntax : (parameters) -> {statements;}

● Supports Stream API

○ It is a sequence of elements. Syntax: Stream<Integer>;

○ This sequence of elements can be obtained from any source like

collection, array or an IO operation.

○ Operation of elements. Predefined methods are present to perform

operations on this stream.

○ Pipeline of operations. Eg: stream.filter().map().forEach();

○ Stream vs collection: stream doesn’t store anything.

○ Functional in nature

○ It is unbounded(no size limit)

○ It is consumable. ie., elements can be traversed only once, can’t be used

again.

Java 11

● Added LTS support(3 years, 6 months one release.)

● Oracle jdk is restricted to the dev and testing environment.

● Updates to stream api

● Added new string methods like strip(), stripLeading(), stripTrailing(), isBlank(),

repeat(n).

● Predicate.not() in the stream filter function as a “not” function is added to java 11.

● var is introduced in java 10, but java 11 allows var keyword to be used when

declaring formal parameters of implicitly type lambdas.

● .destroy() and .stop() from the thread process are being removed from java 11.

● Optional container with optObj.isPresent(arg1) and optObj.isPresentOrElse(arg1,

arg2). Here arg1 and arg2 should be lambda expressions

● To run java 11 program in cmd (we don’t require javac in java11),

○ Syntax: java HelloWorld.java

● New garbage collector is introduced (Epsilon garbage collector)

○ It is a low latency garbage collector which does concurrent tasks.

○ It has a large heap size.

● HttpClient is introduced in java 11.

Junit:

● Unit testing model.

● Unit testing is done by developers in the development phase.

● Assertions:

○ Statement in java used to test assumptions.

○ It is assumed to be true while executing an assertion.

● Fixtures:

○ Fix the state of objects for running the test cases.

● Junit 5 (Java 8+): has Jupiter api, vintage api and Platform.

○ Jupiter api contains all the new extensions.

○ Vintage api gives us the features available in junit 4 and junit 3.

○ Some annotations and functions:

■ assertEquals (value is compared) and assertSame (object is compared)

■ assertTrue and assertFalse

■ assertNull and assertNotNull

■ @Test, @RepeatedTest(value=, name=)

■ @BeforeEach, @AfterEach

■ @BeforeAll, @AfterAll (TestInstance(Lifecycle….)) use static method for

these and no need to include TestInstance

■ Assertions.assertEquals, assertSame, assertThrows returns Throwable

type, assertNull, assertNotNull.

■ @ParameterizedTest with a function having one parameter,

@ValueSource(ints/longs/strings/doubles = {1, 2, 4}), so these values will

be supplied to that function for test cases. Also

@EnumSource(enumName.class), @MethodSource(“methodName”).

And for csv file, it is @CsvfileSource(resources=”filename.csv”)

■ @Disabled (ignoring the test case), @Tag (grouping test cases based on

env), @Nested

JDBC:

● Packages:

○ Java.sql (basic functionalities)

○ Javax.sql (server side accessing of data)

● JDBC DriverManager : loading and registering the driver with application.

○ Helps in connecting db to java applications.

● Connecting to db:

○ Loading the driver (Class.forName(“com.mysql.jdbc.Driver”);)

○ Create the connection using db url (Connection con =

DriverManager.getConnection(url, username, password);)

○ Create statement

○ Fire the statement

○ Close the connection.

JPA (Java Persistence Api)

● ORM: object relational mapping.

● Orm acts as a bridge between object and relational model.

● Orm will take care of:

○ Finding and registering the driver

○ Connect to db schema using url

○ Mapping non compatible data types of java to relational model

○ Simplification of crud operations

○ Provides support for writing custom queries with db.

● Using orm, the class will become the name of the table in relational model.

● JPA: specification/set of rules helps storing java entities into db.

● We will be using a hibernate provider on JPA.

● JPA:

○ Entity:

■ to make the class entity, annotate with @Entity (javax.persistence.Entity)

■ Refers to logical collection of data that can be stored into or retrieved as a

whole, from a database.

■ It's a class which can be mapped to a db table.

■ Every entity must have one id attribute (uniquely identifying a tuple ->

PK).

● Annotate with @Id (javax.persistence.Id)

■ By default table name and column name will be the same as java class

and attributes. To change it, use @Table(name = “”) and @Column(name

= “”)

■ @Temporal(TemporalType.DATE) is used before java.util.date attributes

which automatically formats this in the db.

■ These apis are introduced in jpa:

● EntityManagerFactory:

○ its an interface present in javax.persistence

○ Persistence.xml is present in META-INF folder

○ So this entity manager factory reads from persistence.xml

file by mapping PersistenceUnitName and configures

application with driver info, connection info, user

credentials for db, entity names and provider name.

● EntityManager:

○ Its an interface

○ Its created using EntityManagerFactory

○ It represents the db connections

○ Manages entities and performs crud operations.

○ em.getTransaction().begin();

○ em.merge(obj); //or em.persist(obj); //or

em.find(className.class, id); //or emp.setName(); //or

em.remove(obj);

○ em.getTransaction().commit();

● Entity

Persistence.xml

● tags :

○ persistence-unit name =””

○ class

○ Properties

■ Property name = “” value = “”

Layered approach:

● Dao (interface and class)

● Service (interface and class)

● Entity

● Bean

● Utility (for emf and em)

● Resources.

Entity Relationships:

● Employee(child entity because assetId will be fk in this table) -has-> Asset

(Unidirectional relationship)

● Code for one to one:

○ @OneToOne

○ @JoinColumn(name=”assetId_fk”, unique=true) //for one to one, unique should

be true.

○ private AssetEntity assetEntity;

● One to many: employee -> department

● Many to one: company -> employee

● Many to many: employee -> meeting

JPQL(Java persistence query language):

● Used to execute queries on entities (not on tables and columns)

● Also called oql(object query language)

● Jpql queries are converted into sql queries by jpql query processor.

● Use Query interface for using custom queries (javax.persistence.Query) including em

and emf.

● query.setParameter(1, value); //1 is the position and is used in ?1 query

● query.setParameter(“a”, value); //a is the character to be replaced used in :a query.

● Above entity @NamedQuery(name = “something”, query=””)

and em.createNamedQuery(“something”);

● @NamedQueries({

@NamedQuery(name, query)

@NamedQuery(name, query)

}) //same can be included in orm.xml instead of this method.

Servlets:

● Web Pages can be either static(sends pre-built html page in response) or

dynamic(sends an html page which is created by a server program at runtime).

● Servlet is used to create web applications that reside at the server side for dynamic web

pages.

● Servlet api:

○ Servlet (Interface): methods -> init(), service(), destroy()

○ GenericServlet (abstract class): except service(), others are implemented.

○ HttpServlet (abstract class): doGet(), doPost()

○ UserDefinedServlet (LoginServlet.java)

● Steps:

○ Create a class that extends HttpServlet

○ Override the http method like doPost() or doGet() (write the business logic here)

○ Web.xml will act as a web container, has <servlet-mapping> ->has->

<servlet-name> and <url-pattern>.

● Servlet life cycle:

○ init() and destroy() only once no matter no of requests made

○ service() no of times invoked = no of requests made

● ServletConfig and ServletContext:

○ interfaces

○ ServletConfig:

■ Created by web.xml for each Servlet during servlet initialization.

■ ServletConfig object created per servlet class

■ This object will be only available after first request of a servlet and it gets

destroyed when destroy() is invoked.

■ Init-param has param-name and param-value tags inside servlet tag in

web.xml

○ ServletContext:

■ No matter servlets, only one ServletContext is created by web.xml while

deploying the application for the entire web application.

● RequestDispatcher

○ It is an interface.

○ It provides a facility to dispatch client requests to another web source or include

the response from another web source (html, jsp, servlet)

○ Has two methods: forward and include

○ Request dispatcher shares the request and response object to the forwarded or

included resources.

● Session Tracking

○ HttpSession:

■ Interface to create a session between the client and the server.

■ Has methods : getId(), setAttribute(), getAttribute(), invalidate()

● Servlet filter

○ Intercepts the request and response.

○ Request is preprocessed(like authenticate, encrypt, input validate) before

passing it on to the servlet.

○ Response is post processed before sending it to the client.

○ Add filter-mapping tag with filter-name and servlet-name to configure the filter.

JSP(Java Server Pages):

● Html + java code (to create dynamic web content)

● Unlike servlets, we don’t require a web.xml.

● Jsp separates the presentation logic and business logic using tags.

● Looks similar to html page, has extension of .jsp (can attach business logic in java code

in html within <% //java code here %> called scriptlet tags )

● JSP Life cycle:

○ Client sends request to web server for a jsp page

○ Web server forwards the request to the web container.

○ Web container has an engine called Jasper which translates the jsp to

(servlet)java class (jspInit() is invoked only for the first request, then _jspService()

for every request).

○ And this servlet will get converted to .class after compilation.

○ Web container creates object of servlet class.

○ The code in scriptlet tag/expression tag will be the code in service method and is

processed and the response is sent back to the client.

● Scripting elements:

○ <% %> : scriptlet tag

○ <%= %> : expression tag -> same as out.print();

○ <%! %> : declaration tag

■ used to declare the method/variables

■ will not be placed in service method

● Methods in jsp:

○ jspInit()

○ _jspService()

○ jspDestroy()

● out is an implicit object of JSPWriter(like PrintWriter in servlets) class.

● <%@ %> : is directive

○ @ page:

■ session is true by default

■ isErrorPage is by default false.

■ errorPage

■ import=””

○ @taglib

● Bean creation(create bean java and form html):

○ <jsp:useBean id=”” class=””>

○ <jsp:setProperty name=”nameOfTheObject(useBeanID)” property=”” param=””>

○ <jsp:getProperty name=”” property=””>

● JSTL(JSP Standard Tag Library)

○ Collection of jsp tags

○ Simplifying the web page development using jsp.

○ Types:

■ Core tags

■ Formatting tags

Spring Core:

● Loose coupling vs tight coupling:

○ Tight coupling:

■ Eg: having classes employee and address, address is initialized as soon

as employee obj is initialized. That means the address is dependent on

the employee and if any changes made to the address class might break

the employee class.

○ Loose coupling”

■ The above problem can be resolved by creating the obj of address class

and passed to employee obj (employee class: Employee(Address add))

and hence changes in address won’t make it break the code. But the

object should be created by the developer and passed to runtime.

○ What if runtime creates this object which can be used by the code, this is using

spring framework and this phenomenon is called IOC(Inversion of control).

○ So there should be a container where the objects can be created and used by the

code at runtime.

● Spring framework provides IOC.

● IOC can be achieved using:

○ Dependency injection:

■ Spring implements DI using:

● Spring container

● Config file: xml/java to know the name of the classes for which the

container will manage the objects.

■ Spring container can be created by making use of 2 classes:

● BeanFactory

● ApplicationContext

○ Autowiring:

■ Automatic DI is autowiring

■ Eliminates ref from property/constructor-arg

■ Has four modes(autowire=””):

● byName

● byType

● Constructor

● No

● Annotations:

○ StereoTypeAnnotations:

■ Used to mark classes so that class can be scanned by spring container.

■ Types:

● @Component: annotated class is a spring component

● @Service: service layer

● @Repository: database layer

● @Controller: web layer

○ Enabling and using annotations:

■ <context: annotation-config/> : activates the annotation to be used

■ <context: component-scan/> : extends the above

○ SPEL:used to refer

■ To a bean using “#{beanName}”

■ Bean field using “#{beanName.fieldName}”

■ Bean method using “#{beanName.methodName}”

Spring test:

● @RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations=”spring-config-path” or classes=class-file) [before test

class starts] and @Autowired above private Employee employee.

● Below are the few spring-test annotations:

○ @ContextConfiguration : used to load the location of spring bean config file.

○ @DirtiesContext(methodMode=MethodMode.) :

■ BEFORE_METHOD

■ BEFORE_CLASS

○ @ActiveProfiles(profiles=””) : Used to activate the profile for test cases.

○ @Transactional : used to run every test method in a transaction, with a default

strategy of rollback. It can be placed at method level or class level.

○ @Rollback : used to configure the default rollback strategy.

JSR-330(Java specification requests):

● @Inject is same as @Autowired but difference is required cannot be set to false in

@Inject (supports spring v3.0+)

● @Named is the same as @Component. Default scope is prototype but Singleton scope

in @Named used with spring. (@Singleton to make it singleton)

JSR-250:

● @Resource same as @Autowired but @Resource cannot be placed at constructor.

Spring ORM:

Module 1: Spring with jpa

● Benefits:

○ Datasource management: spring manages connection to db using datasource

○ Exception wrapping

○ Transaction management using @Transactional

○ Resource management

● Spring core with jpa integration:

○ org.springframework.orm.jpa

○ Ways to integrate:

■ LocalEntityManagerFactoryBean

■ LocalContainerEntityManagerFactoryBean

■ Obtaining an Emf from JNDI.

● Using transactional, you don’t need to use em.getTransaction.begin() and .commit() to

make changes in the db. Also instead of Autowired in emf, use @PersistenceContext in

em (emf is already defined in xml and em.createem() is being injected using this

annotation)

● @Transactional(value = “txManager”):

○ By default this is set to read/write

○ Attributes:

■ readOnly:

● To set it to readonly, add readOnly attribute and set it to true.

● @Transactional(value=”txManager”, readOnly=true)

■ timeout

● to implement the transaction timeout.

● @Transactional(value=”txManager”, timeout=3) //timeout is

3seconds.

● use Thread.currentThread().sleep(5000) //5 secs delay to cause

exception to check if it works.

■ rollbackFor = checkedException.class (mention this in both physical and

logical transaction else there will be a conflict)

● Type of transaction:

○ Local transaction: create emf and em and then use em.getTransaction().begin()

and .commit(). No container is required.

○ Global transaction(@Transactional(value=”txManager”)): container is required.

Transaction is maintained by the container itself using JTA(Java Transaction

API), no need to create emf manually. Inject em in class with this

container(@PersistenceContext) and no need to use em.getTransaction().begin()

and .commit()

● Types of PersistenceContext:

○ Transactional scoped persistence context (default for container managed em):

■ For every method call, a transaction begins and is destroyed after

changes are made to the database by the spring container.

○ Extended scope persistence context (default for non container managed em)

■ @PersistenceContext(type=PersistenceContextType.EXTENDED)

● Transaction Propagation:

○ Sharing the transaction scope of physical transaction in service layer with logical

transaction in DAO layer

○ Types:

■ MANDATORY: there should already be a transaction open.

■ NEVER: there should be no transaction open.

■ NESTED:

■ NOT_SUPPORTED: if already a transaction, it will pause it

■ REQUIRED

■ REQUIRES_NEW

■ SUPPORTS:

○ By default its REQUIRED:

■ If a transaction already exists, it will use that only else it will create a new

one.

■ @Transactional(propagation=Propagation.REQUIRED)

■ If any exception occurs at runtime whether in a logical transaction or

physical, since physical(service) and logical(dao) transaction is being

shared, both the transactions will be rolled back.

■ Since @Transactional is used at the service layer, we don’t need to

mention @Transactional in the dao layer. We can mention

@Transactional in the dao layer also along with the service layer, it

doesn’t matter, it will still consider the service layer sharing transaction to

the logical layer.

■ Rollback:

● If any of the logical transaction rollback, then it will cause the

complete physical transaction to rollback there by causing other

logical transactions to rollback.

● Unchecked: throw new RuntimeException(“”); in any one of the

logical layers will cause the complete physical layer to rollback.

● Checked: create a class dummyexception.class and throw a

checked exception using super(“”) extending Exception and try the

same in any one of the logical layers, this will not cause a rollback

in the physical layer. So for checked exceptions, use

@Transactional(value = “txManager”, rollbackFor =

checkedException.class) in both logical as well as physical layers.

Now if the logical layer rolls back, then the complete physical layer

will also be rolled back.

○ REQUIRES_NEW:

■ Even if a previous transaction exists, it will still create a new transaction.

Hence the transactional scope is not shared between physical and logical

transactions and is independent of each other.

■ Use @Transactional(value=”txManager”, propagation =

Propagation.REQUIRES_NEW) in the logical layer function for which you

want it to run independently even if any other logical layer rolls back.

■ Eg: use this at addDepartment and if addEmployee causes rollback,

addDepartment will still execute and add data into the department table.

Module - 2: Spring-JPA-Data

● It is a library/framework that adds an extra layer of abstraction on top of JPA provider.

● It is not a JPA provider

● It automates the DAO layer.

● Has Repository Abstraction feature (eliminates writing methods for each operation, dao

classes, creating queries, logic for pagination(how much data to be displayed in one

page) and auditing(creating log files) like spring jpa)

● DAO interface will only extend CrudRepository<EmployeeEntityBean, Integer> because

spring jpa data repository interface provides these functionality (CRUD) already and we

can use them.

● Marker Interface (empty interface) Repository <- CrudRepository <- Paging <-

JPARepository

● Custom Repository

○ Use @RepositoryDefinition(idClass=Integer.class,

domainClass=EmployeeEntity.class) in EmployeeDAO interface. Interface should

not extend CrudRepository<> to allow only certain methods that are selected.

○ Some methods:

■ EmployeeEntity save(EmployeeEntity en);

■ Iterable<EmployeeEntity> findAll();

■ EmployeeEntity findOne(Integer id);

■ delete(EmployeeEntity en);

○ Have to use @Transactional to make changes in db because we are not using

CrudRepository<>

○ By default, custom repository does not support DML operations, to enable it, use

@Modifying above the method

Code Quality Automation:

● Using sonarLint extension on eclipse helps us follow proper coding conventions.

● Code quality:

○ Types:

■ Static code analysis:

● Done without code execution.

● Deals with adherence with coding standards and presence of

potential bugs.

● It analyzes each and every bit of code.

● Since flaws are detected at an early stage, it is easy to change

before proceeding further.

● Tools: CheckStyle(works on src files), PMD(works on src files),

FindBugs(works on class file), SonarQube, Squale, Kalistick,

MetrixWare, Cast, PanOpticode.

■ Dynamic code analysis:

● Done during execution.

● Deals with behaviour of code during execution.

● Code only which interacts is executed on the fly.

● Since flaws are detected at a later stage, making changes in code

is tedious.

● Tools:

● SonarQube (static code analysis):

○ Open source quality management platform that performs:

■ Automated source code review

■ Constant source code technical quality check

■ Analysis of application source code findings.

○ SonarQube Architecture:

■ SonarQube Server:

● Web server

● Computer server

● Search server (elastic search)

■ SonarQube Database:

● Oracle

● Postgre sql

● Mysql

■ SonarQube plugins

■ SonarQube Scanner

○ SonarQube workflow:

■ Write the code on some IDE (let’s say eclipse) and push the code to

SCM(source code management - version control tools like git)

■ From scm, it will be pushed to a continuous integration tool (SonarQube

Scanner)

■ The code will be analyzed and the report will be published to the

SonarQube server which in turn will be stored in the SonarQube

database.

■ From the database, the report will be fetched by the IDE and displayed on

the console.

Spring MVC:

● MVC - Model View Controller

● Model - Business logic (POJOs)

● View - UI part

● Controller - directing requests/response client <--Controller--> model/view

● Static resource request life cycle: Client requests from file system using url and

login.html appears.

● Dynamic resource request life cycle: After username and password is entered, submit is

entered and request will go to the web container(web.xml //action=”urlPattern”) and will

redirect to Servlet/Controller Instance

● DispatcherServlet acts as a front controller in spring mvc.

● Flow: (Dynamic web project)

○ Login.jsp -> when we hit the submit, takes you to web.xml and searches for .html

in url-pattern, and finds class DispatcherServlet.

○ Add dispatcherServlet in servlet -> servletClass=”org.springframework….”

○ This will take you to a controller, can be identified by using annotation

@Controller at that class

○ In controller class:

■ @RequestMapping(value=”/validateLogin.html”, method =

RequestMethod.POST) before the function will take you to a particular

method handler.

■ Autowire service class and pass to service(@Service) which inturn will

pass to dao(@Repository).

■ Use @RequestParam(“name”) to take values from html

■ Use ModelAndView and setViewName and addObject to pass values to

the next page.

○ Create a file servletName-servlet.xml and add context:component-scan and

mvc:annotation-driven to activate annotation based project

○ Summary: Login.jsp(action) -> web.xml(dispatcherservlet) ->

servletName-servlet.xml (componentscan)-> LoginController.java(@Controller,

RequestMapping(value = “actionOfHtml”), ModelAndView, @RequestParam,

@Autowire) -> LoginService.java -> LoginDAO.java -> LoginController.java ->

Success.jsp/Failure.jsp.

○ LoginController -> Controller, LoginDAO -> Model, .jsp’s and html’s -> View.

○ Spring MVC has 2 types of web Application context:

■ Root/Parent web app context:

● Belongs to entire spring MVC application

● It is good to configure common spring bean configuration in the

root application context.

● In application there is only one root web application context.

■ Child/Servlet web application context:

● Belongs to dispatcher servlet

● An application can have multiple servlet/child web application

contexts.

● Configuration for controller and view resolver for views.

○ SpringMVC provides a tag lib to generate ui components

■ <% @TagLib uri=”http://www.springframework.org/tags/form”

prefix=”form”” >

■ Provides these ui components:

● Button

● Checkboxes

● Radiobutton

● input

● Label

■ Spring form tag is used to bind the form components to the model

exposed by the controller.

■ Use @ModelAttribute(“beanName”) to get the binded bean with form

● @ModelAttribute can be at parameter level (inside the method as

a parameter), or it can be at the method level(above the method)

● At method level:

○ It is executed before any handler method.

○ Populates the spring model before displaying the view.

○ Spring form validation: Use these in Bean class above attributes and add

<form:errors path=”attribute name”> in jsp page and @Valid while using

@ModelAttribute with BindingResult in controller class with result.hasErrors() if

any error is present.

■ @NotNull

■ @NotEmpty

■ @Range(min=, max=, message=”for custom message”)

■ @Future for date

■ @AssertTrue for Boolean

■ @DateTimeFormat(pattern=”dd-MMM-yyyy”)

○ Displaying all errors at once: (in jsp form), add

■ <springform:hasBindErrors name=”bean”>

■ <form:errors path=”*” cssClass=”error”/>

■ </spring:hasBindErrors>

○ Steps to create custom validation:

■ Create an annotation

■ Create a validator

■ Link annotation and validator using

@constraint(validatedBy=validatorName.class)

■ Use @validatorIntertface above attribute in bean class

○ Exception Handler:

■ @ExceptionHandler(value=Exception.class) followed by method

■ mv.setViewName(“exceptionPage.jsp”) and pass the

exception.getMessage to that page

○ Session:

■ ModelMap: map for entire model, use map.get(“employeeBean”), only this

will be passed to the next page but not to further pages.

■ HttpservletRequest req: req.getAttribute(“employeeBean”). This wont be

passed to next page, hence null will be the result

■ HttpSession ses: ses.getAttribute(“employeeBean”), this will also be null

■ So for this we will have to create a session to use any attribute for whole

application using @SessionAttributes(“employeeBean”) for one bean or

multiple beans(just separate it with commas)

Spring REST

● REST: Representational state transfer.

● REST uses HTTP protocol to establish interaction b/w producer and consumer.

● Producer produces the data(object) that is converted into json/xml and transferred to

consumer service through HTTP protocol. Any consumer can be a producer for another

service.

● Spring also supports creation of RESTful service using HttpMessageConverters and

annotations

● Some annotations:

○ @Controller

■ Used to mark the class as controller

○ @ResponseBody

■ Used as a method handler with @RequestMapping

■ This triggers HttpMessageConverters and converts object to json/xml and

passes the message

■ Set the configuration in @RequestMapping with parameter

produces=Mediatype.APPLICATION_JSON_VALUE for json and similarly

for xml.

○ @RestController

■ Equivalent to @Controller + @ResponseBody

■ Used to mark as controller and implicitly append every handler method as

@ResponseBody

○ @RequestBody

■ Used as a parameter of the handler method

■ It also triggers the HttpMessageConverters

■ Here the requested data (json/xml) are converted into java objects

○ @PathVariable

■ Picks the data from url and injects it to the handler method

■ Placed at the parameter level of request handler in the backing bean.

■ In url add /{variableName} and @PathVariable(“variableName”) can be

used to fetch data from url and used in the method.

○ ResponseEntity

■ It is the return type of handler method

■ Used to specify the status code, headers and body

■ Like @ResponseBody, this also triggers HttpMessageConverters and

converts the java objects into json/xml type based upon the configuration

type.

■ Some HTTP status codes:

● HttpStatus.OK

● HttpStatus.NOT_FOUND

● HttpStatus.CREATED

● HttpStatus.INTERNAL_SERVER_ERORR

● Recommended approach: Use @RestController above the class and ResponseEntity as

return type in method handler for Spring REST application.

● RequestMethod for Crud:

○ Add: POST

○ Get: GET

○ Update: PUT

○ Delete: DELETE

● RestTemplate:

○ It is an API template used to perform crud operations in console.

○ RestTemplate rt = new RestTemplate()

○ Methods:

■ Adding: rt.postForObject(uri, value, returnType)

■ Updating: rt.put(uri, value)

■ Display from db: rt.getForObject(uri, returnType)

■ Delete: rt.delete(uri with id)

○ To handle errors:

■ rt.setErrorHandler(new ResponseErrorHandler());

■ ResponseErrorHandler is an interface which has 2 methods:

● hasError(ClientHttpResponse arg) : to check for errors

○ eg: if arg.getStatusCode() ==

HttpStatus.INTERNAL_SERVER_ERROR, then boolean

flag = true and return flag and if return is true, it will

execute handleError()

● handleError(ClientHttpResponse): to handle if there is any error

○ just throw new RuntimeException(“error message”);

Spring Security:

● Terminologies:

○ Principal: user/device that needs access to application.

○ Authentication: login

○ Authorization: access to functionalities. Used to implement role based access.

● Ways to implement security in spring app:

○ Basic authentication using http

○ OAuth using https.

● Security is implemented in presentation and service layer

● Principals:

○ MSD_ADMIN (add, update and view)

○ MSD_DBA (update and view)

○ MSD_USER (view only)

● Add DelegatingFilterProxy in filter-class tag in web.xml

● In root.xml, import the security.xml file

● In security.xml file, add user authentication and authorization

● Types of authentication:

○ inMemory (static credentials in security.xml file)

○ Jdbc (load from the db)

○ LDAP (load from lookup server)

● Flow:

○ Web.xml is loaded which contains the security filter

○ Then root context is loaded where security.xml is imported for service and dao

layer

○ Security.xml has authentication and authorization.

○ When the user clicks on any of the links in index.jsp, the security filter is loaded

and the login page appears, login user/admin/dba and based on the

authorization, it’ll perform the required operation, else take you to access denied

page.

■ AccessDenied page can be custom as well.

● Just add access-denied-handler tag with url to error-page

attribute.

● The url should be configured in child-servlet.jsp using

mvc:view-controller since it does not go to the controller class.

● Mvc:view-controller has path and view-name as attributes

■ Custom login page can also be made.

● Just add the url and param names in form-login tag in

security.xml.

● Use mvc:view-controller to redirect the page to custom login

form.jsp

○ After successful login, a session is created and when the user clicks the logout

button, the session is removed (cache for that user is cleared).

○ Access methods in security.xml:

■ hasAuthority

■ hasRole

■ hasAnyRole

● Csrf: cross site request forgery. diabled = true in security.xml to prevent these kinds of

attacks to the application.

● Restrict multiple concurrent logins:

○ Add listener in web.xml (HttpSessionEventPublisher)

○ Add session-management tag and under that add max-session as 1 in

concurrency-control tag in security.xml

● To enable method level security:

○ Add global-method-security tag with secured-annotations and jsr250-annotations

attributes to enabled in security.xml.

○ Add beans with bean class LogService below that

○ In log service class, add @Secured({“ROLE_MSD_DBA”,

“ROLE_MSD_ADMIN”}) or add @RolesAllowed({“}) above the method.

■ @RolesAllowed is similar to @Secured, only thing is jsr250 has

introduced this rolesAllowed as an alternative.

■ @Secured / @RolesAllowed does not support spring security expression

language (cannot add hasRole(‘’) or hasAuthority(‘’) or hasAnyRole(‘’)).

○ So pre-post-annotations attribute is to be enabled in the global-method-security

tag in security.xml and use @PreAuthorize(“hasRole(‘’)”) in the Log class above

method.

■ @PreAuthorize(“”) only support spring security expression language

Maven:

● Build automation tool.

● Life cycle of build tool:

○ Validate: validate if project is correct and all necessary information is available.

○ Compile: compile source code of project.

○ Test: test compiled source code using unit testing frameworks.

○ Package: take compiled code and package into jar

○ Integration test:

○ Verify: run any checks on results of integration tests to ensure quality criteria are

met.

○ Install: install package into local repo for use as dependency in other projects

○ Deploy: done in the build environment, copies the final package to the remote

repo for sharing with other developers and projects.

● Maven:

○ open source build tool managed by apache software foundation.

○ Based on xml based POM(project object model). //pom.xml

● Setting up maven:

○ Download maven any version and store the folder in program files.

○ Go to system variables and add JAVA_HOME as variable name and path for

jdk1.8 as value

○ Add M2_HOME in system variables with value as path to maven folder

○ Add bin folder path to Path(User Variables).

● Running the first program (Maven cmd):

○ Open cmd and locate to MavenWorkspace

○ “mvn archetype:generate -DgroupId=com.company.app -DartifactId=my-app

-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false”

■ A folder my-app will be created with src(has main and test folder) and

pom.xml

○ go to my-app folder and run “mvn compile” (will compile the main folder files)

■ A folder target is created with classes folder which has class files

○ “mvn test-compile” (will compile the test folder files)

■ In the folder target, a test-classes folder is created which has test classes.

○ “mvn test”

■ This will run the test files

○ “mvn package”

■ Package it to a jar file, will be present in target folder (SNAPSHOT.jar)

● Running maven on eclipse:

○ Create maven project with groupId as package name and artifactId as project

name.

○ Go to configure build path -> libraries and add jdk 1.8 library.

○ Add <maven.compiler.source>1.8</maven.compiler.source> and

<maven.compiler.target>1.8</maven.compiler.target> inside properties tag. This

will help force the compiler to use the jdk 1.8 version for src and target.

○ Run project as maven build.

■ Type, “compiler:compile” in goals to compile the java files

■ Type, “compiler:testCompile” in goals to compile the test files.

■ Type, “jar:jar” in goals to package the project into a jar file.

● Types of POM:

○ Super pom:

■ Parent pom for all the child pom’s.

○ Minimal pom:

■ This will inherit all properties from super pom other than its own.

■ Minimum requirements: should have projectroot, modelVersion, groupId,

artifactId.

○ Effective pom:

■ Consolidated pom file which shows overall configuration details.

(combining the super pom and the minimal pom)

● Maven repository:

○ Stores set of artifacts which are used by maven during dependency resolution for

a project

○ An artifact is bundled as a jar file (can also be war, ear files).

○ Types:

■ Local repo (.m2 folder in user folder local drive)

■ Remote repo (located inside organization’s network)

■ Central repo ( https://repo1.maven.org/maven2/ )

● Dependency:

○ Some tags that are present inside this tag:

■ groupId

■ artifactId

■ Version

■ Scope

■ Type

■ systemPath

○ To add a new dependency, go to https://mvnrepository.com and search for a

dependency, copy it and paste it in the pom.xml dependencies tag.

○ Transitive dependency:

■ Used to overcome drawbacks when dependencies mentioned in pom are

not used in the application. (spring has many modules like bean, aop etc)

○ Dependency mediation:

■ Used to choose one version among multiple versions of same framework

present in pom.xml

○ Dependency management:

■ Used to inherit properties in child pom from root pom.

○ Excluded dependencies:

■ Used to exclude unnecessary jar files from any framework while importing

it.

■ Use <exclusion> inside dependency in pom.xml

○ Optional Dependencies:

■ If you make a dependency optional, it not only saves memory, it will also

control the use of actual dependency in the project

■ Inclusion of wrong dependencies may also lead to violation of license

agreement and causes issues in classpath, etc.

■ In dependency, use the <optional> tag which has true value.

○ Scope:

■ Defined when a particular dependency needs to be used.

■ Types of scopes:

● Compile

○ default scope and it indicates that all dependencies are

available in classpath.

● Provided

○ Is it mostly like compile, it is not transitive and it indicates

that dependency to be provided by jdk/web

server/container.

● Runtime

○ Dependency is not required for compilation and will be

required only for execution.

● Test

○ It is not transitive and dependency is only required for test

compilation and execution phases.

● System

○ It is required to provide the system path

○ Flow:

■ Dependency is checked in local repo, if not found then goes to central

repo and downloads to local repo, if not found then if remote repo exists

then goes to remote repo and downloads to local repo else error message

is generated.

○ Plugin:

■ Core plugins:

● Clean, compiler, deploy, failsafe, install, resources, site, surefire,

verifier

■ Packaging types:

● ear, ejb, jar, rar, war, app-client/acr

■ Reporting plugins

● changelog, changes, checkstyle, soap, dock, javadoc,

project-info-reports, surefire-reports

○ Plugin tools:

■ Default maven tools:

● ant, antrun, archetype, assembly, dependency, help, plugin,

release, repository, scm, scm-publish, stage.

Spring Boot:

● Automating the application development architecture by just mentioning what we want

from it. (create web application with jpa).

● Spring boot is a maven based application.

● Microservice: a module that can be exposed/used by another application.

● Creating boot application:

○ Go to https://start.spring.io/

○ Configure it, select spring web in dependencies and download the structure.

○ Open eclipse and import maven existing projects and wait for it to build.

○ Create a controller with @RestController and produces

MediaType.APPLICATION_JSON_VALUE in @RequestMapping.

○ Return something in the function and run it.

○ If port error occurs, go to application.properties and type “server.port = 8095”

● Main class has @SpringBootApplication, equivalent to @Configuration +

@EnableAutoConfiguration + @ComponentScan which manages all the root and child

packages of the application.

○ Can add more config files using @Import(value=MyBeansConfig.class) for java

config and @ImportResource(locations=”c:/users/.../beans.xml”) for xml.

○ @EnableAutoConfiguration: if no db config is defined, then it will try to read it

from application.properties and auto configure it.

● SpringApplication.run(App.class, args);

● Ways to run:

○ clean install spring-boot:run

○ java -jar

● Types of container:

○ Tomcat is default

○ Jetty

■ To use this, add exclusions -> exclusion to tomcat in pom.xml and add

jetty(org.springframework.boot(group) -> spring-boot-starter-jetty(artifact))

dependency in pom.xml.

● Content negotiation:

○ Getting desired format as output (json/xml) from the microservice using url

○ 2 ways to get the output:

■ Url extension based (/getDetails.xml or /getDetails.json)

■ Url parameter based (/getDetails?dataFormat=xml or

/getDetails?dataFormat=json)

○ Steps to create url extension/ parameter name:

■ Configure the bean:

● Create custom ContentNegotiationManager

● Create bean.xml and create a bean with id

contentManagerFactory with class

org.springframework.web.ContentManagerFactoryBean having

properties:

○ favorParameter -> false (true for parameter name)

■ If true, add parameterName -> dataformat

■ add mediaTypes -> map(“xml or anything”,

“application/xml”), map(“json”, “application/json”)

○ favorPathExtension -> true ( true for url extension)

○ ignoreAcceptHeader -> false

○ useJaf (Java activation framework) -> true

○ defaultContentType -> application/xml or json to set the

default value when nothing is specified.

● mvc:annotation-driven with content-negotiation-manager to

contentNegotationManager

■ Or configure the Java class

● Ass @Configuration

● Extend with WebMvcConfigurationSupport

● Override 2 methods

○ configureDefaultServletHandling(DefaultServletHandlerCo

nfigurer configurer), and enable it using

configurer.enable();

○ configureContentNegotiation(ContentNegotiationConfigure

r configurer) and configurer will have methods like

■ .favorParameter(true)

■ .favorPathExtension(false)

■ .mediaType(“xml”,

MediaType.APPLICATION_XML) and methods

similar to xml config property names.

■ @ImportResource in main class with locations as property or

@Import(spring.class) for java config

■ @XmlRootElement in Bean class

■ In controller, add produces = {“application/xml”, “application/json”}

● Configure jpa (add dependencies jpa and download project from start.spring.io and add

mysql connector dependency in pom.xml):

○ Go to application.properties

■ spring.datasource.url=

■ spring.datasource.username=root

■ spring.datasource.password=root

■ auto=true

■ spring.jpa.show-sql=true

■ Spring.jpa.properties.hibernate.dialect

● Hibernate Bean ValidationAPI:

○ Hibernate is already enabled in spring boot application.

○ This is a request body validation not a form validation. ie., @Valid

@RequestBody errors

○ For custom validation, just create a ValidationMessages.properties in resources

● Profiling

○ Can be used with any component or configuration (stereotype)

○ @Component @Profile(“dev_prof”) and activate it using

spring.profiles.active=dev_prof in either run as configuration argument vm

tab(-Dspring...active=dev_prof) or in application.properties file

● Runners:

○ Used to perform any task just after all the beans and application context is

created in spring boot application

○ 2 types of runner:

■ ApplicationRunner : this would be first in executing compared to CLR

● Will have run(ApplicationArgument arg) method

■ CommandLineRunner: run(String... arg)

● Yaml : yet another markup language

○ Similar to application.properties, application.yml can be used to configure

○ Eg:

■ server:

■ port: (space not tab, and this is similar to server.port=8008 in

application.properties)

● Testing:

○ Junit cant be used to test controller class since the methods can only be

accessed when we hit the specified url present in the requestmapping.

○ Service layer: junit, spring testing framework

○ Controller layer integration test: junit, spring mockmvc test framework

○ Controller layer unit test: junit, mockito, spring mockmvc test framework.

● Packaging into war:

○ Web configuration and compiled classes and interfaces into one package as war.

○ Package into war and publish on git (continuous integration)

○ Git -> jenkins (will compile, test and generate a deployment ready product from

the war) and deploys(continuous deployment)

○ Steps to create a war:

■ Provide implementation for SpringBootServletInitializer which has

configure() method.

■ Change the packaging to war in pom.xml: <packaging>war</packaging>

■ Add scope as provided to tomcat server in pom.xml. (giving the

dependencies to the deployment platform to use it)

Node js:

● It is a JS server.

● ES is a scripting language used to standardize javascript.

● Latest version of ES is the 10th edition called ES2019.

● ES2015/ES6, prior to it, we used to write var name = “John” and function(a, b){}. But

after ES6, let name = “John” and (a, b) => {}

● ES6 is not directly understood by browsers, it has to first be converted to ES3. This

process is called transpiling. (Bebl is a tool used to do this)

● Node.js is an open source, cross platform JS runtime environment.

● Node js is used to write server side javascript unlike angular that is client side scripting.

● Steps to run first node application:

○ Download node js

■ In cmd, node -v or node --version (v12.14.0)

○ Download vs code.

○ Create a helloworld.js

○ Open cmd, navigate to that folder and type node filename.js

● Modules

○ It is a collection of one or more js files which contains functions to serve simple or

complex functionality.

○ They are also called packages.

● Types of modules:

○ core/built in module:

■ By default node.js has set of modules to provide basic functionalities

■ Eg: const os = require(“os”) and use os.hostname(), os.platform(), etc..

■ Some core modules:

● Util:

○ Converting and validating values

○ util.format(“%s”, “john”);

● Path

○ To interact with directories and file path

○ path.isAbsolute(“path/data.json”); //true

● Fs

○ Interact with the physical file system. To perform IO

operations like create file/ read file/ delete file/ update file.

○ fs.writeFile(“filename”, data, (err) => {});

○ fs.readFile(“filename”, (err, data) => {});

● Url

○ New URL(“link”) parses the string into href, pathname,

host, protocol, port.

○ url.format({protocol:””, host:, port:, pathname:}).toString();

will give the href

● Querystring:

○ querystring.parse(“name=John&is=101”) to convert query

string to json object

○ querystring.stringify({id:, name:””}); to convert json to

querystring.

● Child_process

○ It facilitates child process creation to leverage parallel

processing on multi core cpu based systems.

○ Has 3 streams: stdin, stdout, stderr

○ Import child_process

○ .exec(“ls”, (error, stdout, stderr) => {}); runs the command

in the console

● Http

○ Helps us make http requests, can create a http server that

listens on any particular port and sends the response back

to the client.

○ http.get(url, (resp) => {//getting data resp.on(“data”,

(chunk) => {}) //after processing data resp.on(“end”, () =>

{log(data)})});

○ http.request(): used to make all types of requests(get, post,

put, delete).

○ http.createServer((req, res) => {if req.url == “/abc”

{http.get(url, (resp) => {//res.write is used to write in

webpage and resp.on is used to get data from the model

})}}).listen(4200, console.info(“listening on 4200 port”));

// use http://localhost:4200/abc

○ External/third party module:

■ Using npm install modulename

○ User defined module

■ We can create our own modules as well by just importing it using require

function.

Spring Cloud

● Ecosystem to make the microservice ready for cloud/cloud enabled.

● Architecture :

○ Monolithic architecture (single unit):

■ Single application for functionalities offered

■ Has one large database

■ Customer(single application) ->add/ update/fetchDetails(single dao/repo)

-> customerDB(single DB)

■ Has one dao/repo for all operations, design is low on cohesion.

■ So, as the application grows, fixing bugs and maintenance becomes

difficult.

■ Failure of one point could affect the whole system.

■ Suitable for applications which are steady, not fast growing and does not

require frequent changes.

○ SOA Architecture (coarse grained)

■ Service oriented architecture

■ Multiple instances of repo/dao are present, so even if one fails, another

can be used.

■ Ribbon Load balancer is present that helps use scale out the services.

■ Web app/mobile app/desktop app -> load balancer -> servers -> DB

■ Not able to take care of cohesion, loose coupling, automation

■ Challenges: continuous integration, rapid changes, deployment. And this

is where microservice comes to rescue.

○ Microservice architecture (fine grained).

■ Evolution of SOA

■ Can communicate from service to service, service to client

■ Principle:

● Cohesion: single responsibility high cohesion

● Autonomous : loose coupling and independent deployment

● Business domain centric: take similar functions that are related

and define them in a single component

● Resilience

● Observable: observe logs and errors by developers

● Automation: focuses upon having tools for easing out deployment,

regression testing, giving feedback for failed test cases,

continuous integration tools.

■ 12 factors that should be considered while building an application (The

Twelve-Factor App)

■ Challenges:

● Quick setup is needed

● Automation: as there are a number of smaller components, the

developer needs to automate the build, monitoring and deploying.

● Visibility

● Bounded context: deciding boundaries of a microservice is a

challenging task.

● Configuration management: developers will need to manage

configurations of thousands of components.

● Dynamic scale up and scale down

● Pack of cards: the microservice should be fault tolerant, since if

one bottom microservice fails, the others might get affected from

it.

● Debugging

● Consistency

■ This is where microservice design patterns come to rescue

■ Microservice design patterns

● Decomposition patterns

● Database per service pattern

● Api gateway pattern

● Client side and server side discovery

● Messaging and remote procedure invocation patterns

● Single service and multiple services per host pattern

● Cross cutting concerns patterns

● Testing patterns

● Circuit breaker: it acts as a vigilante and monitors for faults. Let's

say after a request is being made by the user, a thread is created

and if any fault occurs, this circuit breaker will stop the thread and

not make the thread wait for a longer time hence reducing the

response time of a request.

● Observability patterns

● UI patterns

● https://microservices.io

● Spring cloud is a big project consisting of child projects(like azure, alibaba, aws, etc..

Spring Cloud). Each project is independently released as part along with spring cloud.

● Releases in spring cloud are not in version number but in trains.

● Releases (names of london tube stations in alphabetical order):

○ Angee (first release)

○ Brixton

○ Camden

○ Dalston

○ Edgware

○ Finchley

○ Greenwich

○ Hoxton

● Eureka is a server which maintains the service registry (containing instances with ip

address) [netflix-eureka-server (greenwich)]

● Creating a Eureka server:

○ Create a spring boot project with eureka server dependency (start.spring.io)

○ Go to application.properties and paste the below:

■ server.port = 7090

■ eureka.client.serviceUrl.defaultZone:http://localhost:7090/eureka/

■ eureka.client.register-with-eureka=false

■ eureka.client.fetch-registry=false

○ Add @EnableEurekaServer in the main class and run it.

○ Type localhost:7090 to view the Eureka server.

● Creating a Eureka producer (microservice):

○ Create a spring boot project with eureka discovery client dependency

(start.spring.io)

○ Add the below dependency in the pom.xml file for(@RestController).

■ <dependency>

■ <groupId>org.springframework.boot</groupId>

■ <artifactId>spring-boot-starter-web</artifactId>

■ </dependency>

○ Add the dao, bean and controller with employee details and functions like

addEmp, fetchEmp and updateEmp.

○ Add @EnableDiscoveryClient or @EnableEurekaClient in the main class

○ Add the below in application.properties:

■ server.port = 7091 #new port for producer

■ eureka.client.serviceUrl.defaultZone=http://localhost:7090/eureka #7090

is the eureka server port

○ Create a new file called bootstrap.properties and add the below:

■ spring.application.name=cst_emp_producer

○ Run the application and type localhost:7090 to view this instance on the eureka

server.

● Creating a Eureka Consumer app:

○ Create a spring boot project with eureka discovery client dependency

(start.spring.io)

○ Add the below in application.properties

■ server.port = 7092

■ eureka.client.serviceUrl.defaultZone=http://localhost:7090/eureka

■ spring.cloud.service-registry.auto-registration.enabled=false

○ Create a file called bootstrap.properties and add the below:

■ spring.application.name=cst_employee_consumer

○ Add the below dependency in the pom.xml file for(@RestController).

■ <dependency>

■ <groupId>org.springframework.boot</groupId>

■ <artifactId>spring-boot-starter-web</artifactId>

■ </dependency>

○ Add @EnableEurekaClient in the main class

○ In the controller

■ Autowire DiscoveryClient from cloud package

■ use discoveryClient.getInstances(“producerName”).get(0) to get ip and

port of the producer ,returns ServiceInstance

■ Use serviceInstance.getUri.toString() to get the url and append it with the

url of function (eg: url += “/emp/controller/getDetails”)

■ Use the rest template, perform the necessary operation and return the

same.

○ Run the application and test it using localhost:7092/fetchAllEmployees

● A rest client open feign can also be created by adding open feign dependency in spring

boot application.

Agile Methodology

● SDLC: Software development life cycle

● Requirement is different for different complexities

● Accenture needs to identify how to attend each of this requirement:

○ Your project may be on Maintenance, testing, enhancement, development

○ Domain

○ Requirements may be based on technology, environment, domain.

○ ADS (accenture development suite) : Process -> Project -> Phase ->

Artifact/Deliverable

● SDLC:

○ Approach that’s available to develop a requirement.

○ It’s a process that consists of a series of planned activities to develop a software

product.

○ Requirement gathering -> analysis -> design -> implementation/coding -> testing

-> evolution.

○ Has different models:

■ Waterfall methodology :

● each phase must be completed before moving to the next phase,

without any overlap in the phases.

■ Spiral model:

● Iterative development process model + sequential linear

development model.

● Has 4 phases and repeatedly passes through these phases in

iterations called spirals:

○ Identification

○ Design

○ Construct or build

○ Evaluation and risk analysis

■ V-shape model:

● Emphasizes verification and validation of the product.

● Parallel execution of planning and development of the product.

● Spends half of the total development effort on testing.

■ Agile methodology:

● Alternative to waterfall model

● Helps teams respond to unpredictability through incremental,

iterative work cadences known as sprints.

● Iteration: doing several iteration on the same requirement to

understand the complexity which helps us know more about the

architecture, latency, character encoding and response time

● Incremental: adding new features in terms of increments.

● Frameworks:

○ Lean

○ Kanban

○ Scrum

○ Extreme programming(XP)

● Needs:

○ Ability to manage priorities

○ Increased productivity

○ Improved project visibility.

● Agile is value driven whereas waterfall is plan driven

● 4 main values:

○ Individuals and interactions

○ Working software

○ Customer collaboration

○ Responding to change

DevOps

● Development operations

● Devops brings in rapid, high quality delivery of standard and custom applications

enabled by automation of build, test and deployment.

● To be considered:

○ Security

○ Time to market

○ Throughput

○ Cost

● Accenture definition of devops:

○ The engineering discipline of optimizing both development and operations to

enable the realisation of business goals through rapid feedback, stable,

responsive and flexible IT.

● The History Of DevOps

● Fundamental practices of devops:

○ Idea, plan, design, build, deploy, test, release, operate

ajay wants to define registercashback

ajay wants to create

ajay has written below

ajay has used @controller and @autowired

ajay understands that its a good 

ajay wants to create a page

ajay wants to display the list of employee

Consider below code snippet

ajay wants to display carrear





Basics:

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-oriented and 

secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. 

James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a 

registered company, so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a 

platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based applications. 

These are traditional software that we need to install on every machine. Examples of standalone 

application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone 

applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application. 

Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web 

applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise 

application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is 

used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android 

and Java ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition) It is a Java programming platform. It includes Java programming 

APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like 

OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, 

Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built 

on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API.

JVM (Java Virtual Machine) is an abstract machine. It is a 

specification that provides runtime environment in which java 

bytecode can be executed.

A Java virtual machine is a virtual machine that enables a computer to run Java programs as well as 

programs written in other languages that are also compiled to Java bytecode.

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM Architecture

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java 

program, it is loaded first by the classloader. There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. 

It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package 

classes, java.net package classes, java.util package classes, java.io package classes, java.sql package 

classes etc.

Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System 

classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.

System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the 

classfiles from classpath. By default, classpath is set to current directory. You can change the 

classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

2) Class(Method) Area

Class (Method) Area stores per-class structures such as the runtime constant pool, field and method 

data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method 

invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method 

invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently 

being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

A virtual processor

Interpreter: Read bytecode stream then execute the instructions.

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code 

that have similar functionality at the same time, and hence reduces the amount of time needed for 

compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual 

machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with another 

application written in another language like C, C++, Assembly etc. Java uses JNI framework to send 

output to the Console or interact with OS libraries.

JDK contains JRE + development tools. The Java Development Kit (JDK) is a software development 

environment which is used to develop java applications and applets. It physically exists. 

The JRE is the on-disk system that takes your Java code, combines it with the necessary libraries, and 

starts the JVM to execute it JRE is the container, JVM is the content

Java Variables

A variable is a container which holds the value while the Java program is executed. A variable is 

assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and 

static.

A variable is the name of a reserved area allocated in memory.

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable 

only within that method and the other methods in the class aren't even aware that the variable 

exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance 

variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among 

instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a 

single copy of the static variable and share it among all the instances of the class. Memory allocation 

for static variables happens only once when the class is loaded in the memory.

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two 

types of data types in Java:

Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and 

double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

List of Java Keywords

A list of Java keywords or reserved words are given below:

1. abstract: Java abstract keyword is used to declare an abstract class. An abstract 

class can provide the implementation of the interface. It can have abstract and 

non-abstract methods.

2. boolean: Java boolean keyword is used to declare a variable as a boolean type. 

It can hold True and False values only.

3. break: Java break keyword is used to break the loop or switch statement. It 

breaks the current flow of the program at specified conditions.

4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data 

values.

5. case: Java case keyword is used with the switch statements to mark blocks of 

text.

6. catch: Java catch keyword is used to catch the exceptions generated by try 

statements. It must be used after the try block only.

7. char: Java char keyword is used to declare a variable that can hold unsigned 

16-bit Unicode characters

8. class: Java class keyword is used to declare a class.

9. continue: Java continue keyword is used to continue the loop. It continues the 

current flow of the program and skips the remaining code at the specified 

condition.

10. default: Java default keyword is used to specify the default block of code in a 

switch statement.

11. do: Java do keyword is used in the control statement to declare a loop. It can 

iterate a part of the program several times.

12. double: Java double keyword is used to declare a variable that can hold 64-bit 

floating-point number.

13. else: Java else keyword is used to indicate the alternative branches in an if 

statement.

14. enum: Java enum keyword is used to define a fixed set of constants. Enum 

constructors are always private or default.

15. extends: Java extends keyword is used to indicate that a class is derived from 

another class or interface.

16. final: Java final keyword is used to indicate that a variable holds a constant 

value. It is used with a variable. It is used to restrict the user from updating the 

value of the variable.

17. finally: Java finally keyword indicates a block of code in a try-catch structure. 

This block is always executed whether an exception is handled or not.

18. float: Java float keyword is used to declare a variable that can hold a 32-bit 

floating-point number.

19. for: Java for keyword is used to start a for loop. It is used to execute a set of 

instructions/functions repeatedly when some condition becomes true. If the 

number of iteration is fixed, it is recommended to use for loop.

20. if: Java if keyword tests the condition. It executes the if block if the condition is 

true.

21. implements: Java implements keyword is used to implement an interface.

22. import: Java import keyword makes classes and interfaces available and 

accessible to the current source code.

23. instanceof: Java instanceof keyword is used to test whether the object is an 

instance of the specified class or implements an interface.

24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed 

integer.

25. interface: Java interface keyword is used to declare an interface. It can have 

only abstract methods.

26. long: Java long keyword is used to declare a variable that can hold a 64-bit 

integer.

27. native: Java native keyword is used to specify that a method is implemented in 

native code using JNI (Java Native Interface).

28. new: Java new keyword is used to create new objects.

29. null: Java null keyword is used to indicate that a reference does not refer to 

anything. It removes the garbage value.

30. package: Java package keyword is used to declare a Java package that includes 

the classes.

31. private: Java private keyword is an access modifier. It is used to indicate that a 

method or variable may be accessed only in the class in which it is declared.

32. protected: Java protected keyword is an access modifier. It can be accessible 

within the package and outside the package but through inheritance only. It 

can't be applied with the class.

33. public: Java public keyword is an access modifier. It is used to indicate that an 

item is accessible anywhere. It has the widest scope among all other modifiers.

34. return: Java return keyword is used to return from a method when its execution 

is complete.

35. short: Java short keyword is used to declare a variable that can hold a 16-bit 

integer.

36. static: Java static keyword is used to indicate that a variable or method is a class 

method. The static keyword in Java is mainly used for memory management.

37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure 

portability.

38. super: Java super keyword is a reference variable that is used to refer to parent 

class objects. It can be used to invoke the immediate parent class method.

39. switch: The Java switch keyword contains a switch statement that executes 

code based on test value. The switch statement tests the equality of a variable 

against multiple values.

40. synchronized: Java synchronized keyword is used to specify the critical sections 

or methods in multithreaded code.

41. this: Java this keyword can be used to refer the current object in a method or 

constructor.

42. throw: The Java throw keyword is used to explicitly throw an exception. The 

throw keyword is mainly used to throw custom exceptions. It is followed by an 

instance.

43. throws: The Java throws keyword is used to declare an exception. Checked 

exceptions can be propagated with throws.

44. transient: Java transient keyword is used in serialization. If you define any data 

member as transient, it will not be serialized.

45. try: Java try keyword is used to start a block of code that will be tested for 

exceptions. The try block must be followed by either catch or finally block.

46. void: Java void keyword is used to specify that a method does not have a return 

value.

47. volatile: Java volatile keyword is used to indicate that a variable may change 

asynchronously.

48. while: Java while keyword is used to start a while loop. This loop iterates a part 

of the program several times. If the number of iteration is not fixed, it is 

recommended to use the while loop.

OOPs (Object-Oriented Programming System)

Object-Oriented Programming is a methodology or paradigm to design a program 

using classes and objects. It simplifies software development and maintenance by 

providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Object: Any entity that has state and behavior is known as an object.

Class:Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual 

object.

Inheritance: When one object acquires all the properties and behaviors of a parent 

object, it is known as inheritance. It provides code reusability. It is used to achieve 

runtime polymorphism.

Polymorphism: If one task is performed in different ways, it is known as 

polymorphism.

Abstraction: Hiding internal details and showing functionality is known as 

abstraction. 

Encapsulation: Binding (or wrapping) code and data together into a single 

unit are known as encapsulation

Coupling

Coupling refers to the knowledge or information or dependency of 

another class. It arises when classes are aware of each other.

Cohesion

Cohesion refers to the level of a component which performs a single welldefined task. A single well-defined task is done by a highly cohesive 

method. The weakly cohesive method will split the task into separate 

parts.

------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------

---------------- ------------------------ ------------------------- --------------------------

1.Spring Boot :

 

Spring Boot is an open-source micro framework maintained by a company called 

Pivotal. It provides Java developers with a platform to get started with an auto configurable 

production-grade Spring application

 Or

Spring Boot makes it easy to create stand-alone, production-grade Spring based 

Applications that you can "just run".

 Or

Spring Boot is a Spring module which provides RAD (Rapid Application Development) 

feature to Spring framework.

It is used to create stand alone spring based application that you can just run because 

it needs very little spring configuration.

2. what is DispatcherServlet and how it works?

DispatcherServlet acts as front controller for Spring based web applications. It creates 

DispatcherServletWebApplicationContext and this will instantiates the backend controller and 

based on the response

from the backend controller it identifies the view and send it to the client.(dispatches requests to 

the handler methods

present in controller class).

3.Rest Template :

Rest Template is used to create applications that consume RESTful Web Services. You 

can use the exchange() method to consume the web services for all HTTP methods.

0r

RestTemplate. is the central class within the Spring framework for executing 

synchronous HTTP requests on the client side. Like Spring JdbcTemplate, 

RestTemplate. is also a high-level API, which in turn is based on an HTTP client 

 or 

Rest Template is used to create applications that consume RESTful Web Services. You 

can use the exchange() method to consume the web services for all HTTP methods. The 

code given below shows how to create Bean for Rest Template to auto wiring the Rest 

Template object.

4. Bean autowriting concept

Spring container is able to autowire relationships between collaborating beans. ... This 

is called spring bean autowiring.

5.@Component is used for? 

@Component is an annotation that allows Spring to automatically detect our custom 

beans. In other words, without having to write any explicit code, Spring will: Scan our 

application for classes annotated with @Component. Instantiate them and inject any 

specified dependencies into them

6. what is maven and sonarqube

Maven is a project management tool. It is based on POM (Project Object 

Model).

or

The ability to execute the SonarQube analysis via a regular Maven 

goal makes it available anywhere Maven is available (developer build, CI 

server, etc.), without the need to manually download, setup, and 

maintain a SonarQube Runner installation

 or

Maven is a powerful project management tool that is based on POM (project object 

model). It is used for projects build, dependency and documentation. It simplifies 

the build process like ANT. ... In short terms we can tell maven is a tool that can be 

used for building and managing any Java-based project. 

Sonarqube: SonarQube is an open-source tool for continuous code inspection. It 

collects and analyzes source code and provides reports on the code quality of your 

projects. With regular use, SonarQube guarantees a universal standard of coding 

within your organization while ensuring application sustainability.

8.Which model is used in spring mvc?

In Spring MVC, the model works a container that contains the data of the 

application. Here, a data can be in any form such as objects, strings, information from 

the database, etc. It is required to place the Model interface in the controller part of 

the application. 

 Or

A Spring MVC is a Java framework which is used to build web applications. It follows 

the Model-View-Controller design pattern. It implements all the basic features of a 

core spring framework like Inversion of Control, Dependency Injection. 

7.What is spring

Spring is an open source development framework for enterprise Java. ... Basically

Spring is a framework for dependency-injection which is a pattern that allows to build 

very decoupled systems. Spring is a good framework for web development.

 Or

It is a lightweight, loosely coupled and integrated framework for developing 

enterprise applications in java.

8.For which technology is a JSP alternative for? 

JSP provided by Sun Microsystems (now oracle) is an alternative for Microsoft’s ASP 

(Active Server Pages).

9.What are the different types of JSP tags? 

(Scriplet,directive,declaration tags)

JSP tags: 

• Presentation tags

• JSP standard tags

• Custom tags

JSP standard tags:

• Directive tags

• Standard action tags

• Scriplet tags

Directive tags:

• Page directive

• Include directive

• Taglib directive

Standard action tags:

• Forward action

• Include action

• Use bean action

Scriplet tags:

• Scriplet tag

• Expression tag

• Declaration tag 

10.Explain life cycle of a JSP? 

JSP lifecycle has 7 phases 

1. Translation 

2. Compilation 

3. Loading 

4. Instantiation 

5. Initialization using jsp Init() method 

6. jspService() method invocation 

7. Jsp destroy() method invocation.

*JSP life cycle:- client request-webs server for jsp

web server-frwds-req-to-web container

jasper engine in container converts jsp to java class(servlet)

servlet compiled to .class

web container creates obj of servelt class

req is processed by service() and response is sent to client

11. What is JSP technology used for? (Why we use JSP)

For creating web application.

 Or

Java Server Pages technology (JSP) is a server-side programming language used 

to create a dynamic web page in the form of HyperText Markup Language (HTML). 

It is an extension to the servlet technology.

A JSP page is internally converted into the servlet. JSP has access to the entire 

family of the Java API including JDBC API to access enterprise database. Hence, 

Java language syntax has been used in the java server pages (JSP). The JSP pages 

are more accessible to maintain than Servlet because we can separate designing 

and development. It provides some additional features such as Expression 

Language, Custom Tags, etc.

12.What is meant by method overloading?

Method overloading refers to the process of creating multiple methods all with 

the same name. It is used to achieve virtual polymorphism in java.

13.What is the difference between method overloading and method 

overriding? 

Method Overloading Method Overriding

It would be performed within the same 

class.

It would occur in two classes which 

have parent-child relationship.

Number of parameters should be 

different or datatypes of parameters 

should be different or the order of 

occurrence of the parameters should 

be different.

Number of parameters, datatypes of 

parameters, order of occurrence of the 

parameters must be same.

It is an example of compile time 

polymorphism.

It is an example of run time 

polymorphism.

Return type of the methods can be 

different.

Overriding method should have same 

return type as that of the parent or it 

can have co-variant return type.

It is used to increase the readability of 

the program.

It is used to modify the method in the 

child class to suit its specific 

requirements which is already provided 

in the parent class.

14.Spring mvc implementation

A Spring MVC is a Java framework which is used to build web 

applications. It follows the Model-View-Controller design pattern. It 

implements all the basic features of a core spring framework like 

Inversion of Control, Dependency Injection.

*Inversion of Control: it is the process of creating objects by giving 

control to spring.

*Dependency Injection:are of two types setter and getter injections

type of dependency injection in which the framework injects the dependent objects 

into the client using a setter method

The container is injecting a method, such as a getter method, rather than a reference or primitive 

as in Setter Injection.

{ Pojo stands for plan old java objects: it will have it’s own behaviour along 

with some variables setter & getters}

15.what is meant by model, view and controller?

Model :- it includes POJOs(class in which we have variables declare and getter 

and setters methods.)/DTO(data transmission object), business logic and 

database related operations.

View :- it include UI and it presents data to the end user.

Controller :- it acts as a link/bridge between view and model. It wil take request 

from view and passes it to model and presents

the obtained result/data to the view. Simply controller gives model to view.

 or

→MVC stands for Model view controller

1.It is an architecture which tells that model part should communicate with 

database

2.View part should communicate with the client where as controller should 

establish communication in between model and view

3.model contains java beans file,java beans is a normal java class which should 

contain a constructor, setter & getter.

4.view part contains html for jsp files

5.controller contains filter & servlets.

16.Spring framework mein kaunse modules(spring frameworks 

contains modules)

The Spring framework comprises of many modules such as core, beans, context, 

expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, 

Transaction, Web, Servlet, Struts etc.

Spring core, spring jpa data, mvc, rest.

Java Database Connectivity (JDBC)

Object-Relational Mapping (ORM)

Object XML Mappers

Java Message Service

Spring mvc,Core ,Data Jpa,Security,Spring rest,Spring test

 Or

17.What are the modules of spring framework?

1. Test

2. Spring Core Container

3. AOP, Aspects and Instrumentation

4. Data Access/Integration

5. Web

18.View resolver:

All the handler methods in the controller returns the logical view name in String,View or 

ModelAndView.

These logical views are mapped to actual views by using view resolver.

19.what is spring jpa data

It is one of the modules in the spring frameworks. spring data jpa provides jpa 

template class to integrate spring application with jpa.

20.What is object?

Object − Objects have states and behaviors. ... An object is an instance of a class. Class − 

A class can be defined as a template/blueprint that describes the behavior/state that the 

object of its type support.

 Or

Object is nothing but instance of class. It has its own state, behaviour and identity

 Or

The Object is the real-time entity having some state and behavior. In Java, Object is an 

instance of the class having the instance variables as the state of the object and the methods 

as the behavior of the object. The object of a class can be created by using the new keyword.

21.Aggregation & Composition

In this real world there are 2types of relation ships

Which exists: is-a relationship

 Has a relationship

1.to deal with is-a relationship extends keyword is used4

2.To deal with has-a relationship aggreagation &composition is used.

Has – arelationship is of two types.

Aggregation: It is the process of having has-a relationship in between 

aggregate object & enclosing object. Aggregate objects are such objects which 

will not be destroy automatically if enclosing object will be destroy.

Composition: It is the process of having has- a relationship in b/w composite & 

enclosing object.Composite object are such objects which will be destroy if 

enclosing will be destroy.

22.Spring core annotations? (di : dependency injection)

@component @bean @autowired @Value @Required @ComponentScan @Configuration 

@Primary @Bean @Qualifier etc

23.Bean life cycle –

24.Isolation Level:

The Isolation level determines what happens during the concurrent (simultaneous) use 

of the same transaction. Dirty Reads return different results within a single transaction 

when an SQL operation accesses an uncommitted or modified record created by another 

transaction.

25.how we specify relationship between entities in spring jpa

A one-to-many relationship between two entities is defined by using the @OneToMany 

annotation in Spring Data JPA. It declares the mappedBy element to indicate the entity 

that owns the bidirectional relationship

26.Spring MVC

Spring MVC stands for Spring Model-View-Controller is a framework that is designed with the 

help of dispatcher servlet which dispatches requests to the specific controllers with the help 

of annotations and that controller will return the response again to the dispatcher servlet i.e. it 

will get data and view name and the view technology will fetch the data from the controller 

then that page goes from dispatcher servlet to the client.

Or

A Spring MVC is a Java framework which is used to build web applications. It 

follows the Model-View-Controller design pattern. It implements all the basic features 

of a core spring framework like Inversion of Control, Dependency Injection.

 Or

A Spring MVC is a Java Framework which is used to develop dynamic web applications. 

It implements all the basic features of a core spring framework like Inversion of Control 

and Dependency Injection. It follows the Model-View-Controller design pattern.

Here,

Model - A model contains the data of the application. Data can be a single object or 

a collection of objects.

Controller - A controller contains the business logic of an application. Here, the 

@Controller annotation is used to mark the class as the controller.

View - A view represents the provided information in a particular format. So, we can 

create a view page by using view technologies like JSP+JSTL, Apache Velocity, 

Thymeleaf, and FreeMarker.

27. Spring JPA Data

Spring Data JPA aims to significantly improve the implementation of data access 

layers by reducing the effort to the amount that's actually needed. ... As a developer you 

write your repository interfaces, including custom finder methods, and Spring will provide the 

implementation automatically.

28.Constructor Injection

Constructor Injection is the act of statically defining the list of required Dependencies 

by specifying them as parameters to the class's constructor. ... The class that needs 

the Dependency must expose a public constructor that takes an instance of the required 

Dependency as a constructor argument

29. JPA:

Java Persistence API (Application Programming Interface)

JPA is an abbreviation that stands for Java Persistence API. It's a specification 

which is part of Java EE and defines an API for object-relational mappings and for 

managing persistent objects.

30. Interface:

An interface in the Java programming language is an abstract type that is used to specify 

a behavior that classes must implement. They are similar to protocols. Interfaces are 

declared using the interface keyword, and may only contain method signature and 

constant declarations.

31. Dispatcher servlet

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and 

as such is declared in the web.xml of your web application. You need to map requests that 

you want the DispatcherServlet to handle, by using a URL mapping in the same web.xml file.

Or

It will get the request find the appropriate controller and do send back that response to the 

client it as a role of dispatcher servlet

--file name should be servlet name hyphen servlet. ispatcher servlet is also some files within 

our Applications so here that file will consist of some configurations within that.

32. Encapsulation

Is an attribute of an object it contains all data which is hidden.That hidden data can be restricted to 

the members of that class. Levels are public,protected,private,internal and protected internal.

Ex: It is wrapped with diff medicines in a capsule,all meedeicine is encapsulated inside a capsule.

In java we can also say that

A java class is an example of encapsulation java bean is fully encapsulated class becoz all the data 

members are private here.

33.Object:

Object − Objects have states and behaviors. Example: A dog has states - color, name, 

breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a 

class. Class − A class can be defined as a template/blueprint that describes the 

behavior/state that the object of its type support.

 Or

Object:Is nothing but an instance of class.It has its own state ,behaviour and identity.

Class: a class is simply a representation of atype of object.It is blueprint or plan or template 

that describes the detail of an object.

34.Inheritance and example

Inheritance is a concept where one class shares the structure and behaviour defined in another 

class . if inheritance applied to one class is called single inheritance and if it depends on multiple 

classes,then it is called multiple inheritance.

Ex: where as inheritance is a relationship b/w a superclass and subclass.

Superclass : the class whose features are inherited is known as superclass {parent class}

Subclass : The class that inherits the other class is known as subclass { child class}

The subclass can add its own fields and methods.

Ex:

In real -life example of inheritance is child and parents,all the properties of a father are inherited by 

his son/

In java: in java library you can see extensive use of inheritance.

The number class abstracts various(numerical)or reference types such as 

bytes,integer,float,double,short and big decimal.

Where here: object->extends ->number-> extends: byte,integer,float,doble.

35. Method overriding with real life example

Declaring a method in sub class which is already present in parent class is known as 

method overriding. Overriding is done so that a child class can give its own implementation 

to a method which is already provided by the parent class.

 Or

Method overriding in java with simple example. Lets consider an example that, A Son 

inherits his Father's public properties e.g. home and car and using it. At later point of 

time, he decided to buy and use his own car, but, still he wants to use his father's home.

36. Spring rest

Spring RestController annotation is used to create RESTful web services using Spring 

MVC. Spring RestController takes care of mapping request data to the defined request 

handler method. Once response body is generated from the handler method, it converts it to 

JSON or XML response.

37. What is constructor

*What is the constructor?

The constructor can be defined as the special type of method that is used to initialize 

the state of an object. It is invoked when the class is instantiated, and the memory is 

allocated for the object. Every time, an object is created using the new keyword, the 

default constructor of the class is called. The name of the constructor must be similar 

to the class name. The constructor must not have an explicit return type.

*What is Maven?

Maven is an automation and management tool developed by Apache Software 

Foundation. It is written in Java Language to build projects written in C#, Ruby, 

Scala, and other languages. It allows developers to create projects, dependency, 

and documentation using Project Object Model and plugins. It has a similar 

development process as ANT, but it is more advanced than ANT.

Maven can also build any number of projects into desired output such as jar, 

war, metadata.

It was initially released on 13 July 2004. In the Yiddish language, the meaning of 

Maven is “accumulator of knowledge.”

ANT stands for Another Neat Tool. It is a Java-based build tool from computer 

software development company Apache.

38.HTTP:

HTTP stands for Hypertext Transfer Protocol. It is a set of rule which is used for 

transferring the files like, audio, video, graphic image, text and other multimedia files 

on the WWW (World Wide Web). HTTP is a protocol that is used to transfer the 

hypertext from the client end to the server end, but HTTP does not have any security. 

Whenever a user opens their Web Browser, that means the user indirectly uses HTTP.

39. Httpservlet

The HttpServlet class extends the GenericServlet class and implements Serializable interface. 

-It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. 

It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the 

request to the protected service method by converting the request and 

response object into http type.

2. protected void service(HttpServletRequest req, HttpServletResponse 

res) receives the request from the service method, and dispatches the request 

to the doXXX() method depending on the incoming http request type.

3. protected void doGet(HttpServletRequest req, HttpServletResponse 

res) handles the GET request. It is invoked by the web container.

4. protected void doPost(HttpServletRequest req, HttpServletResponse 

res) handles the POST request. It is invoked by the web container.

5. protected void doHead(HttpServletRequest req, HttpServletResponse 

res) handles the HEAD request. It is invoked by the web container.

6. protected void doOptions(HttpServletRequest req, HttpServletResponse 

res) handles the OPTIONS request. It is invoked by the web container.

7. protected void doPut(HttpServletRequest req, HttpServletResponse 

res) handles the PUT request. It is invoked by the web container.

8. protected void doTrace(HttpServletRequest req, HttpServletResponse 

res) handles the TRACE request. It is invoked by the web container.

9. protected void doDelete(HttpServletRequest req, HttpServletResponse 

res) handles the DELETE request. It is invoked by the web container.

10. protected long getLastModified(HttpServletRequest req) returns the time 

when HttpServletRequest was last modified since midnight January 1, 1970 

GMT.

40.Why do we use MVC?

Faster development process: MVC supports rapid and parallel development. If an MVC 

model is used to develop any particular web application then it is possible that one 

programmer can work on the view while the other can work on the controller to create the 

business logic of the web application.

41.Spring Security

Spring Security is a powerful and highly customizable authentication and accesscontrol framework. It is the de-facto standard for securing Spring-based applications.

Or

Spring security with example:-------------

Spring Security provides ways to perform authentication and authorization in a web 

application. We can use spring security in any servlet based web application.

Or

Introduction

Spring Security is a framework which provides various security features like: 

authentication, authorization to create secure Java Enterprise Applications.

It is a sub-project of Spring framework which was started in 2003 by Ben Alex. Later 

on, in 2004, It was released under the Apache License as Spring Security 2.0.0.

It overcomes all the problems that come during creating non spring security 

applications and manage new server environment for the application.

This framework targets two major areas of application are authentication and 

authorization. Authentication is the process of knowing and identifying the user that 

wants to access.

42.Develop Platform:

Java is a general-purpose, class-based, object-oriented programming language designed for 

having lesser implementation dependencies. It is a computing platform for application 

development. Java is fast, secure, and reliable, therefore.

43. @ModelAttribute

@ModelAttribute is a Spring-MVC specific annotation used for preparing the model data. 

It is also used to define the command object that would be bound with the HTTP request data. 

The annotation works only if the class is a Controller class (i.e. annotated with @Controller).

44. Reponsebody

The response body consists of the resource data requested by the client. In our example, 

we requested the book's data, and the response body consists of the different books present 

in the database along with their information

45. Exceptions in java

In Java “an event that occurs during the execution of a program that disrupts the 

normal flow of instructions” is called an exception. This is generally an unexpected or 

unwanted event which can occur either at compile-time or run-time in application code.

46. Types of collections

There are three generic types of collection: ordered lists, dictionaries/maps, and sets. 

Ordered lists allows the programmer to insert items in a certain order and retrieve those 

items in the same order. An example is a waiting list. The base interfaces for ordered lists 

are called List and Queue.

47.List

The Java. util. List is a child interface of Collection. It is an ordered collection of objects in 

which duplicate values can be stored. ... List Interface is implemented by ArrayList, 

LinkedList, Vector and Stack classes.

48 JDBC 

Java Database Connectivity (JDBC) is an application programming interface (API) for the 

programming language Java, which defines how a client may access a database. ... It 

provides methods to query and update data in a database, and is oriented toward relational 

databases.

49.JPA

JPA is just a specification that facilitates object-relational mapping to manage 

relational data in Java applications. It provides a platform to work directly with objects 

instead of using SQL statements

Or

The Java Persistence API (JPA) is a specification that defines how to persist data in Java 

applications. The primary focus of JPA is the ORM layer. mvc is one of the most popular 

Java ORM frameworks in use today.

50.Spring MVC

A Spring MVC is a Java framework which is used to build web applications. It follows the 

Model-View-Controller design pattern. It implements all the basic features of a core spring 

framework like Inversion of Control, Dependency Injection.

51.Difference between ArrayList and LinkedList

52. Difference between List and Set:

Difference between List and Set:

List Set

1. The List is an ordered sequence. 1. The Set is an unordered sequence.

2. List allows duplicate elements

2. Set doesn’t allow duplicate 

elements.

3. Elements by their position can be 

accessed.

3. Position access to elements is not 

allowed.

4. Multiple null elements can be stored. 4. Null element can store only once.

5. List implementations are ArrayList, 

LinkedList, Vector, Stack

5. Set implementations are HashSet, 

LinkedHashSet. 

53.Collection

The Collection in Java is a framework that provides an architecture to store and 

manipulate the group of objects. Java Collections can achieve all the operations that you 

perform on a data such as searching, sorting, insertion, manipulation, and deletion. Java 

Collection means a single unit of objects.

54. Spring model

In Spring MVC, the model works a container that contains the data of the application. 

Here, a data can be in any form such as objects, strings, information from the database, etc. 

It is required to place the Model interface in the controller part of the application.

55. View resolver 

Spring provides view resolvers, which enable you to render models in a browser without 

tying you to a specific view technology. ... The two interfaces which are important to the way 

Spring handles views are ViewResolver and View . The ViewResolver provides a mapping 

between view names and actual views

56. Flow of Spring MVC

Spring MVC is a Java framework that is used to develop web applications. It is built on a 

Model-View-Controller (MVC) pattern and possesses all the basic features of a spring 

framework, such as Dependency Injection, Inversion of Control.

57. Advantages of a Spring Boot application

• Fast and easy development of Spring-based applications;

• No need for the deployment of war files;

• The ability to create standalone applications;

• Helping to directly embed Tomcat, Jetty, or Undertow into an application;

• No need for XML configuration;

• Reduced amounts of source code;

Or

200.What is spring? What are its adavantages?

Spring is one of the most popular open source framework for developing enterprise 

applications. It provides comprehensive infrastructure support for developing Java based 

applications. Spring also enables the developer to create high performing, reusable, easily 

testable and loose coupling enterprise Java application.

58. Difference between front end and back end controller

Frontend - are the parts, which are visible to users: HTML, CSS, client-side Javascript. ... In 

a desktop application frontend would be the GUI. Backend - is the invisible part. In web 

applications that is your java, ruby, php or any other serverside code

59.Collection

The Collection in Java is a framework that provides an architecture to store and 

manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as 

searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides 

many interfaces (Set, List, Queue, Deque) and classes (ArrayList, 

Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet)

Collection vs Collections in Java with Example

Collection Collections

It is an interface. It is a utility class.

It is used to represent a group of individual 

objects as a single unit.

It defines several utility methods that are used to 

operate on collection. 

60.What is comparator and comparable

Comparable is meant for objects with natural ordering which means the object itself must 

know how it is to be ordered. For example Roll Numbers of students. ... Logically, 

Comparable interface compares “this” reference with the object specified and Comparator in 

Java compares two different class objects provided.

61. Why backend controller

The main aim of the controller is to help simplify the most common tasks that you need 

to do when setting up routes and functions/classes to handle them

62. Jstl core tags

The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP 

tags which encapsulates the core functionality common to many JSP applications. JSTL has 

support for common, structural tasks such as iteration and conditionals, tags for 

manipulating XML documents, internationalization tags, and SQL tags.

63. How will you create servlet? Explain flow 

How do you create a servlet?

The steps are as follows:

1. Create a directory structure.

2. Create a Servlet.

3. Compile the Servlet.

4. Create a deployment descriptor.

5. Start the server and deploy the project.

6. Access the servlet.

Or

There are given 6 steps to create a servlet example. These steps are required for all 

the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,

2. By inheriting GenericServlet class, (or)

3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request 

specific method such as doGet(), doPost(), doHead() etc.

What is doGet and doPost?

The doGet() method is used for getting the information from server while the doPost() 

method is used for sending information to the server.

Here, we are going to use apache tomcat server in this example. The steps are as 

follows:

1. Create a directory structure

2. Create a Servlet

3. Compile the Servlet

4. Create a deployment descriptor

5. Start the server and deploy the project

6. Access the servlet

GenericServlet

GenericServlet is an abstract class which implements Servlet and 

ServletConfig interface. GenericServlet class can also be used to create a 

Servlet. GenericServlet class is part of the Servlet API and the full path to import 

this class is javax. servlet. GenericServlet.

64.What is servlet workflow?

Web container is responsible for managing execution of servlets and JSP 

pages for Java EE application. When a request comes in for a servlet, the 

server hands the request to the Web Container. Web Container is responsible 

for instantiating the servlet or creating a new thread to handle the request.

65. How to implement crud operations in jpa

How are CRUD operations implemented?

CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four 

most basic operations that can be performed with most traditional database systems and 

they are the backbone for interacting with any database.

Search for: How are CRUD operations implemented?

201.What is JPA CRUD?

The CRUD stands for Create, Retrieve (Read), Update and Delete operations on an 

Entity. ... The EntityManager, em represents a JPA link to the relational database which can 

be used to perform CRUD operations on the Entity objects. In JPA the EntityManager is an 

interface which is associated with a persistence context.

66. What is Scenario technology?

Technology scenarios represent a holistic approach for managing innovation processes 

and technologies efficiently. A multidimensional requirement catalogue for specific 

product- market- combinations represents the fundamental building block for the ranking of 

particular material- components and technologies.

67. What is a HTTP verb?

HTTP defines a set of request methods to indicate the desired action to be 

performed for a given resource. Although they can also be nouns, these request 

methods are sometimes referred to as HTTP verbs

68. Annotations

an annotation is a form of syntactic metadata that can 

be added to Java source code.

Or

Java Annotation is a tag that represents the metadata i.e. attached with class, interface, 

methods or fields to indicate some additional information which can be used by java 

compiler and JVM.

Annotations in Java are used to provide additional information, so it is an alternative 

option for XML and Java marker interfaces.

First, we will learn some built-in annotations then we will move on creating and using 

custom annotations.

Or

Annotations are used to provide supplement information about a program.

• Annotations start with '@'.

• Annotations do not change action of a compiled program.

• Annotations help to associate metadata (information) to the program elements 

i.e. instance variables, constructors, methods, classes, etc.

69. What is a class?

Class is a blueprint. Using the class, JVM creates an object. A class does not exist 

in reality. (Contractor example: 

Building plan – class

JVM – Contractor

Actual Building - object)

70. What is an object?

Object is a real world entity which has a physical existence. An object is created 

by the JVM by referring to the class.

71. What is Java Servlets?

Servlet is basically a java file which can take the request from the client and process the 

request and provide response in the form of html page. Deployment descriptor mentions 

which servlet should be called for which request and mapping can be done using xml files or 

annotations

72. Inversion of control

73. Types of Inversion of control

74. Create Application Context in project

75.Dependency Injection

76. Difference between setter and constructor injection

77. Bean wiring and @Auto wired annotation

78.InternalResourceViewResolver in spring mvc?

79.Difference between @Component @Controller @Repository

80. @ComponentScan annotation

.

81. spring vs spring boot diff

82. Features of spring boot

83.spring boot works

84. configure spring boot externally

85.Spring boot starters

86. autoconfiguration in spring boot

87.change the port

88.spring boot actuator

89.spring boot devtools

DevTools stands for Developer Tool. The aim of the module is to try and improve the 

development time while working with the Spring Boot application. Spring Boot DevTools 

pick up the changes and restart the application.

90.spring boot external database

91. rest and restful

92.life cycle of servlet

93.servlet config

94.servlet context

95.better way of maintaining session

96.http session object

97.diff post and get

98.

99.implicit objects of jsp

100.JDBC

101.Types of JDBC

102. statement,prepared statement

1. Statement :

It is used for accessing your database. Statement interface cannot accept 

parameters and useful when you are using static SQL statements at runtime. 

If you want to run SQL query only once then this interface is preferred over 

PreparedStatement.

2. PreparedStatement :

It is used when you want to use SQL statements many times. The 

PreparedStatement interface accepts input parameters at runtime.

Difference between CallableStatement and PreparedStatement :

Statement PreparedStatement

It is used when SQL query is to be 

executed only once.

It is used when SQL query is to be executed 

multiple times.

You can not pass parameters at runtime. You can pass parameters at runtime.

Used for CREATE, ALTER, DROP 

statements.

Used for the queries which are to be executed 

multiple times.

Performance is very low. Performance is better than Statement.

It is base interface. It extends statement interface.

Used to execute normal SQL queries. Used to execute dynamic SQL queries.

We can not used statement for reading 

binary data.

We can used Preparedstatement for reading 

binary data.

It is used for DDL statements. It is used for any SQL Query.

We can not used statement for writing 

binary data.

We can used Preparedstatement for writing 

binary data.

No binary protocol is used for 

communication. Binary protocol is used for communication.

103. java 8 feature

Feature Name Description

Lambda expression A function that can be shared or referred to as an object.

Functional Interfaces Single abstract method interface.

Method References Uses function as a parameter to invoke a method.

Default method

It provides an implementation of methods within interfaces 

enabling 'Interface evolution' facilities.

Stream API Abstract layer that provides pipeline processing of the data.

Date Time API

New improved joda-time inspired APIs to overcome the 

drawbacks in previous versions

Optional

Wrapper class to check the null values and helps in further 

processing based on the value.

Nashorn, JavaScript 

Engine

An improvised version of JavaScript Engine that enables 

JavaScript executions in Java, to replace Rhino.

104. What do you mean by abstract class?

An abstract class is a template definition of methods and variables of a class 

(category of objects) that contains one or more abstracted methods. ... Declaring a 

class as abstract means that it cannot be directly instantiated, which means that 

an object cannot be created from it.

105. functional interface

A functional interface is an interface that contains only one abstract method. 

They can have only one functionality to exhibit. From Java 8 

onwards, lambda expressions can be used to represent the instance of a 

functional interface. A functional interface can have any number of default 

methods. Runnable, ActionListener, Comparable are some of the 

examples of functional interfaces.

Before Java 8, we had to create anonymous inner class objects or implement 

these interfaces.

106. Map , set

Set:

A Set is a Collection that cannot contain duplicate elements. It models the mathematical 

set abstraction. The Set interface contains only methods inherited from Collection and adds 

the restriction that duplicate elements are prohibited.

Map:

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each 

key can map to at most one value. It models the mathematical function abstraction. ... The 

Java platform contains three general-purpose Map implementations: HashMap , TreeMap , 

and LinkedHashMap .

What is the difference between a Map and a set?

Both Set and Map interfaces are used to store a collection of objects as a single unit. The 

main difference between Set and Map is that Set is unordered and contains different 

elements, whereas Map contains the data in the key-value pair.

107.Unit Testing

Unit testing involves the testing of each unit or an individual component of the software 

application. It is the first level of functional testing. The aim behind unit testing is to validate 

unit components with its performance.

A unit is a single testable part of a software system and tested during the development phase 

of the application software.

The purpose of unit testing is to test the correctness of isolated code. A unit component is an 

individual function or code of the application. White box testing approach used for unit 

testing and usually done by the developers.

Whenever the application is ready and given to the Test engineer, he/she will start checking 

every component of the module or module of the application independently or one by one, 

and this process is known as Unit testing or components testing.

108. Integration testing

Integration testing is the second level of the software testing process comes after unit 

testing. In this testing, units or individual components of the software are tested in a 

group. The focus of the integration testing level is to expose defects at the time of 

interaction between integrated components or units.

[8:55 am, 02/09/2021] Sravani: ContextConfig: used to locate spring configurations(xml files). We 

provide full path inside param value tag

[8:55 am, 02/09/2021] Sravani: Context hierarchy : defines 2 types of web application contexts- root 

and servlet / child web application context

[8:55 am, 02/09/2021] Sravani: VIVA

[8:55 am, 02/09/2021] Sravani: Context configuration helps in loading the spring configurations from 

xml files.

109.What is @inject annotation in spring?

@Inject annotation is a standard annotation, which is defined in the standard 

"Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports 

the generalized model of dependency injection which is defined in the standard JSR330.

120.valid :

The @Valid annotation is used to mark nested attributes in particular. This triggers the 

validation of the nested object. For instance, in our current scenario, let's create a 

UserAddress object: public class UserAddress { @NotBlank private String countryCode; // 

standard constructors / setters / getters / toString

--------------------------------------------------------------------------------------------------

121)@ModelAttribute:

For parameter annotations, think of @ModelAttribute as the equivalent of @Autowired + 

@Qualifier i.e. it tries to retrieve a bean with the given name

from the Spring managed model. If the named bean is not found, instead of throwing an error or 

returning null, it implicitly takes on the role of @Bean i.e.

Create a new instance using the default constructor and add the bean to the model.

The @ModelAttribute is an annotation that binds a method parameter or method return value to a 

named model attribute and then exposes it to a web view.

122)@Autowired:

To autowire a relationship between the collaborating beans without using constructor arguments 

and property tags that reudces rhe amount of XML configaration.It 

automatically injects the dependent beans into the associated references of a POJO class.

Or

The @Autowired annotation can be used to autowire bean on the 

setter method just like @Required annotation, constructor, a 

property or methods with arbitrary names and/or multiple 

arguments.

123)@RequestMapping :

Most imp annotation.This maps http request to handler methods of MVC and REST controllers.Can 

be applied to class level/method level in a controller.

Maps web requests onto specific handleer classes/handler methods.

124)Bean :

In Spring, the objects that form the backbone of your application and that are managed by the 

Spring IoC container are called beans. 

A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC 

container.

125)what's difference between entity and bean class:

126)ORM.XML :

The standard JPA orm. xml file applies metadata to the persistence unit. It provides support for all of 

the JPA 2.0 mappings.

You can use this file instead of annotations or to override JPA annotations in the source code.

127)How many ways we can write query in jpa :

Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL 

syntax.

128)Explain invalid date exception part :

129)Difference between CRUD repository and JPA repository :

130)@PersistenceContext :

widely used by JPA/Hibernate developers to inject an Entity Manager into their DAO classes.

131)Annotations :

@Entity and @Id . The @Entity annotation specifies that the class is an entity and is mapped to a 

database table. 

@Table annotation specifies the name of the database table to be used for mapping.

132)Uses of bean Classes :

In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into 

a single object (the bean). 

They are serializable, have a zero-argument constructor, and allow access to properties using getter 

and setter methods. The name "Bean"

was given to encompass this standard, which aims to create reusable software components for Java.

133)Check for validations and exceptions in code : 

Exceptions : are the unusual behaviour of the code and it should be managed so that it does not 

affect the flow of the rest of the code.

Validations : The possible errors that we can suggest to the user.

134)Explain Spring MVC :

A Spring MVC is a Java framework which is used to build web applications. It follows the ModelView-Controller design pattern. 

MVC Model-represents the POJO'S,bussiness logic,database logic.

 View-responsible to generate/select the User interface and present the data to the end user

 Controller-Intercepts all the requests/commands sent to the application and updates the view.

It implements all the basic features of a core spring framework like Inversion of Control, Dependency 

Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help of 

DispatcherServlet. 

Here, DispatcherServlet is a class that receives the incoming request and maps it to the right 

resource such as controllers, models, and views.

135)@Service -specialization of @Component at the service layer

 @Component-indicates that an annotated class is a spring component

136)Application context :

The ApplicationContext is the central interface within a Spring application that is used for providing 

configuration information to the application.

It represents the Spring IoC container and is responsible for instantiating, configuring, and 

assembling the beans.

The container gets its instructions on what objects to instantiate, configure,

and assemble by reading configuration metadata.

137)Binding result :

BindingResult holds the result of a validation and binding and contains errors that may have 

occurred. 

The BindingResult must come right after the model object that is validated or else Spring fails to 

validate the object and throws an exception

138)Can we write the code without Internal View resolver ?? No

139)Whether the <servlet-name> can be different :

<servlet-name>we can give servlet name here </servlet-name> and that should not be compulsion 

to match with the .XML name 

For example <servlet-name>abc</servlet-name>

And the file name can be anything like this def.xml

140)View resolver :

Spring MVC Framework provides the ViewResolver interface, that maps view names to actual views. 

It also provides the View interface, which addresses the request of a view to the view technology.

(or)

In Spring MVC based application, the last step of request processing is to return the logical view 

name.

Here DispatcherServlet has to delegate control to a view template so the information is rendered. 

This view template decides that which view should be rendered based on returned logical view 

name.

These view templates are one or more view resolver beans declared in the web application context. 

These beans have to implement the ViewResolver interface for DispatcherServlet to auto-detect 

them. Spring MVC comes with several ViewResolver implementations.

141)InternalResourceViewResolver :(URL based):

In most of Spring MVC applications, views are mapped to a template’s name and location directly. 

InternalResourceViewResolver helps in mapping 

the logical view names to directly view files under a certain pre-configured directory.

Uses prefix and suffix to map the view.

142)@Valid :

 value="txmanager" : To avoid transcational begin and commit after persisting every data,,we use 

this.

 @Transactional : there are two types if transaction management Global(managed byy spring 

containers) and local(database)

 Definition : used to give metadata to transactional proxy to perform transaction management.

Transaction management ensures data integruty and consistency at any environment.

143)Dispatcher Servlet :

It is a front cotroller,where a single servlet receives all requests and transfers them to all the other 

components of the application.

It's task is to send the request to the specific MVC controller.

144)Inversion of control :

Run time will be able to create objects and give it back to the code.

145)Getters and setters :

For each instance variable, a getter method returns its value while a setter method sets or updates 

its value.Used for data encapsulation.

146)@RepositoryDefnition :

customization to expose selected methods in the interface can be achieved.

extending CRUD will provde the complete set of methods avalable for entity manipulation.

@Repository: annotation is used to indicate that the class provides the mechanism for storage, 

retrieval, search, update and delete operation on objects.

Questions and Answers:-

148.What tags will be present in web.xml?

• context-param.

• description.

• display-name.

• distributable.

• ejb-ref.

• ejb-local-ref.

• env-entry.

• error-page.

149.Where will the exceptions be placed in ( which layer)

Ans: The Controller layer is where the Domain Exceptions will be treated.

150.How to deal with exception in spring

Ans: You can add extra ( @ExceptionHandler ) methods to any controller to 

specifically handle exceptions thrown by request handling ( @RequestMapping ) 

methods in the same controller. Such methods can: Handle exceptions without the 

@ResponseStatus annotation.

151.How to manage session in spring framework

Ans:

1. Spring Session Core: Provides API and core support for session 

management.

2. Spring Session JDBC: provides session management using relational 

database.

3. Spring Session Data Redis: provides session management implementation 

for Redis database.

4. Spring Session Hazelcast: provides session management support using 

Hazelcast.

152.Diif array and array list:

Basis Array ArrayList

Definition An array is a dynamically-created object. It 

serves as a container that holds the constant 

number of values of the same type. It has a

contiguous memory location.

The ArrayList is a class of 

Java Collections framework. It 

contains popular classes like Vector, 

HashTable, and HashMap.

Static/ 

Dynamic

Array is static in size. ArrayList is dynamic in size.

Resizable An array is a fixed-length data structure. ArrayList is a variable-length data 

structure. It can be resized itself 

when needed.

Initialization It is mandatory to provide the size of an array 

while initializing it directly or indirectly.

We can create an instance of 

ArrayList without specifying its size. 

Java creates ArrayList of default size.

Performance It performs fast in comparison to ArrayList 

because of fixed size.

ArrayList is internally backed by the 

array in Java. The resize operation in 

ArrayList slows down the 

performance.

Primitive/ 

Generic type

An array can store 

both objects and primitives type.

We cannot store primitive type in 

ArrayList. It automatically converts 

primitive type to object.

Iterating 

Values

We use for loop or for each loop to iterate 

over an array.

We use an iterator to iterate over 

ArrayList.

Type-Safety We cannot use generics along with array 

because it is not a convertible type of array.

ArrayList allows us to store 

only generic/ type, that's why it is 

type-safe.

Length Array provides a length variable which 

denotes the length of an array.

ArrayList provides the size() method 

to determine the size of ArrayList.

153.What is lambda?

Ans: A lambda expression is a short block of code which takes in parameters and 

returns a value.

154.What is functional interface

Ans: A functional interface in Java is an interface that contains only a single 

abstract (unimplemented) method. A functional interface can contain default and 

static methods which do have an implementation, in addition to the single 

unimplemented method.

155.Diff between jpa and dpa data

JPA Hibernate

Java Persistence API (JPA) defines the management 

of relational data in the Java applications.

Hibernate is an Object-Relational Mapping 

(ORM) tool which is used to save the state of 

Java object into the database.

It is just a specification. Various ORM tools 

implement it for data persistence.

It is one of the most frequently used JPA 

implementation.

It is defined in javax.persistence package. It is defined in org.hibernate package.

The EntityManagerFactory interface is used to 

interact with the entity manager factory for the 

persistence unit. Thus, it provides an entity manager.

It uses SessionFactory interface to create 

Session instances.

It uses EntityManager interface to create, read, and 

delete operations for instances of mapped entity 

It uses Session interface to create, read, and 

delete operations for instances of mapped 

Adding 

Elements

We can add elements in an array by using 

the assignment operator.

Java provides the add() method to 

add elements in the ArrayList.

Single/ MultiDimensional

Array can be multi-dimensional. ArrayList is always singledimensional.

classes. This interface interacts with the persistence 

context.

entity classes. It behaves as a runtime interface 

between a Java application and Hibernate.

It uses Java Persistence Query Language (JPQL) as 

an object-oriented query language to perform 

database operations.

It uses Hibernate Query Language (HQL) as an 

object-oriented query language to perform 

database operations.

156.Duration of sprint.

Ans: That is, the Team needs to be able to get Stories Done. It's a rule of Scrum 

that a Sprint should never be longer than one month. Generally speaking, the Sprint 

length should be approximately three times as long as it takes to Swarm on an 

average medium-size Story and get it Done.

157.Life cycle of servlet.

Ans:

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.

158.Spring mvc life cycle.

Ans: The entire process is request-driven. There is a Front Controller pattern and the 

Front Controller in Spring MVC is DispatcherServlet. Upon every incoming request 

from the user, Spring manages the entire life cycle

159.Which annotation is used to call handler method.

Ans: @ResponseBody. This annotation is used to annotate request handler 

methods

160.controller vs rest controller

The @controller is a common annotation that is used to mark a 

class as spring MVC controller

while @rest controller is a special controller used in RESTful 

web services and the equivalent of @controller + @response body

161.What is Agile?

Agile is a methodology that focuses on continuously delivering small 

manageable increments of a project through iterative development and 

testing. It was introduced as an alternative to the traditional waterfall 

methodology, known for its structured, linear, sequential life-cycle.

162.What is Devops?

DevOps is the combination of cultural philosophies, practices, and tools 

that increases an organization’s ability to deliver applications

163.What is the JPQL?

JPQL is the Java Persistence query language defined in JPA specification. It is used to 

construct the queries

164. What is the difference between an abstract class and an interface 

in Java?

The key technical differences between an abstract class and an interface are: Abstract 

classes can have constants, members, method stubs (methods without a body) and 

defined methods, whereas interfaces can only have constants and methods stubs

166.What is entity life cycle?

The life cycle of entity objects consists of four states: New, Managed, Removed and 

Detached. When an entity object is initially created its state is New. In this state the object is 

not yet associated with an EntityManager. persistence.

165.Life Cycle of a Servlet (Servlet Life 

Cycle)

A servlet life cycle can be defined as the entire process from its creation till the 

destruction. ... The servlet is initialized by calling the init() method. The servlet calls 

service() method to process a client's request. The servlet is terminated by calling the 

destroy() method.

….>

1. Life Cycle of a Servlet

1. Servlet class is loaded

2. Servlet instance is created

3. init method is invoked

4. service method is invoked

5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle 

of the servlet:

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.

there are three states of a servlet: new, ready and end. The servlet is in new state if 

servlet instance is created. After invoking the init() method, Servlet comes in the ready 

state. In the ready state, servlet performs all the tasks. When the web container invokes 

the destroy() method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when

the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The 

servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize 

the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException 

4) service method is invoked

The web container calls the service method each time when request for the servlet is 

received. If servlet is not initialized, it follows the first three steps as described above 

then calls the service method. If servlet is initialized, it calls the service method. Notice 

that servlet is initialized only once. The syntax of the service method of the Servlet 

interface is given below:

1. public void service(ServletRequest request, ServletResponse response) 

2. throws ServletException, IOException 

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from 

the service. It gives the servlet an opportunity to clean up any resource for example 

memory, thread etc. The syntax of the destroy method of the Servlet interface is given 

below:

public void destroy()

167. steps in implementing spring mvc with jpa 

Steps

1.

1. Create database tables and insert data

2. Create a maven web project

3. Add Spring MVC, Hibernate and MySQL depedencies

1. Update pom.xml

2. Add hibernate and database(mysql) resource file

1. create a applications.properties file under /src/main/resources

3. Add Configuration files -> Screen shot here

1. WebMvcConfig – This configuration class can be treated as a 

replacement of spring-servlet.xml as it contains all the information 

required for component-scanning and view resolver

2. HibernateConfig.java -This file contains information about the 

database and hibernate properties

3. ServletInitializer – which acts as replacement of any spring 

configuration defined in web.xml

4. Add/Update User Entity class -> Screen shot here

1. User.java

5. Create Repository Interface -> Screen shot here

1. UserRepository.java

6. Create Service Interface -> Screen shot here

1. UserService.java

2. UserServiceImpl.java

7. Update a Controller -> Screen shot here

1. UserController.java

8. Add/Update pages/views to display user details -> Screen shot here

1. home.jsp

2. addUser.jsp

3. editUser.jsp

4. allUsers.jsp

5. error.jsp

9. Delete web.xml as we will be using only java configurations

10. Run the application

168.difference between post and put

The difference between POST and PUT is that PUT requests are idempotent. That is, 

calling the same PUT request multiple times will always produce the same result. In contrast, 

calling a POST request repeatedly have side effects of creating the same resource multiple 

times.

PUT HTTP Request

PUT is a request method supported by HTTP used by the World Wide Web. 

The PUT method requests that the enclosed entity be stored under the 

supplied URI. If the URI refers to an already existing resource, it is modified 

and if the URI does not point to an existing resource, then the server can 

create the resource with that URI.

POST HTTP Request

POST is a request method supported by HTTP used by the World Wide 

Web. By design, the POST request method requests that a web server 

accepts the data enclosed in the body of the request message, most likely 

for storing it. It is often used when uploading a file or when submitting a 

completed web form.

Difference between PUT and POST methods

PUT POST

PUT request is made to a particular resource. 

If the Request-URI refers to an already 

existing resource, an update operation will 

happen, otherwise create operation should 

happen if Request-URI is a valid resource URI 

(assuming client is allowed to determine 

resource identifier).

Example –

PUT /article/{article-id}

POST method is used to 

request that the origin 

server accept the entity 

enclosed in the

request as a new 

subordinate of the resource 

identified by the RequestURI in the Request-Line. It 

essentially means that 

POST request-URI should 

be of a collection URI.

Example –

POST /articles

PUT method is idempotent. So if you send 

retry a request multiple times, that should be 

equivalent to single request modification.

POST is NOT idempotent. 

So if you retry the request 

N times, you will end up 

having N resources with N 

different URIs created on 

server.

Use PUT when you want to modify a single 

resource which is already a part of resources 

collection. PUT overwrites the resource in its 

entirety. Use PATCH if request updates part of 

the resource.

Use POST when you want 

to add a child resource 

under resources collection.

PUT POST

Generally, in practice, always use PUT for 

UPDATE operations.

Always use POST for 

CREATE operations.

170.methods of http

The primary or most commonly-used HTTP methods are POST, GET, PUT, PATCH, 

and DELETE. These methods correspond to create, read, update, and delete (or 

CRUD) operations, respectively.

171. diff sql vs jpql 

The main diff b/w sql and jpql is that sql works with relational database 

tables,records and fields,where as jpql works with java classes and objects.

172. spring security

Is a powerful and highly customizable authentication and access-control 

framework

Auth: permission or userid already registered or not?

Autheri : limiting access to particular user

Access is given using roles mapping

173.Ioc (inversion of control ):

It is the process of creating object by giving control to spring

or

Run time is capable of creating obj and sending it to the program when needed

Depency injection is achieved through ioc 

174.@autowiring

Automatic injection of beans

175.Diff b/w crud and jpa repositories:

Difference between JPA and CRUD Repositories:

• CrudRepository mainly provides CRUD functions.

• PagingAndSortingRepository provides methods to do pagination and sorting 

records.

• JPA repository : - it provides functions of both CrudRepository and 

PagingAndSortingRepository and it is technology specific(add some more 

functionality that is specific to JPA)

176.jpa vendors 

Hibernate

Eclipselinks

ibatis

177. @configuration

Used by spring containers as a source of bean definition and it 

is a class level annotation

178. Rest

Representational state transfer it is an architectural pattern used 

to web services which interact with each other through HTTP 

protocol.

179. Lambda 

(parameter)->(expressions)

180. What is Jenkins why it is used?

Jenkins is used to build and test your product continuously, so developers can 

continuously integrate changes into the build. Jenkins is the most popular open 

source CI/CD tool on the market today and is used in support of DevOps, alongside 

other cloud native tools

continuous integration

Continuous delivery

CI stands for continuous integration, a fundamental DevOps best practice where developers 

frequently merge code changes into a central repository where automated builds and tests 

run. But CD can either mean continuous delivery or continuous deployment.

181. Is Jenkins a DevOps tool?

Jenkins is an open source continuous integration/continuous delivery and 

deployment (CI/CD) automation software DevOps tool written in the Java 

programming language. It is used to implement CI/CD workflows, called pipelines.

182. What is SonarQube used for?

SonarQube is a Code Quality Assurance tool that collects and analyzes source 

code, and provides reports for the code quality of your project. It combines static and 

dynamic analysis tools and enables quality to be measured continually over time.

183. What is JSP life cycle?

A JSP life cycle is defined as the process from its creation till the destruction. This is 

similar to a servlet life cycle with an additional step which is required to compile a JSP into 

servlet.

184.Spring test annotations:

?

185.NotNull and Notempty difference:

@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's 

not null, but it can be empty. @NotEmpty: a constrained CharSequence, Collection, Map, 

or Array is valid as long as it's not null, and its size/length is greater than zero.

186. All classes in java inherited from which call:

All classes in java are inherited from Object class. Interfaces are 

not inherited from Object Class.

A subclass inherits all the members (fields, methods, and nested classes) from 

its superclass. Constructors are not members, so they are not inherited by subclasses, 

but the constructor of the superclass can be invoked from the subclass.

187.Why we can't use equals method for employee object:

Now if you compare them with == it will return false despite the fact that the objects 

are exactly the same. Same goes for Strings. "==" compares Object references with 

each other and not their literal values. If both the variables point to same object, it 

will return true.

188.What are the java 7 features:

189."Try-with- resource " method we used instead of which method:

?

190. Finally block in exceptions:

A finally block contains all the crucial statements that must be executed whether 

exception occurs or not. The statements present in this block will always execute 

regardless of whether exception occurs in try block or not such as closing a connection, 

stream etc.

300. @contextConfiguration

@ContextConfiguration defines class-level metadata that is used to determine how to 

load and configure an ApplicationContext for integration tests.

301.@Service if belongs to bean creation annotations?

This means that the bean will be created and initialized only when it is first requested for 

... @Service. This annotation is used on a class. The. @Service.

This annotation is used on a class. The

@Service

marks a Java class that performs some service, such as execute 

business logic, perform calculations and call external APIs. This 

annotation is a specialized form of the

@Component

annotation intended to be used in the service layer.

302.Which are the annotations you used to create an beans:

While the @Component annotation is used to decorate classes that are auto-detected 

by Spring scanning, the @Bean annotation is used to explicitly declare a bean creation.

303.Which are the method present in list but not in set:

The List interface provides two methods to efficiently insert and remove multiple 

elements at an arbitrary point in the list

If the list's list-iterator does not support the set operation then 

an UnsupportedOperationException will be thrown when replacing the first element.

304.Can we retiview the data using index in set:

The boolean value denotes if index is found the set or not. The integer value contains 

the integer stored at index in the set. If the boolean value is set true, which indicates 

index to be a vakid index, print the integer value stored in the pair. Otherwise print 

“Invalid index”.

……///////////

401) what is Class ?

class--the basic building block of an object-oriented language 

such as Java--is a template that describes the data and 

behavior associated with instances of that class. When you 

instantiate a class you create an object that looks and feels like 

other instances of the same class.

402) What is interface ?

An interface is declared by using the interface keyword. It 

provides total abstraction; means all the methods in an interface 

are declared with the empty body, and all the fields are public, 

static and final by default. A class that implements an interface 

must implement all the methods declared in the interface.

403) What is abstract class ?

An abstract class is a template definition of methods and 

variables of a class (category of objects) that contains one or 

more abstracted methods. ... Declaring a class as abstract 

means that it cannot be directly instantiated, which means that 

an object cannot be created from it.

404) What is polymorphism ?

Polymorphisms is the ability of different objects to respond in a 

unique way to the same message.

405) What is JDBC

Java Database Connectivity is an application programming 

interface for the programming language Java, which defines how 

a client may access a database.

JDBC makes it possible to do establish a connection with a data 

source, send queries and update statements, and process the 

results.

406) try-with-resources

In Java, the try-with-resources statement is a try statement 

that declares one or more resources. The resource is as an 

object that must be closed after finishing the program. The 

try-with-resources statement ensures that each resource is 

closed at the end of the statement execution.

408) what is Inheritance 

Inheritance in Java is a mechanism in which one object acquires 

all the properties and behaviors of a parent object. ... The idea 

behind inheritance in Java is that you can create new classes 

that are built upon existing classes. When you inherit from an 

existing class, you can reuse methods and fields of the parent 

class.

) rest API

REST or RESTful API design (Representational State Transfer) 

is designed to take advantage of existing protocols. ... This 

means that developers do not need to install libraries or 

additional software in order to take advantage of a REST API 

design.

RESTful Web services - Interview Questions

GET - Provides a read only access to a resource.

PUT - Used to create a new resource.

DELETE - Ued to remove a resource.

POST - Used to update a existing resource or create a new 

resource.

OPTIONS - Used to get the supported operations on a resource.

500) spring MVC

Spring MVC is a java framework which is used to build web 

applications. It follows the model-view-controller design pattern 

it implements all the basic features of a cold Spring framework 

like inversion of control dependency injection.

It has 4 components 

Front controller, controller , view , web browser.

505) context component scan

<context:component-scan> detects the annotations by package 

scanning. To put it differently, it tells Spring which packages 

need to be scanned to look for the annotated beans or 

components.

506) context annotation config

The <context:annotation-config> annotation is mainly used to 

activate the dependency injection annotations. ... That is 

because <context:annotation-config> activates the annotations 

only for the beans already registered in the application context. 

As can be seen here, we annotated the accountService field 

using @Autowired.

507) concept of oops

Object oriented programming system (oops) is a programming 

concept that works on the principles of abstraction, 

encapsulation, inheritance and polymorphism. The basic concepts 

of oops is to create objects reuse them through the program and 

manipulate these objects to get results.

508) inheritance

Inheritance is a mechanism wherein a new class is derived from 

an existing class. In Java, classes may inherit or acquire the 

properties and methods of other classes.

600) annotation driven

<mvc:annotation-driven /> means that you can define spring 

beans dependencies without actually having to specify a bunch of 

elements in XML or implement an interface or extend a base 

class.

602) @autowired

@Autowired annotation – We can use Spring @Autowired 

annotation for spring bean autowiring. @Autowired annotation can 

be applied on variables and methods for autowiring byType. We 

can also use @Autowired annotation on constructor for 

constructor based spring autowiring.

603) oops concept

Object oriented programming system is a programming concept 

that works on the principles of abstraction, encapsulation, 

inheritance and polymorphism. The basic concepts of oops is to 

create objects reuse them without the program and manipulate 

these objects to get results.

605) @rest controller vs @controller 

The @Controller is a common annotation that is used to mark a 

class as Spring MVC Controller

while @RestController is a special controller used in RESTFul 

web services and the equivalent of @Controller + 

@ResponseBody.

606) entity manager

In JPA, the EntityManager interface is used to allow applications 

to manage and search for entities in the relational database. ... 

The EntityManager is an API that manages the lifecycle of 

entity instances. An EntityManager object manages a set of 

entities that are defined by a persistence unit.

701) dispatcher servelet

The DispatcherServlet is a front controller like it provides a 

single entry point for a client request to Spring MVC web 

application and forwards request to Spring MVC controllers for 

processing.

704) context : component scan

Basically, <context:component-scan> detects the annotations by 

package scanning. To put it differently, it tells Spring which 

packages need to be scanned to look for the annotated beans or 

components.

705) concepts of oops

Object-Oriented Programming System (OOPs) is a programming 

concept that works on the principles of abstraction, 

encapsulation, inheritance, and polymorphism. ... The basic 

concept of OOPs is to create objects, re-use them throughout 

the program, and manipulate these objects to get results.

706) inheritance supported by java

On the basis of class, there can be three types of inheritance in 

java: single, multilevel and hierarchical. In java programming, 

multiple and hybrid inheritance is supported through interface 

only.

702) rest API 

A REST API (also known as RESTful API) is an application 

programming interface (API or web API) that conforms to the 

constraints of REST architectural style and allows for 

interaction with RESTful web services. REST stands for 

representational state transfer

803) exception handler

The Exception Handling in Java is one of the powerful mechanism 

to handle the runtime errors so that normal flow of the 

application can be maintained.

805) oops concepts

Object oriented programming system is a programming concept 

works on the principles of abstraction encapsulation, inheritance 

and polymorphism. The basic concept of oops is to create objects 

reuse them lo throughout the program and manipulate these 

objects to get results.

906) what is MVC driven and why we use it

Stands for "Model-View-Controller." MVC is an application design 

model comprised of three interconnected parts. ... The MVC 

model or "pattern" is commonly used for developing modern user 

interfaces. It is provides the fundamental pieces for designinguu 

a programs for desktop or mobile, as well as web applications. 

806) what is autowired why and where we require it

The @Autowired annotation can be used to autowire bean on the 

setter method just like @Required annotation, constructor, a 

property or methods with arbitrary names and/or multiple 

arguments.

Harry: 

George:

Rohit:

Fred:

Ajay:

Jas:

Edwin :

Raghav :














P1 : ROHIT

Q1 – Rohit wants to create an auto populated drop down box in purchase.jsp page. Help Rohit to 

implement a proper handler method in controller that can retrieve sports Type defined in DAO layer. 

Choose from below a valid option.

Ans- A) Create a method in the controller to invoke DAO layer method which returns the Map of 

SportsType with 

@ModelAttribute annotation.

Q2- Rohit wants to display all the validation error messages in purchase jsp. help him to display those 

messages at the bottom of the page choose from below a valid option assume the below taglib 

directives are added in the JSP.

<%@taglib url=”http://www.springframework.org/tags/form” prefix=”form”%>

<%@taglib url=”http://www.springframework.org/tags/form” prefix=”spring”%>

Ans- A option

Q3- Rohit wants to externalize the validation error messages so he defined the messages in 

com/Accenture/lkm/resources/messages_en properties” file. Rohit to configure the message source 

bean in the context file by choosing a valid option from below.

Ans- A)<bean id> =message source

Class=”org.springframework.context.support.ReloadableResourceBundleMessages

<property name=”basename” value=”classpath.com/Accenture/lkm/resources/messages_en*

</bean>

Q4- Rohit wants to auto populate the items available for the selected sports type to the respectively 

drop down box.Assume he defined the respective method in the controller which can return 

Map<String.Double>. Rohit is supposed to bind the key as label attribute , value as value attribute in the 

drop down box. choose from below a valid option

Ans- A) <form.select path=”items”>

<form.option value=”label=”select”/>

<form.options items=”$(itemsList)”/>

</form.select>

Q5-Rohit wants to navigate to success.jsp page on successful submission. Assume he wrote a handler 

method to return model and view with logical view name as success he needs to configure a view 

resolver bean in child configuration file to resolve the logical view name choose from below a valid 

option .

Ans – A)<bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver

Property Name=”prefix”

<value/WEB-INF/jsp/views</velue>

</property>

<property name=”suffix”>

<value>.jsp</value>

</property>

</bean>

Q6- Rohit wants to create a request handler method in controller that can handle customer request and 

send the response back to the customer. Help rohit to achieve this with a valid option given below.

Ans- A) create a request handler method in the controller to map the request using 

@RequestMapping annotation and return to the model and view object.

Q7- Rohit wants to display the success message in success.jsp page as mentioned in requirement 2. Help 

him to display the purchase date in dd-mmm-yyyy pattern. Choose from below a valid option.

Ans- A) < %@taglib url=”http://java.sun.com/jsp/jstl/fmt” prefix=”fmt” %>

<fmt:formatDate value=”${date}” type=”date” pattern=”dd-MMM-yyyy” />

Q8- Rohit wants to receive the request from customers and forward those requests to other

components of the application.

Ans – B) configure the dispatcher servlet provided by Spring Framework which acts as a

Q9- Rohit wants to validate the quantity entered by the customer as mentioned in requirement 2.

choose from the below valid options

Ans- A) Add @Range

C)The request handler method should include @Valid to @ModelAttribute parameter.

Q10- Rohit deployed the application in the Apache tomcat server but he got an exception as

Ans- A ) Configure< context

C) Configure<mvc

P2 : Meera Raghav

Q1. Help Raghav to choose from below a valid option to be used in DAO layer so that boilerplate code 

can be reduced 

Ans(C) Spring JPA data

Q2. Which are the mandatory annotations Raghav should use in Patient class ?

Ans : (A)(B) @Entity and @Id

Q3. Meera is responsible for creating all the view pages. She wants to create a page 

And (B) Use Spring from tags

Q4. The Admin can get the details of the patients who have taken appointment a particular doctor

Ans: (A) List<Patients> findByDoctorNameEquals(String name)

Q5 Raghav must pre-populate doctor’s name from Doctor table in a drop-down list when patient is 

booking appointments online .

Ans : (A) Use @ModelAttribute on the method ---

Q6. Raghav has added a method to update the details of the patients as below 

Ans ( C ) @Modifying is not used on the method and no changes required in the method signature 

Q7 Meera wants to render the model object on a view without trying to a specific new technology4

And (A) configure ViewResolver in servelet/child web application context

Q8 Raghav Added the following method in service and DAO implementation classes to add patient’s 

info in database

Ans (A) addPatientInDAO() method always executes in a new transaction rather than the transaction 

started in service layer of addPatientService() method

Q9 Help Raghav to select correct JPQL query to retrieve all the details of patient based on their name 

for the below 

Ans(B) @Query(“Select p from Patients p where p pName = ?100”)

Q10.Raghav Added following query in orm.xml file.

Ans (D) @Query(name = “getPatientData”)

List<Object()> getPatientsData();

P3 : HARRY

Q1. Harry wants to validate the mandatory fields(email and title) of newPost.jsp as per the

requirement

Ans ( A) Add @NoNull annotation for email and the fields in the bean class

 ( C) The request handler method should include @Valid annotation & @modelAttribute parameter

Q2. Harry needs to configure Dispatcher servlet in the deployment descriptor(web.xml) for his app.

Ans. (B) <servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</s-n>

<url-pattern>*.htm</u-p>

</s-m>

Q3 Harry needs to mark postId field as primary key and the value for primary key column should be

Ans. ( c) @id @generatedValue(strategy= GenerationType.AUTO) private in postId;

Q4 Harry needs to define spring beans and dependencies using dependency injection annotations and 

Ans. (B) <context:component - scan base-package = “com.accenture” />

Q5. Harry wants to use spring declarative transaction using @Transactional annotation.

Ans (A) <tx:annotation-driven transaction-manager="txManager"/>

Q6. To integrate framework with JPA and get complete support of transaction management

Ans (D) <bean id = “ entityManagerFactory”

Class = “org.springframework.com.jpa.LocalContainerEntityManagerFactoryBean”

Q7. Harry creates a method in controller class to redirect to new Post.jsp page .

Ans. (A) <bean class = “org.springframework.web.servelet.view.InternalResourseViewResolver”>

<property name = “prefix” value=”/WEB-INF/” />

<property name = “suffix” value=”.jsp” />

</bean>

Q8.Harry wants to create container managed Entity Manager for managing the entities and their 

Ans (A) @PersistenceContext and (C) @PersistenceContextType= PersistenceType.Transaction

Q9. Harry need to write a JPQL query to count number of posts entered by user as mentioned 

Ans(A)Query = query ----

m.email=email”}

 (C) @NamedQuery{-------

m.email=?:email”}

Q10. Harry added the spring MVC form select tag in newPost.jsp to auto populate the values in dropAns (A) Map<String,String> themeMap = new HashMap<String,String>

P4 : Edwin

Q1. Edwin wants to use DispatcherServelet as a front controller

Ans (C )

Q2. Edwin want to autopopulate the rides 

Ans (A) (Hint : @ModelAttribute)

Q3. Edwin wants to create a spring from radio button to get the input on the camera 

Ans (A) (Hint : radiobutton and both line isCameraIncluded)

Q4. Edwin wants to validate the number of tickets entered by the customer as per the req.

Ans(A)Add @NotNull @Range(min = 1, max = 10) 

 (C) The request handler method should include @Valid annotation @ModelAttribute

Q5. Edwin wants to create a jsp pages in the custom location “WEB-INF/jspViews”

Ans (B) <bean class = “org.springframework.web.servelet.view.InternalResourseViewResolver”>

<property name = “prefix”>< value>WEB-INF/jspViews</value></property>

<property name = “suffix” ><value>.jsp</value></property>

</bean>

Q7. Edwin wants to create a method in the controller to handle the request .

Ans (B) (Hint: public ModelAndView bookTicket(@Valid @ModelAttribute()))

Q8. Edwin wants to create a handler method in the controller for booking tickets.

Ans (A) 

Q9. Edwin wants to auto populate the shows available in the drop down box

Ans (B ) (Hint : @modelAttribute (“shows”))

Q10. Edwin wants to display the list of show details in viewItems.jsp page 

Ans(C ) <table border = “1” width = “25”> <caption><b>--</b></caption>

<c:forEach name = “show” items = “$(shows)”>

P5 : George

Q1.George wants to perform CRUD operations and transactions using the DAO interface that extends 

Ans (B) @Autowired

Q2. George wants to validate the answer text field entered by the user as per the requirement

Ans ( C) Add @NotEmpty @Size(min =1 , max = 50) annotation in the bean class

Q3. George want to write a method in container to process the request submitted from 

Ans (B) @RequestMapping

Q4. George wants to create a radio button in qaForm.jsp for categoryGrade.

Ans(A) Grade<form.radiobutton.path=”categoryGrade” value = “10”/>10 

(Hint – path and radioButton and value other option either contains name or radioButtons or lable )

Q5 George want to handle custom exception called CategoryGradeNotMatchException

Ans(D) (Hint : Extends exception and (String Mess)

Q6. George want to use a bean that gives complete and fine –grained 

Ans (D)

Q7. George wants to auto populate the categoryName dynamically , in the drop down box placed in 

Ans(B) (Hint : <form:options items = $(categoryMap)”/>

Q8. George wants to auto populate the categoryName dynamically from categoryTable 

Ans (B) Hint 1 : List<CategoryBean> listBean = newArrayList<>()

Hint2: Iterable

Hint 3 : CategoruyEntity bean = new CategoryEntity()

Q9. George want to handle the exception “CategoryGradeNotMatchException”

Ans (C) (Hint : @ExceptionHandler(CategoryGradeNotMatchException

Public ModelAndView handleException(----)

Q10. In qaForm.jsp grade selected should be less than equal to 

Ans (C) Hint : throw new and throws should be there 

P6 : AJAY

Q1. Ajay wants to create a page cashbackPage.jsp so that value entered by the user could be mapped

Ans: (B) Use Spring from tag inside cashbackPage.jsp

Q2. Ajay wants to display Career Level in drop down box on cashbackPage.jsp page 

Ans: (B) @ModelAttribute(“careerLevels”)

Public Set<String> getCareerLevels(){

Map<String,Double> map ------------

return map.keySet();

}

Q3. Consider below code snippet

<servlet>

<servlet-name>----</servlet-name>

<servlet-class>-----</servlet-class>

Ans: ( C ) Ajay has used the given snippet to configure Spring MVC frontend controller in the

deployment descriptor web.xml file

Q4: Ajay wants to create a page cashbackPage.jsp that accepts user input . This Page helps on 

Ans: (A) <%@ taglib prefix = “sptags” url=http://www.springframework.org/tags/form%>

Q5. Ajay Understand that it's good practice to put JSP files (that just serve as views) under WEB-INF

Ans: (B) <bean class = “org.springframework.web.servelet.view.InternalResourseViewResolver”>

<property name = “prefix” value=”/WEB-INF/” />

<property name = “suffix” value=”.jsp” />

</bean>

Q6. Ajay wants to display the list of employee career levels and corresponding cashback percentage 

Ans: (B) <c: forEach var = “map” items = “${cashbackPercentMap}”>

<tr>

<td>${map.key}</td>

<td>${map.value}</td>

</tr>

</c:forEach>

Q7. Ajay has used @Controller amd @Autowired annotation inside 

Ans : (A) <context:component - scan base-package = “com.accenture” />

Q8. Ajay has written code snippet on cashbackPage.jsp page <form options item =”$(productNames)”

/>

Ans. (C) public Set <String> geProductNames(----)){

Map<String,Double>map = ----

Return map.keySet();

}

Q9. Ajay wants to define registerCashback() method in controller. It must be mapped to URL pattern

Ans : D

Q10. Ajay wants to define showCashbackPage() method in controller and map it to URL

Ans : (D) @RequestMapping(url = “loadcashbackpage.htm” , method = GET)











P1:ROHIT

Rohit Wants to create an auto populated drop-down box in purchase.jsp page. 

Help Rohit to implement a proper handler method in controller that can retireve 

sportsType defined in DAO layer. Choose from below a valid option.

Create a method in the controller to invoke DAO layer method

 which returns the Map of Sportstype with @ModelAttribute annotation

Rohit wants to create a request handler method in controller that can handle

 customer request and send the response back to the customer. Help Rohit 

to achieve this with a valid option given below

Create a request handler method in the controller to map the request

 using @Requestmapping annotation and return the ModelAndView object

Rohit Wants to auto populate the items available for the selected SportsType to

 the respective drop-down box. Assume he defined the respective method in

 controller which can return Map<String.Double>. Rohit is supposed to bind the

 key as label attribute value as value attribute in the drop-down box. Choose

 from below a valid option

<form:select path="items">

<form:option value="label="select"/>

<form:options items=$(itemsList)"/>

</form:select>

Rohit wants to display the success message in success.jsp page as mentioned

 in the requirement 2. Help him to display the purchase date in dd-MMM-yyyy 

pattern. Choose from below a valid option.

<%@ taglib url="http://java.sun.com/jsp/jsti/fmt" prefix="fmt" %>

<fmt: formatDate value="$(date)" type="date" pattern="dd-MMM-yyyy" />

Rohit wants to validate the quantity entered by the customer as mentioned in

 Requirement 2. Choose from below valid options [Choose 2]

option 1: Add @Range (min=1, max=10) annotation in the bean class

option 2: The request handler method should include @valid to

 @ModelAttribute parameter

Rohit wants to receive the requests from customers and forward those requests

 to other components of the application for further processing. Choose from

 below the most appropriate option which rohit perform as his first step as per 

Spring-MVC workflow.

Configure the DispatchServlet provided by Spring framework which

 acts as a front controller

Rohit wants to externalize the vakidation error messages. So he defined the 

messages in "com/accenture/lkm/sources/messages_en.properties" file. 

Help Rohit to configure the MessageSource bean in the context file by choosing

 a valid option from below.

<bean id="messageSource"

class="org.spring/framework.context.support.ReloadableResourceBundleMessageSource"

<property name="basename"value="classpath:com/accenture/lkm/resources/messages.properties" />

</bean.

Rohit wants to navigate to success.jsp page on successfull submission.

 Assume he wrote a handler method to return ModelAndView with logical view name 

as success. He needs to configure a view resolver bean in child configuration fike to

 resolve the logical view name. Choose form below a valid option.

<bean class="org.springFramework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jspViews/</value>

</property>

<property name="suffix">

<value>jsp</value>

</property>

</bean>

Rohit deployed the application in the Apache Tomcat server. But he got an exception

 as "org.srpingframework.beans.factory.NoSuchBeanDefinitonException: No qualifying 

bean of type [com.accenture.lkm.dao.PurchaseDAo]". Choose from below valid options

 to succesfully execute his application [choose2]

option 1: Configure <context.component-scan base-package="com.accenture.lkm.dao"/> in the context 

 configuration

option 2: Configure <mvc:annotation-driven/> in the child context configuration

Rohit wants to display all the validation error messages in purchase jsp. help him to 

display those messages at the bottom of the page choose from below a valid option

 assume the below taglib directives are added in the JSP.

<%@taglib url=”http://www.springframework.org/tags/form” prefix=”form”%>

 <%@taglib url=”http://www.springframework.org/tags/form” prefix=”spring”%>

<form:form.method="POST" modelAttribute="bean" action="store.html">

<lable border="3">

<!--Assume form elements are mentioned="bean" action="store.html">

</table>

<spring hasBindErrors name="bean">

<h3>All Errors</h3>

<form:errors path="*" cssClass="error"/>

</spring hasBindErrors>

</form:form>

P2:RAGHAV

the admin can get the details of patient who have taken appointment of particular doctor 

suggest method name to raghav so that method signature can be converted into JPQL

query. plz refer patient class List<Patients>findByDoctorNnameEquals(String name)

help raghav to select correct JPQL query to retrieve all details of patients based o their name

for below method declared in DAO layer

List<Ptients>getPatients(String name); @Query("select p from Patients p where p pName=?100"0

raghav must pre-populate doctor's names from doctors table in drop-down list when patient 

is booking appointments online. he has written required method implementations in DAO and

service layer but he wants stuck in controller layer and not understanding how to 

prepopulate doctor;s name.meera helped raghav in writing method successfully. guess what meera

has sugested

use @ModelAttribute on method in controller class when invokes 

the service class method returning

the doctor's name from DAO layer

which are mandotory annotations raghav should use in patient class @Entity and @Id

help raghav to choose from below valid option to be used DAO layer so that boilerplate 

code can be reduced and queries can be genrated automatically spring JPA data

raghav has added method to update details of the patients as below 

public interface patientsDAO{

@Query(name="updateQuery1")

int updateAppointmentSlot(Patients patients , String newAppointmentTime):

}

but he is getting exception as DML operation is not supported" . wat went wrong @Mmodifying is not used on method and no changes required in method signature

raghav added following methods in service and DAO implemntations class

 to add patient's information in database

//

//

what is the behaviour of addPatientsDAO method

addPatientInDAO() method always executes in new transaction rather than the 

transaction started in service layer pf addPatientService() method

raghav added following query in orm.xml file

//

select correct method declaration in DAO interface. refer patients class and patients table @Query(nme=getPatientsData)

List<Object()>getPatientsData

"Meera is responsible for creating all the view pages. She wants to create a page, so that the values 

entered by the user could be mapped to the bean properties automatically. Suggest her to achieve this." Use Spring form tags

"Meera wants to render the model objects on a view without tying to a specific view technology and 

wants to map the logical view names to the actual view names. What do you suggest her to use?" Configure ViewResolver in servletchild web application context

P3:HARRY

To integrate Spring framework with JPA and get complete support of transaction management, 

Harry needs to create a bean in the spring configuration le Choose the most appropriate option.

<bean id = "entityManagerFactory"

class = "org.springframework.jpaLocalContainerEntityManagerFactoryBean">

 <!__ Assume properties are assigned properly>

</bean>

Harry added the Spring MVC form select tag in newPost.jsp to auto populate the values 

in the drop-down list as shown below 

<form:select path="themes">

 <form:options items="${themeMap}" />

<form:select>

Which of the following method must be added in controller class to achieve the same? 

Choose the most appropriate option.

Map<String, String> themeMap = new pathMap<String, String>

themeMap put("DJ", "Daily Journal");

themeMap put("CU", "Cheer Up");

themeMap put("JB", "Joy the Baker");

themeMap put("NY", "The New York");

return themeMap;

Harry creates a method in controller class to redirect to newPost.jsp page. He wants to use 

view resolver to map logical view names to actual views. Which of the following bean 

configuration should be added in spring MVC configuration file? Choose the most 

appropriate option.

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/"/>

<property name="suffix" value=".jsp"/>

</bean>

Harry needs to write a JPQL query to count number of posts entered by a user as mentioned 

in the requirement.

Choose from below valid options. [Choose 2]

Add the below code in the DAO layer

 Query query = entityManager.createQuery("select count(") from postEntity m where 

m.email = email") 

Add the below code in the Entity class 

@NamedQuery(name = "countPostsByName", query = "select count(") from PostEntity m where 

m.email = email")"

Harry wants to create container managed Entity Manager for managing the entities and their 

life cycle. 

Choose the right annotation to be used in DAO layer from below options. [Choose 2]

@PersistenceContext 

private EntityManager entityManager; 

@PersistanceContext(type = PersistanceContextType.TRANSACTION) 

private EntityManager entityManager;"

Harry needs to define spring beans and dependencies using dependancy injection annotations 

and bean annotations. To activate both these annotations he should add one.xnl element in 

the spring configuration file. Choose from below a valid option.

<context:component-scan base-package="com.accenture"/>

Harry wants to use spring declarative transaction using @Trasactional annotation. Which of 

the following should be added in the spring configuration file to enable transaction 

management using annotations? Assume JpaTransactionManager bean with the name 

txtManager is defined in the spring configuration file. Choose the most appropriate option.

<tx:annotation-driven transaction-manager="">

Harry needs to configure Dispatcher Servlet in the deployment descriptor (web.xml) for 

his application. 

Help him to choose from below a valid option

<servlet>

 <servlet-name>dispatcher</servlet-name>

 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

</servlet>

<servlet-mapping>

 <servlet-name>dispatcher</servlet-name>

 <url-pattern>*.html</url-pattern>

<servlet-mapping>

Harry need to mark postId field as primary key and the value for primary key column should 

be autogenerated.

Which of the following annotations should be specified in the entity class? Choose the 

most appropriate option.

@Id

@GeneratedValue(strategy="GenerationType.AUTO)

private int postId;

Harry want to validate the mandatory fields(email and title) of newPost.jsp page as per the 

requirement.

Chosse from below valid options[Choose 2]

1.Add @NotNull annotation for email and title field in the bean class

2.The request handler method should include @Valid annotation to @ModelAttribute parameter

P4:EDWIN

Edwin want to use DispatcherServlet as a front controller for his Spring MVC

application. Help him to configure the same in web.xml. Option C

Edwin wants to create a handler method in the controller for booking tickets.

He needs to validate the themeparkBean retrieved from the bookPage.jsp page. 

Upon validation if any error raised , error message should be displayed on 

same page. If there are no error request should be processed and booking message

should be displayed on successpage.jsp page as per requirement. Choose from 

below a valid option.”

@RequestMapping(“processBooking.html”)

Public ModelandView bookTicket@valid@ModelAttribute(“themeparkBean..

ThemeParkBean

themeparkBean,BindingResult result(){

String viewPage = “”;

ModelAndView mv= new ModelAndView();

If (!result hasError()){

viewPage =”bookPage”;

……………………………..

….

OPTION A

Edwin wants to display the list of show details in viewItems.jsp page. 

Assume he defined the respective method in the controller which can 

return the map with the name as shown. Edwin need to get this map,

iterate the ……….structure.Choose from below a valid code. Option C

Edwin wants to create a method in the controller to handle the request

for booking ticket.He also wanted to get the themeparkbean model attribute

from bookPage.jsp and need to validate it. Help him choose a valid option

@RequestMapping(“processBooking.html”)

Public ModelAndView bookTicket@Valid @ModelAttribute(“themeparkBean”)

ThemeParkBean

 ThemeparkBean, Bindingresult(result)

OPTION B

Edwin wants to create jsp pages in the custom location "WEB-UNF/jspViews".

Help him to Configure the bean to identify the jsp page from the specific location.

<bean class ="org.springframework.web.servlet.View.InternalResourceView….”)

<property name=”prefix”>

 <value>/WEB-INF/jspViews/</value>

</prporty>

</property name = “suffix”>

 <value>.jsp</value>

</property>

</bean>

OPTION B

Edwin wants to create a method in the controller

to handle the request booking ticket. He also 

wanted to get the themeparkBean model attribute

from bookPage.jsp and need to validate it.

@RequestMapping("processBooking.html")

public ModelandView book Ticket@Valid @ModelAttribute("themeparkBean")

ThemeParkBean 

 themeparkBean,BindingResult(result)

Edwin wants to create jsp pages in the custom

location "WEB-INF Views". Help him to configure

the bean to identify the jsp pages from the specified

location.

<bean class='org.springframework.web.servlet........

 <property name='prefix'> 

 <value>/WEB-INF/jsp... 

OPTION B

Edwin wants to create a handler method in the

for booking tickets. He needs yo validate the

themeparkBean retrived from the bookPage.jsp

page. ....... should be displayed on successpage.jsp

page as per requirement.

@RequestMapping("processBooking.html")

public ModelandView book Ticket@Valid @ModelAttribute("themeparkBean")

ThemeParkBean 

themeparkBean,BindingResult(result)

 String viewPage... 

OPTION A

Edwin wants to auto populate the shows available

in the drop-down box placed in bookPage.jsp. He

needs to create respective method in the controller

.............. that helps to auto populate in drop-down 

box.

@ModelAttribute("shows")

 public Set<String> getShows() {

 Map<String Double>....... 

OPTION B

Edwin wants to display the list of show details in viewitems.jsp page. Assume

he defined the respective method in the controller which can return the Map

with the name as shows.Edwin needs to get this map ......tabular structure. OPTION C

Edwin wants to auto populates the rides available in the drop down box placed in the 

bookPage.jsp. Help Edwin to implement a proper handler method in the controller that

 can retrieve rides defined in the DAO layer. Choose from the below valid code

OPTION A

create a method in controller with 

@ModelAttribute annotation to… DAO layer method which returns the Map of rides

Edwin want to create a spring form radio button to get the input on the camera inclusion

 for the field “is camera included or not” , it helps him to calculate the total cost.

Option A

<label> is camera included?</label>

<form.radiobutton path = “isCameraIncluded” value= “yes” …..yes”>

<form.radiobutton path= “isCameraIncluded” value = “no”…..no”>

Edwin wants to validate no of tickets entered by customer as per the requirement .

choose from the below option(choose2)

OPTION A,C

Add @NotNull @Range(min = 1, max=10…………)

The request handler method should include@Valid annotation to @ModelAttribute parameter

P5:George

George wants to auto populate the categoryName dynamically from the category table,

in the drop-down box placed in qaFrom.jsp. To accomplish this,help George to choose a

method that returns List<CategoryBean> in DAO layer. Choose from below a valid option.

public List<CategoryBean> get Categories(){

 List<CategoryBean> listBean=new ArrayList<>();

 Iterable<CategoryEntity> it=categoryDao.findAll();

 for(CategoryEntity.entity.it){

 CategoryBean bean=new CategoryBean();

 BeanUtils.copyProperties(entity.bean);

 listBean.add(bean);

 }

 return listBean;

In qaFrom.jsp grade selectedshould be less than or equal to the categoryGrade that is

provided for the selected catagoryName in Category table as per the requirement. 

Otherwise it should throw CategoryGradeNotMathchException. George wants to write a logic

for the same. Choose from below a valid option.

public boolean validateCategoryGrade(QABotBean qaBean){

 boolean flag=false;

 List<CategoryBean>

listBean= categoryDaoWrapper.getCategories();

 for(CategoryBean bean:listBean){

 if(qaBean.getCategoryId()==bean.getCategoryId)

 {

 if(qaBean.getCategoryGrade()

 <=bean.getCategoryGrade())

 {

 flag==true;

 break;

 }

 else

 throw new

 CategoryGradeNotMatchException("Category

 does not match with Grade");

 }

 }

 return flag;

}

George wants to perform the curd operation and transactions using the DAO interface that

extends CurdRespository. Which of the following annotation is used to inject the DAO interface? @Transactional

George wants to create a radio botton in qaFrom.jsp for categoryGreade. It should contain the 

values 10,20,30,40.Choose the correct one from below options.

Grade<from.radiobutton path="categoryGreade" value="10"/>10

<from.radiobutton path="categoryGreade" value="20"/>20

<from.radiobutton path="categoryGreade" value="30"/>30

<from.radiobutton path="categoryGreade" value="40"/>40 Option A is the ans

George wants to use a bean that gives complete support and fine-grained control over the creation

of JPA specific EntityManagerFactory. It also gives complete support for transaction

management . Help him to configure the same. Choose from below a valid option.

<bean id="entityManagerFactory"

class="org.springframework.com.jpa.LocalContainerEntityManagerFactoryBean>

<!-Assume all the DataSource and JPAVendorAdapter has been provided->

<property name="packagesToScan" value="com.accenture.lkm.entity></property>

</bean>

<bcannotation-driven transaction-manager="bcManager"/>

<bean id="bcManager" class="org.springframework.orm.jpa.JpaTransactionManager">

 <property name="entityManagerFactory" ref="entityManagerFactory" />

</bean> Option D

George wants to auto populate the categoryName dynamically, in the drop-down box placed in 

qaFrom.jsp. Assume he defined the respective method in the controller which returns a Map He

is supposed to bind this map with drop-down box. Choose from below a valid option.

<form : select path=" categoryName">

 <form:option value="" label=" select "></form:option>

 <form:options items= '$(categoryMap)'/>

</form:select>

George wants to handle custom exception called CategoryGradeNotMatchException . He would 

like to create a custom exception. Choose from below a valid options.

public class CategoryGradeNotMatchException extends Exception {

 public CategoryGradeNotMatchException(String mess) {

 super(mess);

 }

}

George wants to validate the answer text field entered by the user as per the requirement. Help

him to provide an annotation on a bean property. Choose from below a valid option. Add @NotEmpty @Size(min=1, max=50) annotation in the bean class

George wants to write a method in controller to process the request submitted from qaReportLjsp.

It should take the model data from qaReportLjsp and bind it with a ReportBean. Also validation 

should be triggered. If the validation fails, it should retain in the same page by displaying error messages.

otherwise it should display the result in the same page. Choose from below a valid option.

Note: Model object name provided as "ReportBean".

@RequestMapping("processReportFormhtml")

 publicModelAndView processReportForm(@ModelAttribute("reportBean")@validReportBean

 reportBeanBindingResult(result) {

 ModelAndView mv=new ModelAndView();

 if(resulthasError()) {

 mv.setViewName("qaReport");

 else {

 QABolBean ans= qaService.getAnswer(reportBean.getCategory Name());

 mv.addObject("listBean", ans);

 mv.setViewName("qaReport");

 return mv;

}

George wants to handle the exception "CategoryGradeNotMatchException" that is throw when the selected

category and grade does not match according to the category table. Help him to select the appropriate code

that he can include in controller, so that exception is handled properly.

@ExceptionHandler(CategoryGradeNotMatchException class)

 public ModelAndView handleException(CategoryGradeNotMatchException) {

 ModelAndView mv= new ModelAndView();

 mv.addObject("mess", exception.getMessage());

 mv.addObject("exceptObject", exception);

 mv.setViewName("exceptionHandlerPage");

 return mv;

}

P6:AJAY

Ajay want to define register cashback() method in controller . it must be mapped to URL pattern

"registration.htm". the parameter model attributes "cashbackBEAN" hold the form populated 

cashbackBEAN object. if invalid input are provided by user then redirect to cashbackpage.jsp

page and display error message.otherwise redirect the user to success.jsp page and display

 calculated totalcashback with a success message. which of the below code snippets can be

 used by AJAY to achieve these requirements. Option D

ajay want to create a apge cashbackpage.jsp so that values entered by the user could be 

mapped TO cashbackBean bean properties automatically select valid option that will help Ajay use spring from tags inside cashbackpage.jsp

ajay has written below code snippet on cashbackpage.jsp page

<form option items="$(productName)"/>

to bind the data in above code snippet he should write a method in the controller class this 

method must be excecuted before any processing starts inside other handler method of controller

choose from below an invalid option

public set<string> get productNames(@modelattribute(value="productNames")){

map<string,double>map=cashbackservice.getproductpricesmap();

return map.ketset();}

ajay has used@controller and@autowired annotations inside contriller class. he needs to define spring

beans and dependencies using dependency injection annotations and beans and annotations . which 

among the below tags can be written in the spring bean configuration xml file to activate these annotations? <context.component-scan base-package="com.accenture"/>

ajay understand that its a good practice to put JSP files(that just serve as views)under WEB-INF. this help tow hide

them from direct access (e.g via a manually entered Url). omly controllers will be able to access them.help him

to configure a view resolverbean in child web application context configuration file

<bean class="org.springframework.web.servlet.view.internalresourcesviewresolver">

<property name="prefix"value="/WEB-INF/"/>

<property name="suffix"value=".jsp"/>

</bean>

Ajay wants to create a page cashbackPage.jsp that accepts user inputs. The page helps on 

registering the cashback request by selecting career level and product name.

He wants to create the page using tags( like <sptags:form>, ,sptags:options>,<sptags;errors>)

that can bind the user input with Spring Model object exposed by controller Select valid taglib

derective <%@ taglib prefix="sptags" url="http;//www.springframework.org/tags/form"%>

Ajay wants to display the list of employee career levels and correspondiong cashback

percentage on the cashbackMaster.jsp web page. He has created a request handler method

in the Controller, that can add cashbackPercentMap to the spring Model

Refer cashbackpercentMap : map<String, Double> as given Requirement 1.

Assumethat valid taglibs are added in jsp page.

which of the below options is the coirrect syntax to display the data on the jsp?

<c forEach var ="map" items="${cashbackpercentmap}">

<tr>

<td>${map.key}</td>

<td>${map.value}</td>

</tr>

</c:foreach>

Consider below code snippet

<servlet>

<servlet-name>dispatcher</servelt-name>

<servlet-class>org.springframework.web.servlet.Dispatcherservlet</servlet-class>

</servlet>

<servlet-mapping>

<srvlet-name>dispatcher</servlet-name>

<url-pattern>*html</url-pattern>

</servlet-mapping>

Choose from below a valid option

Ajay has used the given snippetto configure Spring MVCfrontend controller in the 

deployment descriptor web.xml file

Ajay wants to display Career Level in drop-drown box on cashbackPage.jsp page. help him 

to define a method in controller class, that can retrieve career levels from 

CashbackPercentmap defined in DAO layer. This method must be executed before any

processing starts inside other handler method of controller

Choose from below a valid option

@ModelAttribute("careerLevels")

getCareerLevels(){

Map<String, Double> map = cashbackService.getcashbackPercentMap();

return map.keySet();

}

Ajay wants to define showCashbackPage() metod in controller and map it to URl pattern

loadcashbackpage.htm and request method GET.the method should define cashbackBean

as Spring Model object and redirect to cahbackPage.jsp view.

Select an invalid code snippet for the method from given options

Assume correct view resolver configuration is already present

@RequestMapping(url="loadcashbackpage.htm", method = GET)

public ModelAndView showcashbackPage(){

return neww ModelAndView("cashbackPage","cashbackBean",new ........

P7:Fred

Fred a newbie want to understand the SpringMVC request lifecycel.From the following 

options Identify the correct order of the steps performed by FrontEnd Controller.

 A) Tries to find and load the servletname-servlet.xml. 

B)Creates Spring context DispatcherServlet WebApplicationContext

. C)It reads the ServletName configured in web.xml C,A,B

.................other than the standard location......... Option D

Fred wants to explore the Spring Model in Spring MVC, Aid him by identifying two 

correct options

1)BackendController uses Spring Model to share data to view and vice versa. 2)

Spring Model gets refreshed each time a request is submitted.

Fred .............. spring bean such as service and DAO, so that these 

beans ............... Spring MVC application, even before the first

request................ He must use RootWebApplicationContext

Fred wants to code a request handler to handle the request submitted from appointment 

app.The request handler will validate the bean fetched from appointment.jsp and display 

the validation error in appointment.jsp. If any,Otherwise nevigated to successorder.jsp to 

display total cost with success message as specified in Requirement 2. Option D

Fred wants to validate the username entered by the user buy using custom 

annotations at specified in Requirement-1. Choose Two correct options from

the following to create a custom annotation.

Answer : A & B

A.Define UserNameValidator annotaion by using

 //Assume required 

 @interface....{

 //Assume....

 }

B.Define the validation tags

Fred Deployed the application in the Apache tomcat server. 

Whenever chosen test is not available at chosen branch TestExceptionPage

must be displayed as specified in Requirement-2. To his surprise, he found that always

GeneralizedExceptionHandlingPageis is displayed . Help him by chooding the 

correct statement to be added in the backend controller from the following. 

Assume that he is using custom exception named TestNotAvailableException.

Answe:A 

@ExceptionHandler(value= TestNotAvailableException.class)

public ModelAndView handler TestNotAvailableException(

 TestNotAvailableException exception ){

 ModelAndView modelAndView = new ModelAndView();

 modelAndView.setViewName("TestExceptionPage");

 modelAndView.addObject("message",exception.getMessage());

 return modelAndView;

}

Only anwer was visible..

Option A: When @ModelAttribute placed at method level they are executed 

before executing any handler method.

....must be mapped in actual views using view resoler.

From...must be used in case he choose to use suffix and ...

Option D: InternalResourceViewResolver

Fred Deployed the application in the Apache tomcat server.

But to his shock he found the error...in the messages.properties file

created i the package. LKM.resources was not displayed in the appointment.jsp,

instead default error displayed. he checked the code and found that he had

added correct message attribute in bean class. By choosing one of the

following options.

Option D

P8:JAS

JAS wants to auto populate the restaurants names reservations timings in the drop down and radio buttons respectively 

in the CreateReservation.jsp Name and Value will be different(refer the tables in the question description)

JAS wants to create code in the DAO layer that returns the name and value for the Restuarants and reservation timings 

choose one valid option from below to help JAS complete the requirement

public Map<String, String> getRestaurants(){

LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

map.put("JAS-Restaurant in Hyderabad","JAS-Restaurant");

map.put("MSD-Restaurant in Bangalore","MSD-Restaurant");

.

.

.

.

JAS wants to submit the CreateReservation.jsp form to complete the booking. He provided all the details and submitting 

the form with POST method and action name as "/reserveTable" this submission even goes through the validations.

choose one valid option from below to help JAS identity the correct method signature to fulfill the requirment

@RequestMapping(value = "/reserveTable", method = RequestMethod.POST)

public ModelAndView reserveTable(@Valid @ModelAttribute("restaurantBean")

RestaurantBean restaurantBean, BindingResult bindingResult) throws Exception{

.

.

.

.

JAS has coded the RestaurantBean class as shown to save the reservation details,this class even acts as a model class 

for spring form.

public class RestaurantBean {

 private integer restaurantid;

 private string name;

 private integer tableNo;

 private string reservedtime='Morning",

 private integer capacity;

 private string customerName;

 private date dateofreservation;

}

 It is required to add validation specific annotations to the above restaurantbean class sich that all the validation given 

in the requirment 2 are fulfilled.

choose one valid option from below to help JAS complete the requirment

public class RestaurantBean {

private Integer restaurantId;

private String name;

@NotNull(message = "Table number can't be null");

@Range(max = 12, min = 1, message = "Table number should not be between 1 and 12")

.

.

.@NotEmpty(message = "Customer name cant be empty")

.

.

.

JAS wants to display all the validation messages at the bottom of CreateReservation.jsp.

Choose the valid option from below to help JAS complete the requirement.

<%@taglib uri = "http://www.springframework.org/tags" prefix = "spring" %>

.

.

.

<form:errors path="*" cssClass="error"/>

</spring:hasBindErrors>

JAS wants to customise the RestaurantDAO repository layer to expose only the save() method and add a custom 

method to retrieve the list of reservations with the given restaurant name.

Choose one valid option from below to help JAS complete the Requirement.

@RepositoryDefinition(domainClass = RestaurantEntity.class, idClass = Integer.class)

@Transactional("txManager")

public interface RestaurantDAO{

RestaurantEntity save(RestaurantEntity restaurantEntity){

@Query("SELECT E FROM RestaurantEntity E WHERE E.name =: name");

List<RestaurantEntity> getReservationsByRestaurantName(@Param("name")String restaurantName);

}

JAS wants to display the validation error messages in the CreateReservation.jsp page and he wants to use the class to 

decorate the text in Red color and italic style. Choose one valid option from below to help JAS comple the Requiremen.

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form" %>

<style>

.error{

color : red;

font-style : italic;

}

</style>

.

.

JAS wants to add the view resolver configuration in dispatcher servlet of the application and

configure it to display the JSP pages form jspViews folder under WebContern/WEB-INF folder

Choose ona valid option from below to help JAS complete the requirement.

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

.

.

.

<html>

<body>

<center> 

<h2>Employee Details </h2>

<c.if test="$(not empty reservedTablesList)">

<tale border="2">

<tr>

<th>CustomerName</th>

<th>TableNo</th>

<th>ReserverTime</th>

<th>DateoOFReservation</th>

</tr>

<!--Line1--->

</table>

</c:if>

<c:if test="${empty reservedTablesList}">

<h2>No reservation availale for the selacted Restaurant</h2>

</c:if>

</body>

</html>

<c:forEach var ="var" items="${reservedTablesList}">

.

.

.

.

.

<beans>

<bean id="datasource"

class="oeg springframework jdbc.datasource.drivemanagerdatasource">

<property name="driverclassName"value="${cst_db_driver}"/>

<property name ="url"value="${cst_db_url}"/>

<propery name ="username" value="${cst_user)"/>

<property name="password"value="{cst_password}"/>

</bean>

 <!_Assume rest of the confugartion to create EntityManagerFactory;

 TransactionManager, enable JPA Repositories are configured properly-->

</beans>

<bean class="org.springframework.beans.factory.config.PropertyPlaceHoldeConfigurer">

<property name="location">

.

.

.

JAS wants to auto popular the Restaurarnts names and Reservation timings in dropdown and

radio buttons of CreateReservation.jsp before the pages as mentioned in Requirement 

2,

Assume the controller is coded with the respective @modelattribute annotated methods.

Choose ona vaild option from below to help JAS complete the Requirement.

<tr>

<th> RestaurantName </th>

<td>

<form:select path="name">

<form:options items="${restaurants}"/>

</form:select>

</td>

</tr\>

<tr>

<td> Time to Reserve </td>

<td><from:radioButtons path="reservedTime" items="${reserveTimings}"/></td>

</tr>

P9:LISA

Lisa wants to add the view resolver configuration in dispatcher

 servlet of the application Consider the project structure given below:

dispatcher-web-servlet.xml

Assume JSP pages are placed under ViewPages folder. 

Choose the valid view resolverconfiguration to be placed in

 dispatcher-web-serviet.xml file.

A

Lisa wants the validation messages to be displayed at the bottom 

of the Booking.jsp page.

Choose the valid option from below.

C

Lisa wants to create a method to calculate and return the 

total cost to be paid during check-in from the details entered

 by the customer in Booking.jsp page such that: 

totalCast=foodServiceCost+ (roomCost*noOfRooms)

where foodServiceCost is a Double[] Choose from below a valid option.

B

Lisa wants to auto-populate the drop-down in Booking.jsp with Hotel Names.

 Create a method in DAO layer with a JPQL query to return the List<String>

 with Hotel Names as a value.

Choose the appropriate JSP code to create the dropdown.

Assume the Entity class is named as HotelEntity Choose a valid code 

from below options.

B

Lisa wants to externalize the JPQL query to orm.xml flie, 

to retrieve the roomCost of HotelEntity where the hotel

Name matches the given holelName.

[Note: It is required to use positional parameters in the query].

 Choose a valid option from below to fulfil this requirement. 

A

Lisa wants to create an interface named HotelBookingDAO as

 a Data JPA repository to save HotelBookingEntity to the DB table.

 Help her in finding the right way to do it.

 Choose valid options from below (Choose 2) C & D

Lisa wants to submit the Booking.jsp form to complete the booking. 

She provided all the details, submitting the form with POST method 

and action name is "/saveBooking". It is also required to validate the

 form fields Help Lisa to identify the appropriate

 controller method to be created to service the request ? [Choose one] D

Considering the Requirement 2, Lisa wants to add validation specific 

annotation to HotelBookingBean class Help her in identifying the 

correct bean class with proper validation annotations. 

Choose one valid option from below

D

Lisa wants to auto populate the drop-down in Booking.jsp with Hotel Names.

 Create an appropriate method in controller layer that returns the 

List<String> with Hotel Names as a value. Choose the appropriate JSP code to 

create the dropdown. Choose a valid option from below B

Lisa wants to auto populate the check boxes with FoodServices names in Booking.jsp.

 Create a method in DAO layer with a JPQL query that returns the List<FoodServicesEntity> 

and populate it to Map <Double,String> such that FoodServicesEntity's attribute costOfService

 becomes the key, FoodServicesEntity's attribute foodServiceName becomes the value and

 return the map. Assume the Entity class is named as FoodServicesEntity and FoodServicesEntity's

 attribute costOfService is unique. Choose a valid code from below options. B

Scenario--explain

What was the requirement in scenario

Explain the scenario Annotations for validation on no. Of tickets

Case Study - your experience

Interface

Front controller--A front controller is defined as a controller that handles all requests for a Web Application.

DispatcherServlet servlet is the front controller in Spring MVC that intercepts every request and then

dispatches requests to an appropriate controller.

Configuration--@Configuration annotation indicates that a class declares one or more @Bean methods and

may be processed by the Spring container to generate bean definitions and service requests for those

beans at runtime

******Mvc flow--prefer video**********

******What are the steps in implementing spring mvc with jpa--Video(Naveen reddy)******

 Difference between post and put--PUT is meant as a a method for "uploading" stuff to a particular URI, or

overwriting what is already in that URI. POST, on the other hand, is a way of submitting data RELATED to a

given URI.

Methods of http--The primary or most commonly-used HTTP methods are POST, GET, PUT, PATCH, and

DELETE. These methods correspond to create, read, update, and delete (or CRUD) operations,

respectively. There are a number of other methods, too, but they are utilized less frequently

Advantages of JPA--that in JPA data is represented by classes and objects rather than by tables and

records as in JDBC

Spring JPA data--

Java Persistence API (JPA) is a specification provided by Java for APIs accessing various SQL databases.

... Spring Data JPA is a sub-project of Spring Data and provides abstraction over the Data Access Layer

using Java Persistence API and ORM implementations like Hibernate.

 JSP in detail.---prefer video

Life cycle of entity and servlet--

Servlet class is loaded.

Servlet instance is created.

init method is invoked.

service method is invoked.

destroy method is invoked.

The life cycle of entity objects consists of four states: New, Managed, Removed and Detached. When an

entity object is initially created its state is New. In this state the object is not yet associated with an

EntityManager and has no representation in the database.

An entity object becomes Managed when it is persisted to the database via an EntityManager’s persist

method

A managed entity object can also be retrieved from the database and marked for deletion, using the

EntityManager’s remove method within an active transaction.

The last state, Detached, represents entity objects that have been disconnected from the EntityManager.

For instance, all the managed objects of an EntityManager become detached when the EntityManager is

closed.

Diff btw interface and abstract class---Abstract class

 Interface

1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract

methods. Since Java 8, it can

have

default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple

inheritance.

3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and

final variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the

implementation of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used

to declare interface.

Spring data jpa annotations----@Transactional,@NoRepositoryBean,@Param,@Id,@Transient,@Query,@

Procedure,@EnableJpaRepositories,@Modifying,@Lock

jdbc and orm ---->>>>>

ORM responsible for establishing connections with the database, unlike JDBC. It uses Query Language to

communicate with the database and execute the queries.

After, ORM maps itself the results to corresponding Java objects.

maven ---->>>>>

Maven is a powerful project management tool that is based on POM (project object model). It is used for

projects build, dependency and documentation.

It simplifies the build process like ANT. ... In short terms we can tell maven is a tool that can be used for

building and managing any Java-based project.

Jpql vs SQL--->>>

The main difference between SQL and JPQL is that SQL works with relational database tables, records and

fields, whereas JPQL works with Java classes and objects.

For example, a JPQL query can retrieve and return entity objects rather than just field values from database

tables, as with SQL.

Spring security--->>>>

Spring Security is the primary choice for implementing application-level security in Spring applications.

Generally, its purpose is to offer you a highly customizable way of implementing authentication,

authorization, and protection against common attacks.

Autowired, dependency injection, how to achieve dependency injection

Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.

The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter

methods.

The design principle of Inversion of Control emphasizes keeping the Java classes independent of each

other and the container frees them from object creation and maintenance.

Ioc---->>>>

Spring IoC Container is the core of Spring Framework. It creates the objects, configures and assembles

their dependencies, manages their entire life cycle.

The Container uses Dependency Injection(DI) to manage the components that make up the application. ...

These objects are called Beans.

Crud repositories vs jpa repository--->>>>

Their main functions are: CrudRepository mainly provides CRUD functions. PagingAndSortingRepository

provides methods to do pagination and sorting records.

JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting

records in a batch.

What is dispatchservelet?--->>>

The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers

(generally methods on Controller classes) and

views (generally JSPs) that combine to form the page or resource that's supposed to be found at that

location.

What is Junit?----->>>>

JUnit is an open source framework designed for the purpose of writing and running tests in the Java

programming language. ...

JUnit allows the developer to incrementally build test suites to measure progress and detect unintended

side effects. Tests can be run continuously.

 Results are provided immediately.

What are the configuration is java?--->>>>

Spring JavaConfig is a product of the Spring community that provides a pure-Java approach to configuring

the Spring IoC Container.

While JavaConfig aims to be a feature-complete option for configuration, it can be (and often is) used in

conjunction with the more well-known

XML-based configuration approach.

What is final keyword?----The final keyword in java is used to restrict the user.If you make any variable as

final, you cannot change the value of final variable,If you make any method as final, you cannot override it,If

you make any class as final, you cannot extend it,

Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it.

Which annotation is used for autopopulating?

 you want your beans auto-detected and then to collect them automatically.

So annotate your B, C, D classes with @Component -like annotations (e.g. @Component, @Service,

@Repository, @Controller etc.), and then use @ComponentScan to detect them. (@Bean is used for other

purposes, you didn't use it properly in your example).

Then you collect all beans of type A with @Autowired annotation:

Collection---The Collection in Java is a framework that provides an architecture to store and manipulate the

group of objects.

Differences between arraylist and vector.---ArrayList

 Vector

1) ArrayList is not synchronized.

 Vector is synchronized.

2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity.

Vector increments 100% means

 doubles the array size if the total number of

 elements exceeds than

its capacity.

3) ArrayList is not a legacy class. It is introduced in JDK 1.2.

 Vector is a legacy class.

4) ArrayList is fast because it is non-synchronized. Vector is

slow because it is synchronized, i.e.,

 in a multithreading environment, it holds

the

other threads in runnable or non-runnable state until

 current thread releases the lock of the object.

5) ArrayList uses the Iterator interface to traverse the elements. A

Vector can use the Iterator interface or

 Enumeration

entitymanager---- The EntityManager API is used to create and remove persistent entity instances, to find

entities by their primary key, and to query over entities.

pathvariable.....---the @PathVariable annotation can be used to handle template variables in the request

URI mapping

jpa directives...----JSP directives are the elements of a JSP source code that guide the web container on

how to translate the JSP page into it’s respective servlet.

Page directive

Include directive

Taglib directive

implicit objects-----These Objects are the Java objects that the JSP Container makes available to the

developers in each page and the developer can call them directly without being explicitly declared. ... JSP

Implicit Objects are also called pre-defined variables

Autowired--Autowiring feature of spring framework enables you to inject the object dependency implicitly. It

internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works with reference only

Controller and autocontroller---Controllers interpret user input and transform it into a model that is

represented to the user by the view. Spring implements a controller in a very abstract way, which enables

you to create a wide variety of controllers.

View resolver----Spring provides view resolvers, which enable you to render models in a browser without

tying you to a specific view technology

Functional interface---A functional interface is an interface that contains only one abstract method. They

can have only one functionality to exhibit. A functional interface can have any number of default methods.

Runnable, ActionListener, Comparable are some of the examples of functional interfaces.

Inheritence---Inheritance is a mechanism of deriving new class from already existing class.(Reusability)

Bean scope---In Spring, bean scope is used to decide which type of bean instance should be returned from

Spring container back to the caller.

5 types of bean scopes are supported

1:- Singleton

2:-Prototype

3:-Request

4:-Session

5:-GlobalSession

Difference between comparable and comparator----

1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis

of a single element such as id, name, and price.

The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the

basis of multiple elements such as id, name, and price etc.

2) Comparable affects the original class, i.e., the actual class is modified.

Comparator doesn't affect the original class, i.e., the actual class is not modified.

3) Comparable provides compareTo() method to sort elements.

Comparator provides compare() method to sort elements.

4) Comparable is present in java.lang package.

A Comparator is present in the java.util package.

5) We can sort the list elements of Comparable type by Collections.sort(List) method.

We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

Internal view resolver---The InternalResourceViewResolver is an implementation of ViewResolver in Spring

MVC framework which resolves logical view name

JSP directives ---The jsp directives are messages that tells the web container how to translate a JSP page

into the corresponding servlet.

There are three types of directives:

page directive

include directive

taglib directive

Implicit objects---These Objects are the Java objects that the JSP Container makes available to the

developers in each page and the developer can call them directly without being explicitly declared. ... JSP

Implicit Objects are also called pre-defined variables.

Serializable--Serializable is a marker interface your classes must implement if they are to be serialized and

deserialized. Java object serialization (writing) is done with the ObjectOutputStream and deserialization

(reading) is done with the ObjectInputStream.

Question: what is serialisation and how to implement?

Ans: Just by writing implements serializable

Annotations used in entity and bean-->>>>>--annotate the component property as @Id and make the

component class @Embeddable.

annotate the component property as @EmbeddedId.

annotate the class as @IdClass and annotate each property of the entity involved in the primary key with

@Id.

how to validate the min. And max. Tickets in the scenario.. (this was the question in MCQs)

Session tracking and the ways which we can do session tracking.. how to do it in spring MVC..->>>>---

1-Session Tracking is a way to maintain state (data) of an user.

It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state

using session tracking techniques.

Each time user requests to the server, server treats the request as the new request.

2-User Authentication.

HTML Hidden Field.

Cookies.

URL Rewriting.

Session Management API.

3-Using spring security you can implement session tracking and apply filters to validate requests. Spring

security is very easy to implement.

Question: what is serialisation and how to implement? >-----

In Java, we create objects. These objects live in memory and are removed by the garbage collector once

they are not used anymore.

If we want to transfer an object, for instance, store it on a disk or send it over a network, we need to

transform it into a byte stream.

To do this, the class of that object needs to implement the interface Serializable. Serialization is converting

the state of an object into a byte stream.

This byte stream does not contain the actual code.

Ans: Just by writing implements serializable

Which JPA vendor did we use?-----Hibernate

Uses of annotations--->>

Annotations are used to provide supplement information about a program. Annotations start with '@'.

Annotations do not change action of a compiled program.

Annotations help to associate metadata (information) to the program elements i.e. instance variables,

constructors, methods, classes, etc.

Custom exception--->>>>

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard

Java exception. These can store additional information,

like an application-specific error code, or provide utility methods that can be used to handle or present the

exception to a user.

Spring boot and everything else that is spring --->>>

Spring Boot is an open-source micro framework maintained by a company called Pivotal. It provides Java

developers with a platform to get started

with an auto configurable production-grade Spring application.

What is spring boot is used for?

Spring Boot helps developers create applications that just run. Specifically, it lets you create standalone

applications that run on their own,

without relying on an external web server, by embedding a web server such as Tomcat or Netty into your

app during the initialization process.

Dispatcher and why---->

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is

declared in the web.xml of your web application.

You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the

same web.xml file.

====DispatcherServlet acts as front controller for Spring based web applications. It provides a mechanism

for request processing where actual work is performed

 by configurable, delegate components.

Question regarding component scan ----->>>

Using component scan is one method of asking Spring to detect Spring-managed components. Spring

needs the information to locate and register all the

Spring components with the application context when the application starts. Spring can auto scan, detect,

and instantiate components from pre-defined project packages

Difference between spring jpa and jpa data

Crud repository methods.----->>>>

CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type.

It provides several methods out of the box for interacting with a database.

METHODS--

Wrapper class---->>>>

A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object

to a wrapper class,

it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive

value into a wrapper class object.

Multi threading---->>>>Multithreading is a model of program execution that allows for multiple threads to be

created within a process,

executing independently but concurrently sharing process resources. Depending on the hardware,

threads can run fully parallel if they are distributed to their own CPU core

@modelattribute anotation

@SessionaAttribute

@configuration

@componentscan

@controller and @restcontroller

@Atcontroller and @Requestmapping

Spring Rest

Spring security

View resolver

How do u handle Exceptions in spring

No comments:

Post a Comment