In above code we create an
object of anonymous inner class but this anonymous inner class is an implementer
of the interface Hello. Any anonymous inner class can implement only one
interface
at one time. It can either extend a class or implement interface at a
time.
They allow to store heterogeneous objects.
A class is nothing but a
blueprint or a template for creating different objects which defines its
properties and behaviors.
Java class objects exhibit
the properties and behaviors defined by its class.
A class can contain fields
and methods to describe the behavior of an object.
Methods are nothing but
members of a class that provide a service for an object or perform some
business logic.
Java fields and member
functions names are case sensitive. Current states of a class’s
corresponding object are
stored in the object’s instance variables. Methods define the operations that
can be performed in java programming.
Below is an example
showing the Objects and Classes of the Cube class that defines 3 fields namely
length, breadth and height. Also the class contains a member function
getVolume().
This is
accomplished by stating the name of the object reference, followed by a period
(dot),
followed by the name of the member inside the object.(
objectReference.member ).
You call a method for an
object by naming the object followed by a period (dot), followed by the
name of
the method and its argument list, like this:
objectName.methodName(arg1,
arg2, arg3).
We use class variables
also know as Static fields when we want to share characteristics across all
objects within a class. When you declare a field to be static, only a single
instance of the associated
variable is created common to all the objects of
that class. Hence when one object changes the value
of a class variable, it
affects all objects of the class. We can access a class variable by using the
name
of the class, and not necessarily using a reference to an individual
object within the class.
Static variables can be
accessed even though no objects of that class exist. It is declared using
static
keyword.
Class methods, similar to
Class variables can be invoked without having an instance of the class.
Class
methods are often used to provide global functions for Java programs.
For example, methods in
the java.lang.Mathpackage are class methods. You cannot call non-static
methods
from inside a static method.
Instance
variables stores the state of the object. Each class would have its own copy of
the variable.
Every object has a state that is determined by the values stored
in the object. An object is said to have changed its state when one or more
data values stored in the object have been modified. When an
object responds to
a message, it will usually perform an action, change its state etc. An object
that has
the ability to store values is often said to have persistence.
Consider this simple Java
program showing the use of static fields and static methods
1) In Java we can mark
fields, methods and classes as final. Once marked as final, these items cannot
be changed.
2) Variables defined in an
interface are implicitly final. You can’t change value of a final variable (is
a constant).
3) A final class can’t be
extended i.e., final class may not be subclassed. This is done for security
reasons
with basic classes like String and Integer. It also allows the compiler to make
some
optimizations, and makes thread safety a little easier to achieve.
4) A final method can’t be
overridden when its class is inherited. Any attempt to override or hide a
final
method will result in a compiler error.
Method overloading results
when two or more methods in the same class have the same name but
different
parameters. Methods with the same name must differ in their types or number of
parameters.
This allows the compiler to match parameters and choose the correct
method when a number of
choices exist. Changing just the return type is not
enough to overload a method, and will be a compile
-time error. They must have a
different signature. When no method matching the input parameters is
found, the
compiler attempts to convert the input parameters to types of greater
precision. A match
may then be found without error. At compile time, the right
implementation is chosen based on the
signature of the method call
Below is a code snippet to
show whether a Class Object Represents a Class or Interface:
The Statement interface provides a standard
abstraction to execute SQL statements and return the
results using the
ResultSet objects.
A Statement object contains a single
ResultSet object at a time. The execute method of a Statement implicitly close
its current ResultSet if it is already open. PreparedStatement and
CallableStatement are two specialized Statement interfaces. You can create a
Statement object by
using the createStatement() method of the Connection
interface as:
in, out, inout are the modes of the variables in PL/SQl.
“
in” is input variable mode.
“out” is output variable mode.
“inout” is in-out variable mode.
Spring config.xml, SpringBean class,
SpringBean interface(POJI interface) and POJO class.
“order by”--> used to arrange the
data either in ascending or descending order.
“group by”--> allows aggregation
operations on a column .(having condition also).
Many to many.
107) What are the joins?
Cursors, views, stored procedures….
108) Which tools do you used
in design documents?
109) What is XML parser, SAX, DOM parsers?
110) Differences b/w
Statement and PreparedStatement apart from performance issue?
Q:
What are Statements types?
1) Statement: Statement is used to execute a
“query” only for one time in the entire application
execution.
2) PreparedStatement: PreparedStatement is
used to execute same “query” for multiple no. of times
with the same/different
values. It works with compiled query & allows place holders.
3) CallableStatement: It is used to execute
PL/SQL Procedures/functions from the Java appl.
111) How do you configured
Spring DAO?
In
contextApplication.xml
112) How to configure
“counter” to know no. of users visited
the website?
<%!
int count=0;
%>
<%
count++;
%>
<font color='green'
size=8>
The no of hits is:<%=count%>
</font>
113) How to invoke stored
procedures from a Java application?
Using CallableStatement &
prepareStatement();
114) What Design patterns do
you know?
MVC, Singleton class, Factory ,
FrontController, DAO class, D.T.O/V.O these are
design patterns I know
115) What is HB? What are
its files.
It is an ORM tool that is there to
develop DB independent persistence logic.
Hibernate-config.xml, Hibernate-mapping.xml, pojo class
116) How to integrate HB
with Spring?
The DAO implementation class of
spring must extends HibernateDAOSupport and
implements DAO interface.
117) How to integrate Struts
with Spring?
ContextLoaderServlet and
applicationContext.xml configured in struts-config.xml that is there
in web.xml
118) What are the
differences b/w BeanFactory and ApplicationContext?
BeanFactory (I) container ApplicationContext (I)
to develop spring core
applications. It is an advanced
& extended for BeanFactory.
It gives full fledged
spring features support like;
i) Bean property values
can be collected from
“outside properties file”.
ii) gives support for
Pre-Initialization of Beans.
iii) text messages can be collected from
outside property files to give support
for i18n.
iv) allows to work with EventHandling through
Listeners.
119) What are the
SessionTracking Techniques?
Session Tracking: is a technique by which the client data can
be remembered across
the multiple requests given by a client during a Session.
1) Hidden Form Fields
2) Http Cookies
3) HttpSession with
Cookies
4) HttpSession with
URL-rewriting.(best)
120) How to handle multiple submit buttons in a HTML form?
<input type=”submit” name=”s1”
value=”add”> </th>
<input type=”submit” name=”s1”
value=”delete”> </th>
<input type=”submit” name=”s1”
value=”modify”> </th>
Code for accessing the above data in
Servlet.
String
cap=request.getParameter(“s1”);
if(cap.equals(“add”)) {
---------- }
elseif(cap.equals(“delete”)) {
------------- }
else(cap.equals(“modify”)) {
------------ }
121) What you write to open a window?
Window.open(); in
Javascript
<a
href="javascript:;"
onClick="mm_openbrwindow('Mypage.html','','width=800, height=600,
scrollbars=no')">MyPage</a>
newwindow=window.open(url,'name','height=500,width=400,left=100,
top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
122) Do you know CSS? What
can I do with CSS?
CSS is a style language
that defines layout of HTML documents. For example, CSS covers fonts,
colours,
margins, lines, height, width, background images, advanced positions and many
other things
123)What is the difference between CSS and HTML?
HTML is used to structure
content. CSS is used for formatting structured content.
124) Code for DataSource?
Context ct=new InitialContext();
Object obj=ct.lookUp(“ JNDI name
of dataSource reference”);
DataSource ds=(DataSource)obj;
Connecton con=ds.getConnection();
Statement st=con.createStatement();
--------------------
con.close();
125)
What is the return type of “executeUpdate()” ?
It is used to execute “Non-Select
queries” and
whose return type is “int”.
126) What is “OUTER join”?
Outer join supports 3types joins.These
are
i)left outer join
ii)right outer join
iii)full outer join
It gives both matching and non-matching
rows.
127) Why there are Directive
and Action tags in JSP?
Directive tags: perform Global operations on a page like
i)
importing packages,
ii)
working with tag-library
iii)
including other JSPs content and etc.,.
ex: page, include, taglib
Action tags:
are there to perform actions
during request-processing/execution phase of JSP.
Ex:
include, forward,useBean, setProperty, getProperty, param, plugin.
128) What is Expression tag
in JSP?
It is used to
i) evaluate a Java
expression & sends that result to
Browser-window. <%=a+b;%>
ii) display the variable values on the
Browser-window. <% int a=10;%>
<% =a %>
iii) call both pre-defined
& user-defined methods.
<%=sum(10,20)%> ,
<%=”raja”.length()%>
iv) instantiates java classes & to display
the default data of the object.
date and time is:<%=new
java.util.Date();%>
129) What is Self Join? A
table joins with itself.
sum(): select sum(salarycolumn) from tablename
group by salarycolumn;--groups the same
salaries into different
groups.
select sum(salarycolumn)
from tablename;-à gives total sum of salary column
130) What is Setter and Constructor
injection?
Setter Injection:
Setter Injection is a process of injecting/assigning the dependent values to
the Bean properties
by the spring container using Bean
class setXXX(-) methods.
Note:
In Spring Config.xml:
<property name=”age ”>
<value> 20</value>
</property>
Constructor Injection:
Constructor Injection is a process of
assigning/injecting the dependent values to the
Bean properties
by the spring container using
“parameterized Constructors”.
Note:
In Spring config.xml:
<constructor-arg>
<value>ramu</value>
</constructor-arg>
131) Can we use Setter
Injection when we use private Constructor?
No
132) What is “inverse=true”
in hbm file?
The Association is bi-directional.
133) How to establish
many to many association?
Declare one column as primary key in the Parent table.
Declare one column as primary key in the child table.
Take another table where above two primary keys will be declared
as foreign keys.
134) Can I
develop a spring application without hbm file.
Yes, by using “Annotation”
135) Can I
develop a spring application without spring config.xml?
Yes, by using Properties file.
136) What is
distributed transaction?
The transaction where two databases are used for a project.
137)
Differences b/w procedure & function?
Procedure
|
Function
|
1) may or may not return
value.
2) may returns one or
many
values(max.1024)
3) result is gathered only
through OUT
parameters.
|
must returns a value.
Must return exactly one value
through OUT parameters & return
value.
|
138) Difference b/w
Primary and Unique key?
Primary key:
Only one Primary key constraint can be applied to a table.
Primary key column won’t allow duplicates.
Primary key
column won’t allow NULL.
Unique key: one or many Unique key constraint can be
applied to one table.
It does n’t allows duplicates.
It allows NULL(only one time).
139) Explain Joins?
Purpose : to bind data together, across tables, without repeating
all of the data in every table.
JOIN: Return rows when there is at least one match in both tables
LEFT OUTER JOIN:
Return all rows from the left table, even if there are no matches in the
right
table
RIGHT OUTER JOIN: Return
all rows from the right table, even if there are no matches in the
left table
FULL OUTER JOIN:
Return rows when there is a match in one of the tables
SELF JOIN :
EQUI/INNER JOIN:
140) How do you
maintain bug tracking in your project?
Using JIRA tool.
JIRA is a Bug and Issue tracker. It has been designed:
• for Bug tracking
• aid in Project
Management
• enable Agile Development
There is a connection tool
to Eclipse that allows you to manage tasks, issues, builds, and code reviews
directly in your integrated development environment.
JIRA is the project
tracker for teams planning, building and launching great products.
Thousands of teams choose
JIRA to capture and organize issues, work through action items, and stay
up-to-date with team activity.
As your dev team
grows, so should your bug tracker. With our simple importer, it's easier than
ever
to get your issues into JIRA and watch your team destroy bugs with the
fury of a thousand mutant
dinosaurs.
Over 6,300 JIRA customers
have gone Agile with GreenHopper.
GreenHopper will make your
Agile adoption successful with presets for Scrum and Kanban.
Turbocharge JIRA
to improve visibility across teams and projects.
Have trouble seeing the
big picture? Or even the small picture? See clearly with JIRA 5.2.
The completely re-imagined
JIRA search experience lets you quickly find and organize your issues,
so you –
and your team – can focus on what matters most. Getting the job done!
141) What tool are
you using to write hundreds of fields for your project?
142) What code
styles are you following in IDE?
143) Procedure to
work with PreparedStatement in a Java application.
1).
Prepare a query having “positional/place” holders/”in
parameters”.ie.(?,?,?)
2).
Send the query to DB s/w, make the query as “pre-compiled query”
& represent
it through “PreparedStatement”.
3).
Set the values for place-holders using “setXXX(-,-)”.
4).
Execute the query.
5).
To execute the same query for multiple no. of times with
same/different values,
repeat steps 3 & 4 for multiple times.
6).
Close PreparedStatement object.
à
Pre-compiled query: a query that goes to DB & becomes
compiled-query without values, and also resides on DB.
It reduces
“Network traffic” b/w Java appl & DB s/w.
144) How to display
data from the table in HB?
SessionFactory sf = new
Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction t = session.beginTransaction();
Student st = new
Student(); //pojo
//Displaying data from
Student table using HQL
Query qry =
session.createQuery("from Student");
List lt = qry.list();
// data saves into List with no restrictions
//Restrcting data based on
age condition
Criteria ct =
session.createCriteria(Student.class);
ct.add(Restrictions.age("studentAge", 20));
List lt = ct.list();
Iterator<Student> itr = lt.iterator();
// displays all records
System.out.println("Student no: \t Name :
\t Age");
while
(itr.hasNext()) {
Student student = itr.next();
System.out.println(student.getStudentId()+"\t"+
student.getStudentName()+"\t"+student.getStudentAge());
}
145) How to insert
one record into a Table (single row insertion)
student.setStudentName("sridhar");
student.setStudentAge(28);
session.save(student);
146) How to update
existing a table record?
student.setStudentId(5);
//primary key val
student.setStudentName("sridhar");
student.setStudentAge(28);
session.saveOrUpdate(st);
147) How to delete a
table record from HB session obj?
session.load(student, new Integer(1)); // load(Student.class, primarykey)
session.delete(student);
148) What are the
Escape characters in JSP?
149) How many ways
are there to invoke a Servlet object.
150) What is the
difference b/w Filter and Servlet?
151) What is syntax
for doFilter()?
152) Give me one
example for Detached state of an object in HB?
153) What is the
implementation class of SessionFactory?
LocalSessionFactoryBean
154) How do you
configure one to many and many to many for an single Hb application?
155) What is
Bi-directional and Uni-directional in HB?
inverse=”true”-àmeans bi-directional association.
Inverse=”false”àmeans uni -directional
assoiciation
156) How to do
Pagination?
157) Signature of
“validate()”?
Public ActionErrors validator(ActionMapping am, HttpServletRequest
req)
158) Write the code for CallableStatement?
------------------------------------------------------------------------
how we do configure spring
security in your project?
<!-- Spring
Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.core.version}</version>
<type>jar</type>
<!-- <scope>compile</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.core.version}</version>
<type>jar</type>
<!-- <scope>compile</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.core.version}</version>
<type>jar</type>
<!-- <scope>compile</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.core.version}</version>
<type>jar</type>
<!-- <scope>compile</scope> -->
</dependency>
how we do configure spring
with mongoDB in your project?
<!-- Spring Data
MongoDB -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- MongoDB Java Driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongodb.driver.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
how we do configure JUnit testing
dependencies in your project (Spring with maven)?
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<type>jar</type>
<scope>test</scope>
</dependency>
how we do configure Java
Mail API dependencies in your project (Spring with maven)?
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
how we do configure log4j
dependencies in your project (Spring with maven)?
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
how we do configure RESTFul
dependencies in your project (Spring with maven)?
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
how we do configure
Rest-Assured dependencies in your project (Spring with maven)?
Rest-Assured is an
open-source Java Domain-Specific Language (DSL). DSL for simplifying
testing
of REST based services built on top of HTTP Builder. It supports POST,
GET, PUT, DELETE,
OPTIONS, PATCH and HEAD requests and can be used to validate
and verify the response of these
requests.
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>1.4</version>
</dependency>
how we do configure
JSON dependencies in your project (Spring with maven)?
<!-- Data Mapper
package is a high-performance data binding package built
on
Jackson JSON processor -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!--
Jackson is a high-performance JSON processor (parser, generator) -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160807</version>
</dependency>
how we do configure
Spring-Boot dependencies in your project (Spring with maven)?
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath
/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
----------------------------------------------------------------------------------------
159) REST Vs SOAP
REST(REpresentational State Transfer)
REST is an architectural style. It doesn’t define so many standards like SOAP.
REST is for exposing
Public APIs (i.e. Facebook API, Google Maps API) over the internet to handle
CRUD operations on data.
REST is focused on
accessing named resources through a single consistent interface.
SOAP
(Simple Object Access Protocol)
SOAP brings its own protocol and focuses on exposing pieces of application
logic (not data) as
services. SOAP exposes operations. SOAP is focused on
accessing named operations, each operation implement some business logic.
Though SOAP is commonly referred to as web services this is
misnomer. SOAP
has a very little if anything to do with the Web. REST provides true Web
services
based on URIs and HTTP.
Why REST?
1) Since REST uses
standard HTTP it is much simpler in just about every way.
2) REST is easier to
implement, requires less bandwidth and resources.
3) REST permits many
different data formats whereas SOAP only permits XML.
4) REST allows better
support for browser clients due to its support for JSON.
5) REST has better
performance and scalability.
6) REST reads can be
cached, SOAP based reads cannot be cached.
7) If security is not a
major concern and we have limited resources. Or we want to create an API that
will be easily used by other developers publicly then we should go with REST.
8) If we need Stateless
CRUD operations then go with REST.
9) REST is commonly used
in social media, web chat, mobile services and Public APIs like Google
Maps.
10) RESTful service return
various MediaTypes for the same resource, depending on the
request header
parameter "Accept" as application/xml or application/json for
POST .
11) REST services are
meant to be called by the client-side application and not the end user
directly.
12) REST comes
from State Transfer. You transfer the state around instead of having
the server
store it, this makes REST services scalable.
Why SOAP?
1) SOAP is not very easy
to implement and requires more bandwidth and resources.
2) SOAP message request is
processed slower as compared to REST and it does not use web caching mechanism.
3) WS-Security: While
SOAP supports SSL (just like REST) it also supports WS-Security which
adds some
enterprise security features.
4)
WS-AtomicTransaction: Need ACID Transactions over a service, you’re going
to need SOAP.
5)
WS-ReliableMessaging: If your application needs Asynchronous processing
and a guaranteed leve
l of reliability and security. Rest doesn’t have a
standard messaging system and expects clients to
deal with communication
failures by retrying.
6) If the security is a
major concern and the resources are not limited then we should use SOAP
web
services. Like if we are creating a web service for payment gateways, financial
and
telecommunication related work then we should go with SOAP as here high
security is needed.
====================================================================
160)@Consumes and @Produces to
Customize Requests and Responses
The information sent
to a resource and then passed back to the client is specified as a MIME
media
type in the headers of an HTTP request or response. You can specify which MIME
media types of representations a resource can respond to or produce by using
the following
annotations:
javax.ws.rs.Consumes
javax.ws.rs.Produces
By default, a resource
class can respond to and produce all MIME media types of representations
specified in the HTTP request and response headers.
The @Produces annotation
is used to specify the MIME media types or representations a resource can
produce and send back to the client. If @Produces is applied at the
class level, all the methods in a resource can produce the specified MIME types
by default. If applied at the method level, the
annotation overrides
any @Produces annotations applied at the class level.
If no methods in a
resource are able to produce the MIME type in a client request, the JAX-RS
runtime sends back an HTTP “406 Not Acceptable” error.
The value
of @Produces is an array of String of MIME types. For
example:
@Produces({"image/jpeg,image/png"})
The following example
shows how to apply @Produces at both the class and method levels:
@Path("/myResource")
@Produces("text/plain")
public class SomeResource
{
@GET
public
String doGetAsPlainText() {
...
}
@GET
@Produces("text/html")
public
String doGetAsHtml() {
...
}
}
The doGetAsPlainText method
defaults to the MIME media type of the @Produces annotation at the
class level. The doGetAsHtml method’s @Produces annotation
overrides the class-level @Produces
setting and specifies that the
method can produce HTML rather than plain text.
If a resource class is
capable of producing more than one MIME media type, the resource method
chosen
will correspond to the most acceptable media type as declared by the client.
More specifically, the Accept header of the HTTP request declares
what is most acceptable.
For example, if
the Accept header is Accept: text/plain,
the doGetAsPlainText method will be
invoked. Alternatively, if
the Accept header is Accept: text/plain;q=0.9, text/html, which
declares
that the client can accept media types
of text/plain and text/html but prefers the latter,
the doGetAsHtml method will be invoked.
More than one media type
may be declared in the same @Produces declaration. The following code
example shows how this is done:
@Produces({"application/xml",
"application/json"})
public String
doGetAsXmlOrJson() {
...
}
The doGetAsXmlOrJson method
will get invoked if either of the media
types application/xml and application/json is acceptable.
If both are equally acceptable, the former
will be chosen because it occurs
first. The preceding examples refer explicitly to MIME media types
for clarity.
It is possible to refer to constant values, which may reduce typographical
errors.
The @Consumes annotation
is used to specify which MIME media types of representations a resource can
accept, or consume, from the client. If @Consumes is applied at the
class level, all the response
methods accept the specified MIME types by
default. If applied at the method level, @Consumes
overrides
any @Consumes annotations applied at the class level.
If a resource is unable
to consume the MIME type of a client request, the JAX-RS runtime sends back
an
HTTP 415 (“Unsupported Media Type”) error.
The value
of @Consumes is an array of String of acceptable MIME
types. For example:
@Consumes({"text/plain,text/html"})
The following example
shows how to apply @Consumes at both the class and method levels:
@Path("/myResource")
@Consumes("multipart/related")
public class SomeResource
{
@POST
public
String doPost(MimeMultipart mimeMultipartData) {
...
}
@POST
@Consumes("application/x-www-form-urlencoded")
public
String doPost2(FormURLEncodedProperties formData) {
...
}
}
The doPost method
defaults to the MIME media type of the @Consumes annotation at the
class level. The doPost2 method overrides the class
level @Consumes annotation to specify that it
can accept
URL-encoded
form data.
If no resource methods can
respond to the requested MIME type, an HTTP 415
(“Unsupported Media
Type”)
error is returned to the client.
The HelloWorld example
discussed previously in this section can be modified to set the message by
using @Consumes, as shown in the following code example:
@Consumes("text/plain")
public void postClichedMessage(String
message) {
//
Store the message
}
In this example, the Java
method will consume representations identified by the MIME media
type
text/plain. Note that the resource method returns void. This
means that no representation is returned
and that a response with a status code
of HTTP 204 (“No Content”) will be returned.
161) Spring Features
Spring is the most popular
application development framework for enterprise Java. Millions of
developers
around the world use Spring Framework to create high performing, easily
testable, and
reusable code.
Spring framework is an
open source Java platform. It was initially written by Rod Johnson and was
first released under the Apache 2.0 license in June 2003.
Spring is lightweight when
it comes to size and transparency. The basic version of Spring framework
is
around 2MB.
The core features of the
Spring Framework can be used in developing any Java application, but there
are
extensions for building web applications on top of the Java EE platform. Spring
framework targets
to make J2EE development easier to use and promotes good
programming practices by enabling a
POJO-based programming model.
162) Benefits of Using the Spring Framework
Following is the list of
few of the great benefits of using Spring Framework −
1) Spring enables
developers to develop enterprise-class
applications using POJOs. The
benefit of
using only POJOs is that you do not need an EJB container product
such as an application server
but you have the option of using only a robust
servlet container such as Tomcat or some commercial
product.
2) Spring is organized in
a modular
fashion.
Even though the number of packages and classes are
substantial, you have to
worry only about the ones you need and ignore the rest.
3) Spring does not reinvent the wheel, instead it
truly makes use of some of the existing technologies
like several ORM frameworks, logging
frameworks, JEE, Quartz and JDK timers, and other view technologies.
4) Testing an application written with
Spring is simple because
environment-dependent code is
moved into this framework. Furthermore, by using
JavaBeanstyle POJOs, it becomes easier to use dependency injection for
injecting test data.
5) Spring's web framework
is a well-designed
web MVC framework,
which provides a great
alternative to web frameworks such as Struts or other
over-engineered or less popular web frameworks.
6) Spring provides a convenient API to translate
technology-specific exceptions (thrown
by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
7) Spring has Lightweight IoC containers tend to be lightweight,
especially when compared to EJB containers, for example. This is beneficial for
developing and deploying applications on
computers with limited memory and CPU
resources.
8) Spring provides a consistent transaction
management interface that
can scale down to a local
transaction (using a single database, for example)
and scale up to global transactions (using JTA, for example).
9) Dependency Injection (DI)
The technology that Spring
is most identified with is the Dependency Injection (DI) flavor of
Inversion of Control. The Inversion
of Control (IoC) is a
general concept, and it can be expressed
in many different ways. Dependency
Injection is merely one concrete example of Inversion of
Control.
When writing a complex
Java application, application classes should be as independent as possible
of
other Java classes to increase the possibility to reuse these classes and to test
them independently
of other classes while unit testing.
Dependency injection can
happen in the way of passing parameters to the constructor or by
post-construction using setter methods. As Dependency Injection is the heart of
Spring Framework,
we will explain this concept in a separate chapter with
relevant example.
10) Aspect Oriented Programming (AOP)
One of the key components
of Spring is the Aspect Oriented Programming (AOP) framework. The
functions that span multiple points of an application are called cross-cutting
concerns and these
cross-cutting concerns are conceptually separate from
the application's business logic. There are
various common good examples of
aspects including logging, declarative transactions, security,
caching, etc.
The key unit of modularity
in OOP is the class, whereas in AOP the unit of modularity is the aspect.
DI
helps you decouple your application objects from each other, while AOP helps
you decouple
cross-cutting concerns from the objects that they affect.
The AOP module of Spring
Framework provides an aspect-oriented programming implementation
allowing you
to define method-interceptors and pointcuts to cleanly decouple code that
implements functionality that should be separated.
163) What is Spring Boot?
Spring Boot is a Framework
from “The Spring Team” to ease the bootstrapping and development of
new Spring
Applications.
It provides defaults for
code and annotation configuration to quick start new Spring projects within
no
time. It follows “Opinionated Defaults Configuration” Approach to avoid lot of
boilerplate code
and configuration to improve Development, Unit Test and
Integration Test Process.
What is NOT Spring Boot?
Spring Boot Framework is
not implemented from the scratch by The Spring Team, rather than
implemented on
top of existing Spring Framework (Spring IO Platform).
It is not used for solving
any new problems. It is used to solve same problems like Spring Framework.
Why Spring Boot?
To ease the Java-based
applications Development, Unit Test and Integration Test Process.
To reduce Development,
Unit Test and Integration Test time by providing some defaults.
To increase Productivity.
Don’t worry about what is
“Opinionated Defaults Configuration” Approach at this stage. We will
explain
this in detail with some examples in coming posts.
Advantages of Spring Boot:
It is very easy to develop
Spring Based applications with Java or Groovy.
It reduces lots of
development time and increases productivity.
It avoids writing lots of
boilerplate Code, Annotations and XML Configuration.
It is very easy to
integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC,
Spring ORM, Spring Data, Spring Security etc.
It follows “Opinionated
Defaults Configuration” Approach to reduce Developer effort
It provides Embedded HTTP
servers like Tomcat, Jetty etc. to develop and test our web applications
very
easily.
It provides CLI (Command
Line Interface) tool to develop and test Spring Boot(Java or Groovy)
Applications from command prompt very easily and quickly.
It provides lots of
plugins to develop and test Spring Boot Applications very easily using
Build
Tools like Maven and Gradle
It provides lots of
plugins to work with embedded and in-memory Databases very easily.
164) Difference between
Procedure and Function
Procedure
|
Function
|
1) Used mainly to a execute
certain process.
2) Cannot call in SELECT
statement.
3 Use OUT parameter to return
the value
4) It is not mandatory to
return the value.
5) RETURN will simply exit the
control from subprogram.
6) Return datatype will not be
specified at the time of creation.
|
1) Used mainly to perform some
calculation.
2) A Function that contains no
DML statements
can be called in SELECT statement.
3) Use RETURN to return the
value
4) It is mandatory to return
the value.
5) RETURN will exit the control
from
subprogram and also returns the value.
6) Return datatype is mandatory
at the time .
|
165) Explain the JSP life-cycle
methods?
1. Page translation: The
page is parsed & a Java file containing the corresponding servlet is
created.
2. Page compilation:
The Java file is compiled.
3. Load class:
The compiled class is loaded.
4 .Create instance:
An instance of the servlet is created.
5. Call jspInit():
This method is called before any other
method to allow initialization.
6. Call _jspService():
This method is called for each request. (can’t be overridden)
7. Call jspDestroy(): The
container calls this when it decides take the instance out of service.
It is the last method called n the servlet instance.
166) What are
differences b/w Servlets & Jsp?
Servlets:
i) Servlets
requires Recompilation and Reloading when we do modifications in a
Servlet.
(some servers)
ii) Every
Servlet must be configured in “web.xml”.
iii) Servlets is
providing less amount of implicit objects support.
iv) Since it
consists both HTML & bussiness logic hence modification in one logic may
disturbs
the other logic.
v) No
implicit Exception Handling support.
vi) Since Servlets
requires strong Java knowledge hence non-java programmers shows no interest.
vii) Keeping HTML
code in Servlets is quite complex.
JSP:
i) No
need of Recompilation & Reloading when we do modifications in a JSP page.
ii) We need
not to Configure a JSP in a “web.xml”.
iii) Jsp is
providing huge amount of Implicit Objects support.
iv) Since
Html & Java code are separated hence no disturbance while changing logic.
v) Jsp is
providing implicit XML Exception Handling support.
vi) Jsp is
easy to learn & implement since it is tags based.
vii) Jsp allows to
develop custom tags.
viii) Jsp gives JSTL
support.
(JSP Standard Tag
Library--> It provides more tags that will help to develop a JSP
without
using Java code).
ix) Jsp gives all
benefits of Servlets.
167) What are the functions
of service()?
protected void
service(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException
Receives standard HTTP
requests from the public service method and dispatches them to the doXXX
methods defined in this class. This method is an HTTP-specific version of the
public void
service(ServletRequest req, ServletResponse res)
throws ServletException, java.io.IOException
Dispatches client requests
to the protected service method.
There's no
need to override this method.
168) How do we get
the container related information?
By
using “ServletContext” object. we can create ServletContext object in two
ways.
First way :
public class
TestServlet extends HttpServlet
{
public void service(HttpServletRequest req
,HttpServletResponse response) throws
ServletException, IOException
{
ServletConfig
cg=getServletConfig();
ServletContext sc=cg.getServletContext();
====== usage of ServletContext object
here ====
}
}
|
Second way :
public class
TestServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException ,IOException
{
ServletConfig sc=getServletContext();
======
usage of ServletContext object here ====
}
}
|
169) What are the functions
of a FilterServlet?
FilterServlet traps
all the requests & responses.
Container creates the Filter object when the web application is deployed.
170) Which JSP tag is
used to display error validation?
In
Source page:
<%@page
errorPage=”error-page-name.jsp”>
In
Error page:
<%@page
isErrorPage=”true”>
171) How to compile a
JSP page?
your jsps. It does this by compiling the jsps in a project
and inserting servlet and servlet mapping
entries into the final web.xml
file, which gets packaged into the project's war file.
To use it, you need
references to jspc-maven-plugin and maven-war-plugin in your project's pom.xml.
The precompiling takes place during the "compile" phase of the maven
build (default) lifecycle.
The jspc maven plugin writes the servlet and servlet
mappings to a target/jspweb.xml file, and the
maven war plugin copies this file
and uses it in the war file that it builds.
<!-- begin -
precompiling jsps -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jspc-maven-plugin</artifactId>
<executions>
<execution>
<id>jspc</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>${basedir}/target/jspweb.xml</webXml>
</configuration>
</plugin>
<!-- end - precompiling jsps -->
172) How do you forward
Servlet1 request to Servlet2?
ServletContext sc=getServletContext();
RequestDispatcher rd =sc.getRequestDispatcher(“/s2url”);
//” or html file name”
rd.forward(req,resp); (or) rd.include(req,resp);
173) How do you make
the variables applicable to the whole application in JSP?
JSP declarations are used to declare class variables and methods
(both instance and static) in a JSP page. These declations will be placed
directly at class level in the generated servlet and these are available to the
entire JSP.
174) What are
ServletListeners?
Source obj
|
Event
|
Listener
|
EventHandling methods (public
void
|
ServletRequest
ServletContext
HttpSession
|
ServletRequestEvent(sre)
ServletContextEvent(sce)
HttpSessionEvent (hse)
|
ServletRequestListener
ServletContextListener
HttpSessionListener
|
requestInitialized(sre)
requestDestroyed(sre)
contextInitialized(sce)
contextDestroyed(sce)
sessionCreated(hse)
sessionDestroyed(hse)
|
From Servlet 2.4 onwards, EventHandling is
allowed on special objects of webapplication
like ServletContext, ServletRequest, HttpSession objects.
ServletRequest:
By doing EventHandling on ServletRequest object,
we can keep track of
each “request” object creation time
& destruction time. Based on this, we can
find out “request processing time”.
HttpSession:
By performing EventHandling on HttpSession object,
we can find out
“session” object creation time &
destruction time. Based on this, we can
know the time taken by the each user to work with “session”.
Procedure to configure Listeners with webapplication
1) Develop
a Java class implementing appropriate “Listener”
& place
it in WEB-INF/classes folder.
2) Configure
that Listener class name in web.xml by using <listener-class>
175) What is a
Session?
Session: It is a set of related & continuous
requests given by a client to a web application.
Ex: SignIn
to SignOut in any Mail Systems Application like Gmail, Ymail etc…
176) How do you
maintain client data at client side?
Cookies
177)
Difference b/w GET and POST methods?
GET
|
POST
|
1) It is a default Http
request method
2) Query string is visible in
Browser
address bar
hence no data Secrecy.
3) It allows to send limited
amount of
data(1kb)
4) It is not suitable
for File uploading.
5) It is not suitable
for sending Enscripted data.
6) It shows Idempotent behaviour.
7) Use either doGet(-,-) or
service(-,-)
to process this.
|
Not a default
method.
It gives data
Secrecy.
Unlimited amount of
data.
Suitable for File
uploading.
Suitable.
Non-Idempotent.
Use either doPost(-,-)
or service(-,-)
|
178) What is
Idempotent behavior?
It is the behavior like processing the multiple same
requests from the same web page.
179) How the POST is not having Idempotent
behavoiur?
180) What are the
different Scopes in JSP?
request, page, session, application
181) How to disable
“Cache” ?
<%
resp.setHeader(“cache-control”, ”no-cache”);%>
(<meta http-equiv=”cache-control” content=”no-cache”>
<%resp.setHeader(“pragma”,”no-cache”);%>
//http1.0
OR
<meta http-equiv=”pragma” content=”no-cache”>)
182) What is default
Scope in JSP?
page
183) How to configure
a JavaBean in JSP?
<jsp:useBean>
184) How the JSP
code is converting into Servlet code?
JSP parser/Engine/compiler
185) What is “useBean”?
JSP standard tag to configure a Java Bean in JSP.
186) What is Servlet
Chaining?
Servlet Chaining is a method of processing the request using multiple
servlets as a chain.
187) What is Servlet
life-cycle?
1. If an instance of the servlet
does not exist, the Web container
a. Loads the servlet
class.
b. Creates an instance of
the servlet class.
c. Initializes the servlet
instance by calling the init method.
2.
Invokes the service method, passing a request and response object.
3.
If the container needs to remove the servlet, it finalizes the servlet by
calling
the servlet's destroy method.
188) What are the differences
b/w Servlet and JSP?
For every time we modifing the servlet , we should re-deploy the servlet.
Its very big headache.
Manually written servlets are somewhat faster than JSPs.
JSP:
i) No
need of Recompilation & Reloading when we do modifications in a JSP page.
ii) We need
not to Configure a JSP in a “web.xml”.
iii) It is
providing huge amount of Implicit Objects support.
iv) Since
Html & Java code are separated hence no disturbance while changing logic.
v) It is
providing implicit XML Exception Handling support.
189) What is
“isThreadSafe=true” in JSP?
It makes the equivalent servlet as thread safe.
The “JSP equivalent Servlet” will implement
SingleTreadModel(I) implicitely.
190) What is custom
Servlet?
The servlet that extending pre-defined Servlet (ie
HttpServlet/GenericServlet/Servlet)
191) What Is a Custom Tag?
A custom tag is a
user-defined JSP language element. When a JSP page containing a custom tag
is
translated into a servlet, the tag is converted to operations on a tag handler.
The web container
then invokes those operations when the JSP page’s servlet is
executed.
Custom tags have a rich
set of features. They can
• Be customized by means
of attributes passed from the calling page.
• Pass variables back to
the calling page.
• Access all the objects
available to JSP pages.
• Communicate with each
other. You can create and initialize a JavaBeans component, create a public
EL(Expression Language) variable that refers to that bean in one tag, and then
use the bean in
another tag.
• Be nested within one
another and communicate by means of private variables.
Table 9-2 Tag Handler Methods
Tag Type
|
Interface
|
Methods
|
Basic
|
Tag
|
doStartTag, doEndTag
|
Attributes
|
Tag
|
doStartTag, doEndTag, setAttribute1,...,N, release
|
Body
|
Tag
|
doStartTag, doEndTag, release
|
Body, iterative evaluation
|
IterationTag
|
doStartTag, doAfterBody, doEndTag, release
|
Body, manipulation
|
BodyTag
|
doStartTag, doEndTag, release, doInitBody, doAfterBody
|
192) Is the Servlet
thread-Safe by default?
No, the servlet by default is not Thread safe. To achieve
this, the servlet must implements
SingleThreadModel interface OR synchronize
the service().
193) Which JSP methods
can be overridden?
jspInit() & jspDestroy().
194) What are the common
files when 5 or more projects are developed using Hibernate ?
Hibernate-configuration file
195) Can I call a
procedure from a HB? How?
Yes.
1)In hibernate main file,
we have to set getNamedQuery("-") after openSession() method.
Query query =
session.getNamedQuery("callStockStoreProcedure");
query .setParameter("stockCode",
"7277");
List result =
query.list();
for(int i=0;
i<result.size(); i++){
Stock
stock = (Stock)result.get(i);
System.out.println(stock.getStockCode());
}
2) In hibernate mapping
file we have to set <sql-query> after </class>
<sql-query
name="callStockStoreProcedure" callable="true">
<return alias="emp" class="Stock "/>
{ call
get_stockdetails() }
</sql-query>
196) Can I use a big
query in HB?
Yes.
197) Tell me few
Hibernate interfaces?
i) Configuration(c),
ii) SessionFactory,
iii) Session,
iv) Transaction,
v) Query
198) How do you create
“Criteria”?(to do select operations.)
Criteria criteria=session.createCriteria(EmpBean.class);
// select *
from Employee where eid between 100 and 200 and firstname in
(“raja”,”ramana”));
Condition: 1
criteria=criteria.add(Expression.between(“no”,new Integer(100)),new
Integer(200));
Condition: 2
criteria=criteria.add(Expression.in(“fname”,new String
[]{“raja”,”ramana”} )));
List
l=ct.list(); //
retrieves more selected records
for(int x=0;x<l.size();x++){
EmpBean emp=(EmpBean) l.get(x);
S.o.p(emp.getNo()+”\t”+emp.getFname()+”\t”+emp.getLname()+”\t”+emp.getEmail());
199) What is
Hibernate configuration file?
HB dialect, DB Driver class, Driver class URL, Username,
Password.
200) Why the people
using frameworks?
201) What is POJO
& POJI model programming?
The programming with no api dependent classes/interfaces
202) What is
“Caching “ mechanism?
Hibernate has
caching mechanism.It means
To minimize n/w round trips.
“Session” is default and
“SessionFactory’ explicitly configured.
203) Do you know
“restriction” and “expression”?
Expression.between()
Expression.in()
204) What is Java?
Java is a high-level, object - oriented, platform independent programming language designed for developing
wide range of applications such as web applications, mobile applications, enterprise applications, desktop applications.
It was introduced by sun microsystems in 1995 (now owned by Oracle)
Jave uses a combination of compiler & interpreter to convert code into byte code which can run on any
device with a Java Virtual Machine (JVM), making it as high portable.
205) How do you
configure “one to many” association in Hibernate?
Example:
==========
Step1) In Parent POJO
class,we need a collection property for representing/storing a group of
child
objects associated.
//User.java (Parent POJO
class)
import java.util.*;
public class User {
private long userId ;
private String firstName ;
private Set phones; //
phones is a collection property
//
wrtie setXxx(-), getXxx() methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Set getPhones() {
return phones;
}
public void setPhones(Set phones) {
this.phones=phones;
}
}//class
//PhoneNumber.java (Child
POJO class)
public class PhoneNumber
{
private String numberType;
private long phone ;
private long id;
// write setXxx(-) and getXxx() methods
}
Step 2) In the Parent
class mapping the collection property with the collection element
(i.e.,
set,list,map)
<?xml
version="1.0"?>
<!DOCTYPE
hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="User" table="USER_TABLE" >
<id name="userId" column="USER_ID"/>
<property name="firstName"
column="FIRST_NAME"/>
<set name="phones"
table="PHONE_NUMBERS" cascade="all"
lazy="true">
//set ---àcollecton element
<key column="UNID"/>
//UNID -àforeign key
<one-to-many class="PhoneNumber" />
</set>
</class>
</hibernate-mapping>
Step 3)In main java file
i)add
the group of child objects to the collection object
Set s=new
HashSet(); //s--àcollection object
s.add(ph1);
s.add(ph2);
ii)Add
the collection object to parent object
u1.setPhones(s); //u1 --àparent object
For complete main java
file code
==============================
//TestClient (ClentApp)
import org.hibernate.*;
import
org.hibernate.cfg.*;
import java.util.*;
public class TestClient {
public static void
main(String[] args)
{
try
{
Session ses=new
Configuration().configure().buildSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
User u1=new User();
u1.setUserId(105);
u1.setFirstName("raja1");
PhoneNumber ph1=new PhoneNumber();
ph1.setNumberType("residence");
ph1.setPhone(65538968);
PhoneNumber ph2=new
PhoneNumber();
ph2.setNumberType("office");
ph2.setPhone(65538958);
Set s=new HashSet();
s.add(ph1);
s.add(ph2);
// setting PhoneNumber
class objs to phones property of User obj
u1.setPhones(s);
//To Insert record
ses.save(u1);
tx.commit();
ses.close();
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//main
}//class
206) What are the uses with Hibernate?
i) It allows to develop DB independent query language like HQL.
ii) It supports POJO/POJI model programming.
iii)
Any Java/J2EE can access HB persistence logic.
iv)
It supports to call all Procedures & Functions of PL/SQL programming.
v) The result after “SELECT” operation, by default, is
“Serializable”.
207) How to connect with DB?
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@<IPadress>:1521”,
”orcl”,”scott”,”tiger”);
Statement st=con.createStatement();
// ResultSet rs=st.execute(“select query”);
(or)
// int
x=st.executeUpdate(“Non-select query”);
208) What is
dialect?
Using dialect, Hibernate knows the type of DB & its version to
which it will connected.
209) How do you map
HB Pojo class with Table?
<hibernate-mapping default-cascade="none"
default-access="property" default-lazy="true"
auto-import="true">
<class
name="CustomerOrder" table="CustomerOrder"
mutable="true" polymorphism="implicit"
dynamic-update="false" dynamic-insert="false"
select-before-update="false"
optimistic-lock="version">
<composite-id
name="orderId" class="OrderId" mapped="false"
unsaved-value="undefined">
<key-property name="customerId" column="customer_id"
/>
<key-property
name="orderTime" column="order_time" />
</composite-id>
<property
name="orderDescription" unique="false"
optimistic-lock="true" lazy="false"
generated="never" />
</class>
</hibernate-mapping>
210)Spring annotations:
For spring to process annotations, add the following lines in your application-context.xml file.<context:annotation-config /><context:component-scan base-package="...specify your package name..." />
@Service
Annotate all your service classes with @Service. All your business logic should be in Service classes.@Service
public class CompanyServiceImpl implements CompanyService {
...
}
@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}
@Component
Annotate your other components (for example REST resource classes) with @Component.@Component
public class ContactResource {......
}
@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
@Component
Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the
@Repository annotation or AspectJ's
@Aspect annotation.
211)....ComponentScanConfigures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.
Either basePackageClasses or basePackages (or its alias value) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Note that the <context:component-scan> element has an annotation-config attribute; however, this annotation does not. This is because in almost all cases when using @ComponentScan, default annotation config processing (e.g. processing @Autowired and friends) is assumed. Furthermore, when using AnnotationConfigApplicationContext, annotation config processors are always registered, meaning that any attempt to disable them at the @ComponentScan level would be ignored.
212)....Scope
When used as a type-level annotation in conjunction with @Component, @Scope indicates the name of a scope to use for instances of the annotated type.
When used as a method-level annotation in conjunction with @Bean, @Scope indicates the name of a scope to use for the instance returned from the method.
NOTE: @Scope annotations are only introspected on the concrete bean class (for annotated components) or the factory method (for @Bean methods). In contrast to XML bean definitions, there is no notion of bean definition inheritance, and inheritance hierarchies at the class level are irrelevant for metadata purposes.
In this context, scope means the lifecycle of an instance, such as singleton, prototype, and so forth. Scopes provided out of the box in Spring may be referred to using the SCOPE_* constants available in the ConfigurableBeanFactory and WebApplicationContext interfaces.
@Scope is a Spring-managed components in general, the default and most common scope for autodetected components is singleton. To change this default behavior, use @Scope spring annotation.
@Component
@Scope("request")
public class ContactResource {
...
}
Similarly, you can annotate your component with @Scope("prototype") for beans with prototype scopes.To register additional custom scopes, see CustomScopeConfigurer.
213)Spring MVC Annotations
@Controller
Annotate your controller classes with @Controller.
@Controller
public class CompanyController {
...
}
@RequestMapping
@RequestMapping spring annotation is used to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping.
.....RequestMapping
@Target(value={METHOD, TYPE})
Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.
Both Spring MVC and Spring WebFlux support this annotation through a RequestMappingHandlerMapping and RequestMappingHandlerAdapter in their respective modules and package structure. For the exact list of supported handler method arguments and return types in each, please use the reference documentation links below:
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
...
}
@PathVariable
@PathVariable spring annotation is used on a method argument to bind it to the value of a URI template variable. In our example below, a request path of /company/sample will bind companyName variable with 'sample' value.
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("{companyName}")
public String getCompany(Map<String, Object> map,
@PathVariable String companyName) {
Company company = companyService.findByName(companyName);
map.put("company", company);
return "company";
}
...
}
@RequestParam
@RequestParam annotation is used to bind request parameters to method variables.
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("/companyList")
public String listCompanies(Map<String, Object> map,
@RequestParam int pageNum) {
map.put("pageNum", pageNum);
map.put("companyList", companyService.listCompanies(pageNum));
return "companyList";
}
...
}
Similarly, you can use spring annotation @RequestHeader to bind request headers.
@ModelAttribute
An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("/add")
public String saveNewCompany(@ModelAttribute Company company) {
companyService.add(company);
return "redirect:" + company.getName();
}
...
}
@SessionAttributes
@SessionAttributes spring annotation declares session attributes. This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests.
@Controller
@RequestMapping("/company")
@SessionAttributes("company")
public class CompanyController {
@Autowired
private CompanyService companyService;
...
}
@SessionAttribute works as follows:
- @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).
- @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.
- @SessionAttributes are cleared when you call setComplete() on SessionStatus object passed into controller method as an argument.
The following listing illustrate these concepts. It is also an example for pre-populating Model objects.
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
Spring Security Annotations
@PreAuthorize
@PreAuthorize annotation is used to authorize or deny a functionality in Spring Security . In our example below, only a user with Admin role has the access to delete a contact.
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
A convenience annotation that is itself annotated with @Controller and @ResponseBody.
Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.
NOTE: @RestController is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.
216)
...ControllerIndicates that an annotated class is a "Controller" (e.g. a web controller).
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the org.springframework.web.bind.annotation.RequestMapping annotation.
217)....SpringBootApplication
Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's a combination of three annotations:
@Configuration, @EnableAutoConfiguration and @ComponentScan.
218).....EntityScan
Configures the base packages used by auto-configuration when scanning for entity classes.
Using @EntityScan will cause auto-configuration to:
One of basePackageClasses(), basePackages() or its alias value() may be specified to define specific packages to scan. If specific packages are not defined scanning will occur from the package of the class with this annotation.
219)....EnableAutoConfiguration
Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined. For example, if you have tomcat-embedded.jar on your classpath you are likely to want a TomcatServletWebServerFactory (unless you have defined your own ServletWebServerFactory bean).
When using SpringBootApplication, the auto-configuration of the context is automatically enabled and adding this annotation has therefore no additional effect.
Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration. You can always manually exclude() any configuration that you never want to apply (use excludeName() if you don't have access to them). You can also exclude them via the spring.autoconfigure.exclude property. Auto-configuration is always applied after user-defined beans have been registered.
The package of the class that is annotated with @EnableAutoConfiguration, usually via @SpringBootApplication, has specific significance and is often used as a 'default'. For example, it will be used when scanning for @Entity classes. It is generally recommended that you place @EnableAutoConfiguration (if you're not using @SpringBootApplication) in a root package so that all sub-packages and classes can be searched.
Auto-configuration classes are regular Spring Configuration beans. They are located using the SpringFactoriesLoader mechanism (keyed against this class). Generally auto-configuration beans are @Conditional beans (most often using @ConditionalOnClass and @ConditionalOnMissingBean annotations).
220).....CrossOrigin
Annotation for permitting cross-origin requests on specific handler classes and/or handler methods. Processed if an appropriate HandlerMapping is configured.
Both Spring Web MVC and Spring WebFlux support this annotation through the RequestMappingHandlerMapping in their respective modules. The values from each type and method level pair of annotations are added to a CorsConfiguration and then default values are applied via CorsConfiguration.applyPermitDefaultValues().
The rules for combining global and local configuration are generally additive -- e.g. all global and all local origins. For those attributes where only a single value can be accepted such as allowCredentials and maxAge, the local overrides the global value. See CorsConfiguration.combine(CorsConfiguration) for more details.