#servletcontext
Explore tagged Tumblr posts
atplblog · 8 months ago
Text
Price: [price_with_discount] (as of [price_update_date] - Details) [ad_1] 1.Java Networking Network Basics and Socket overview, TCP/IP client sockets, URL, TCP/IP server sockets, Datagrams, java.net package Socket, ServerSocket, InetAddress, URL, URLConnection. (Chapter - 1) 2.JDBC Programming The JDBC Connectivity Model, Database Programming : Connecting to the Database, Creating a SQL Query, Getting the Results, Updating Database Data, Error Checking and the SQLException Class, The SQLWarning Class, The Statement Interface, PreparedStatement, CallableStatement The ResultSet Interface, Updatable Result Sets, JDBC Types, Executing SQL Queries, ResultSetMetaData, Executing SQL Updates, Transaction Management. (Chapter - 2) 3.Servlet API and Overview Servlet Model : Overview of Servlet, Servlet Life Cycle, HTTP Methods Structure and Deployment descriptor ServletContext and ServletConfig interface, Attributes in Servlet, Request Dispacher interface. The Filter API: Filter, FilterChain, Filter Config Cookies and Session Management : Understanding state and session, Understanding Session Timeout and Session Tracking, URL Rewriting. (Chapter - 3) 4.Java Server Pages JSP Overview: The Problem with Servlets, Life Cycle of JSP Page, JSP Processing, JSP Application Design with MVC, Setting Up the JSP Environment, JSP Directives, JSP Action, JSP Implicit Objects JSP Form Processing, JSP Session and Cookies Handling, JSP Session Tracking JSP Database Access, JSP Standard Tag Libraries, JSP Custom Tag, JSP Expression Language, JSP Exception Handling, JSP XML Processing. (Chapter - 4) 5.Java Server Faces 2.0 Introduction to JSF, JSF request processing Life cycle, JSF Expression Language, JSF Standard Component, JSF Facelets Tag, JSF Convertor Tag, JSF Validation Tag, JSF Event Handling and Database Access, JSF Libraries : PrimeFaces. (Chapter - 5) 6.Hibernate 4.0 Overview of Hibernate, Hibernate Architecture, Hibernate Mapping Types, Hibernate O/R Mapping, Hibernate Annotation, Hibernate Query Language. (Chapter - 6) 7.Java Web Frameworks . Publisher ‏ : ‎ Technical Publications; First Edition (1 January 2021) Language ‏ : ‎ English Paperback ‏ : ‎ 392 pages ISBN-10 ‏ : ‎ 9333221638 ISBN-13 ‏ : ‎ 978-9333221634 Item Weight ‏ : ‎ 520 g Dimensions ‏ : ‎ 24 x 18.3 x 1.5 cm Country of Origin ‏ : ‎ India Generic Name ‏ : ‎ Books [ad_2]
0 notes
oxfordschoolofenglish · 3 years ago
Text
Oxford Certified Advance Java Professional
Tumblr media
Oxford Certified Advance Java Professional
A Step ahead of Core Java – Advanced Java focuses on the APIs defined in Java Enterprise Edition, includes Servlet programming, Web Services, the Persistence API, etc. Oxford Software Institute provides the best classes in Advanced Java in Delhi and our course includes advanced topics like creating web applications by using technologies like Servlet, JSP, JSF, JDBC, EJB etc. We will further learn enterprise applications used a lot in banking sector.
JDBC, SERVLET AND JSP
The course will focus on JDBC, JDBC Drivers, Setting up a database and creating a schema, Connecting to DB, CRUD Operations, Rowset, Resultset, Preparedstatement, Connection Modes and much more. We will further learn the Basics of Servlet, Servlet Life Cycle, Working with Apache Tomcat Server, Servlet with JDBC, Servlet Collaboration, servletconfig, servletcontext, Attribute, Session, Tracking, Event and Listener, Filter, ServletInputStream etc. Under JSP, we’ll learn Basics of JSP, API, JSP in netbeans, Implicit Objects, Directive Elements, Taglib, Exception Handling, Action Elements, Expression Language, MVC, JSTL etc.
JAVAMAIL API, JMS AND JAVA NETWORKING
Under these topics, Oxford Software Institute offers best classes in Advanced Java such as Sending Email, Sending Email through Gmail server, Receiving Email, Sending HTML content, JMS Overview, JMS Messaging Domains, Example of JMS using Queue, Example of JMS using Topic, Networking Concepts, Socket Programming, URL class, URLConnection class, HttpURLConnection, InetAddress class, DatagramSocket class.
JQUERY, AJAX, MAVEN AND DAO PATTERN
The content has been prepared with utmost care at Oxford Software Institute where we provide the best classes with topics such as Introduction to JQuery, Validation, Forms, , Introduction to AJAX, Servlet and JSP with AJAX, Interacting with database, Maven, Ant Vs Maven, How to install Maven, Maven Repository, Understanding pom.xml, Maven Example, Maven Web App Example, Maven using NetBeans, DAO pattern, Singleton, DAO, DTO, MVC, Front Controller, Factory Method.
HIBERNATE AND SPRING FRAMEWORK
This session will focus on HB Introduction and Architecture, Hibernate with NetBeans, HB using XML, HB using Annotation, Web application, Generator classes, Dialects, Log4j, Inheritance Mapping, Mapping, Transaction Management, HQL, HCQL, Named Query, Caching, Second Level Cache, Integration, Struts. We will further learn about Spring Modules, Spring in NetBeans , Dependency Injection, JdbcTemplate, ORM, SPEL, MVC, MVC Form Tag Library, MVC Validation, MVC Tiles, Spring Remoting, OXM, Java Mail, Spring Security , Spring + Angular, CRUD Example, File Upload Example, Login & Logout Example, Search Field Example.
REST - REPRESENTATIONAL STATE TRANSFER
This session will focus on Installation of Jersey, Web container, required setup for Gradle and Eclipse web projects, How to Create your first RESTful WebService, How to Create a REST client, RESTful web services and JAXB, CRUD RESTful WebService, Rest Resources. We, at Oxford Software Institute will provide best classes that will focus on the practical applications of these concepts
SOFT SKILLS
Having a technical and discipline-specific expertise can help you get to the interview room but it’s the soft skills that will make the hiring manager hand you the appointment letter. In this course, students will also learn various Soft Skills like how to communicate professionally in English, Speaking in public without hesitation, using effective gestures and postures to appear impressive, managing stress and emotions and taking successful interviews. Oxford Software Institute provides the best classes in Soft-skill training.
CERTIFICATIONS*
During this course, students will be trained for the following certifications
Oxford Certified Advance Java Professional.
0 notes
siva3155 · 6 years ago
Text
300+ TOP SERVLET Interview Questions and Answers
SERVLET Interview Questions for freshers experienced :-
1. What is Servlet? A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request & response paradigm. 2. Why is Servlet so popular? Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server. 3. What is servlet container? The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle. 4.When a client request is sent to the servlet container, how does the container choose which servlet to invoke? The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response. 5.If a servlet is not properly initialized, what exception may be thrown? During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException. 6.Given the request path below, which are context path, servlet path and path info? /bookstore/education/index.html context path: /bookstore servlet path: /education path info: /index.html 7.What is filter? Can filter be used as request or response? A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. 8.When using servlets to build the HTML, you build a DOCTYPE line, why do you do that? I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors. 9.What is new in ServletRequest interface ? (Servlet 2.4) The following methods have been added to ServletRequest 2.4 version: public int getRemotePort() public java.lang.String getLocalName() public java.lang.String getLocalAddr() public int getLocalPort() 10.Request parameter How to find whether a parameter exists in the request object? 1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals("")); 2. boolean hasParameter = request.getParameterMap().contains(theParameter); (which works in Servlet 2.3+)
Tumblr media
SERVLET Interview Questions 11. How can I send user authentication information while making URL Connection? You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization. 12.Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext. 13.How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push 14.The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute. 15.What mechanisms are used by a Servlet Container to maintain session information? Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information 16.Difference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy. In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure. 17.What is session? The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. 18.What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets. 19.What is servlet context ? The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial). 20.Which interface must be implemented by all servlets? Servlet interface. 21.Explain the life cycle of Servlet. Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded. 22.When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet? An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method. 23.Why don't we write a constructor in a servlet? Container writes a no argument constructor for our servlet. 24.When we don't write any constructor for the servlet, how does container create an instance of servlet? Container creates instance of servlet by calling Class.forName(className).newInstance(). 25.Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time? Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish. 26.What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext? We can give relative URL when we use ServletRequest and not while using ServletContext. 27.Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()? Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not. 28. Whats the advantages using servlets over using CGI? CGI programs run outside the webserver. So a new process must be started to execute a CGI program. CGI programs are designed to handle a single request at a time. After that they return the result to the web server and exit. On the other hand servlets can handle multiple requests concurrently. They run within web servers. They generate dynamic content that is easier to write and faster to run. 29. What is Servlets and explain the advantages of Servlet life cycle? Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads. In servlets, JVM stays running and handles each request using a light weight thread. Servlets life cycle involve three important methods, i.e. init, service and destroy. Init() Init method is called when Servlet first loaded in to the web server memory. Service() Once initialized, Servlets stays in memory to process requests. Servlets read the data provided in the request in the service() method. Destroy() When server unloads servlets, destroy() method is called to clean up resources the servlet is consuming. 30. What are different Authentication options available in Servlets. There are four ways of Authentication options available in servlets HTTP basic authentication In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding. HTTP digest authentication This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5. HTTPS client authentication This options is based on HTTP over SSL. Form-based authentication Form-based authentication uses login page to collect username and password. 31. What is the GenericServlet class? GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method. 32. What is the difference between an Applet and a Servlet? Applets: Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. An Applet is a client side java program that runs within a Web browser on the client machine. An applet can use the user interface classes like AWT or Swing. Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy() Servlets: Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server. Servlet is a server side component which runs on the web server. The servlet does not have a user interface. Servlet Methods: doGet(), doPost() 33. List out the difference between ServletConfig and ServletContext? Both are interfaces in the package javax.servlet: ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. The ServletContext object is contained within the ServletConfig object. It is provided by the web server to the servlet when the servlet is initialized. ServletContext is an interface which has a set of methods like getServletName(), getServletContext(), getInitParameter(), getInitParameterNames(). The servlet uses to interact with its servlet container. ServletContext is common to all servlets within the same web application. So, servlets use ServletContext to share context information. 35. What is the difference between using getSession(true) and getSession(false) methods? getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it. getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null. 36. List out difference between a JavaBean from a Servlet? Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc. So, both have nothing in common except Java. 37. Define servlet mapping? Servlet mapping controls how you access a servlet. It is recommended that you don’t use absolute URLs. Instead usage of relative URLs should be done. If you try to deploy the application with a different context root, you might have to change all the urls used in all the JSP programs. Relative URLs is the solution so that you can deploy your application with different context root with out changing the URLs. 38. What is Servlets and explain the advantages of Servlet life cycle? Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream. Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client. 39. What is the difference between Difference between doGet() and doPost()? A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string. 40. What is the difference between ServletContext and ServletConfig? ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet. 41. What are all the protocols supported by HttpServlet? HttpServlet supports HTTP and HTTPS protocol. 42. Which exception is thrown if servlet is not initialized properly? Servlet Exception or Unavailable Exception is thrown if servlet is not initialized properly. 43. Who is responsible for writing a constructor? Container is responsible for writing constructor without arguments in servlet. 44. What are all the advantages of Servlet over CGI? Following are the advantages of Servlet over CGI: Cannot be run in an individual process. Servlet stays in the memory while requests. For every CGI request, you must load and start a CGI program. web.xml conveniences 45. What are the different mode that servlets can be used? Following are the modes that servlets can be used: Filter chains can be used to collect servlets together Support HTTP protocol Used for CGI based applications Dynamic generation of servlets 46. What are the uses of servlets? Servlets are used to process and store data submitted by HTML form, dynamic content, handle multiple request concurrently and manage state information on top of stateless HTTP. 47. Whether we can get deadlock situation in Servlets? Yes, it can be achieved by writing doGet method in doPost method and writing doPost method in doGet method. 48. What is the default HTTP method in the servlet? Default method is GET method for HTTPservlet. 49. Whether thread can be used in Servlets? Yes, Single thread can be used in servlets. 50. What exception should be thrown when servlet is not properly initialized? Servlet exception or an Unavailable exception is thrown when it is not properly initialized. 51. What is a filter? A filter is nothing but a piece of code which can be reusable that will be transforming the content of HTTP requests, response and header information. 52. What are the features added in Servlet 2.5? Following are the features added in Servlet 2.5: Dependency on J2SE 5.0 Support for annotations Loading the class Several web.xml Removed restrictions Edge case clarifications 53. When servlet is loaded? A servlet can be loaded when: First request is made Auto loading and Server starts up There is a single instance that answers all requests concurrently which saves memory Administrator manually loads. 54. When Servlet is unloaded? A servlet is unloaded when: Server shuts down Administrator manually unloads 55. What is life cycle of Servlet? Following is life cycle of Servlet: Loaded Initialized Destroy Unloaded SERVLET Questions and Answers Pdf Download Read the full article
0 notes
tccicomputercoaching · 6 years ago
Video
tumblr
What is difference between servletconfig and servletcontext? tccicomputercoaching.com
0 notes
quadrate-lk · 5 years ago
Text
Spring Interview Questions and Answers
Spring Interview Questions
What is Spring Framework?
What are some of the important features and advantages of Spring Framework?
What do you understand by Dependency Injection?
How do we implement DI in Spring Framework?
What are the new features in Spring 5?
What is Spring WebFlux?
What are the benefits of using Spring Tool Suite?
Name some of the important Spring Modules?
What do you understand by Aspect Oriented Programming?
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
What is the difference between Spring AOP and AspectJ AOP?
What is Spring IoC Container?
What is a Spring Bean?
What is the importance of Spring bean configuration file?
What are different ways to configure a class as Spring Bean?
What are different scopes of Spring Bean?
What is Spring Bean life cycle?
How to get ServletContext and ServletConfig object in a Spring Bean?
What is Bean wiring and @Autowired annotation?
What are different types of Spring Bean autowiring?
Does Spring Bean provide thread safety?
What is a Controller in Spring MVC?
What’s the difference between @Component, @Repository & @Service annotations in Spring?
What is DispatcherServlet and ContextLoaderListener?
What is ViewResolver in Spring?
What is a MultipartResolver and when it’s used?
How to handle exceptions in Spring MVC Framework?
How to create ApplicationContext in a Java Program?
Can we have multiple Spring configuration files?
What is ContextLoaderListener?
What are the minimum configurations needed to create Spring MVC application?
How would you relate Spring MVC Framework to MVC architecture?
How to achieve localization in Spring MVC applications?
How can we use Spring to create Restful Web Service returning JSON response?
What are some of the important Spring annotations you have used?
Can we send an Object as the response of Controller handler method?
How to upload file in Spring MVC Application?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
What is Spring JdbcTemplate class and how to use it?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you achieve Transaction Management in Spring?
What is Spring DAO?
How to integrate Spring and Hibernate Frameworks?
What is Spring Security?
How to inject a java.util.Properties into a Spring Bean?
Name some of the design patterns used in Spring Framework?
What are some of the best practices for Spring Framework?
Spring Interview Questions and Answers
Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.
Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross-cutting tasks such as logging and authentication using spring support for aspect-oriented programming.
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with the Spring framework is easy and fun at the same time.
Recommended Read: Spring Framework
Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
Some of the features of spring framework are:
Lightweight and very little overhead of using framework for our development.
Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency on our project.
Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example, there is a Spring project for Android to help us write better code for native Android applications. This makes spring framework a complete package and we don’t need to look after the different framework for different requirements.
Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are Separation of Concerns, Boilerplate Code reduction, Configurable components, and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injection to automate the process of dependency injection. But in most of the cases, we are looking for more than just dependency injection and that’s why Spring is the top choice for this.
We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains a sample project zip file, that you can download and play around to learn more.
Spring 5 brought a massive update to Spring framework. Some of the new features in Spring 5 are:
Spring 5 runs on Java 8+ and supports Java EE 7. So we can use lambda expressions and Servlet 4.0 features. It’s good to see Spring trying to support the latest versions.
Spring Framework 5.0 comes with its own Commons Logging bridge; spring-jcl instead of standard Commons Logging.
Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
Spring WebFlux brings reactive programming to the Spring Framework.
Spring 5 also supports Kotlin programming now. This is a huge step towards supporting functional programming, just as Java is also moving towards functional programming.
Support for JUnit 5 and parallel testing execution in the Spring TestContext Framework.
You can read about these features in more detail at Spring 5 Features.
Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in spring framework.
Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.
You can read more about it at Spring WebFlux Tutorial.
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring-based applications.
Some of the important Spring Framework modules are:
Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that are not possible in normal object-oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.
Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.
AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
One of the shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and makes it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.
We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean XML file and initializes all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.
There are three different ways to configure Spring Bean.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
<bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
@Configuration @ComponentScan(value="com.journaldev.spring.main") public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } }
To get this bean from spring context, we need to use following code snippet:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( MyConfiguration.class); MyService service = ctx.getBean(MyService.class);
<context:component-scan base-package="com.journaldev.spring" />
There are five scopes defined for Spring Beans.
singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.
To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the context is destroyed, it also destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
We can do this by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle Methods.
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
@Autowired ServletContext servletContext;
The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually, it’s best practice to do the explicit wiring of all the bean dependencies, but the spring framework also supports auto-wiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation-based configuration in spring bean configuration file. This can be done by context:annotation-config element.
For more details about @Autowired annotation, please read Spring Autowire Example.
There are four types of autowiring in Spring framework.
autowire byName
autowire byType
autowire by constructor
autowiring by @Autowired and @Qualifier annotations
Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType. For more details about these options, please read Spring Bean Autowiring.
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
However, we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle a different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually, it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.
@Component is used to indicate that a class is a component. These classes are used for auto-detection and configured as bean when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually, the business facade classes that provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean>
InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please read Spring MVC File Upload Example.
Spring MVC Framework provides the following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
For a complete example, please read Spring Exception Handling Example.
There are following ways to create spring context in a standalone java program.
AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param>            <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
We can also define multiple root level spring configurations and load it through context-param. For example;
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value> </context-param>
Another option is to use import element in the context configuration file to import other configurations, for example:
<beans:import resource="spring-jdbc.xml"/>
ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file as:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
For creating a simple Spring MVC application, we would need to do the following tasks.
Add spring-context and spring-webmvc dependencies in the project.
Configure DispatcherServlet in the web.xml file to handle requests through spring container.
Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC Hello World application.
As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.
The model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="classpath:messages" /> <beans:property name="defaultEncoding" value="UTF-8" /> </beans:bean> <beans:bean id="localeResolver"    class="org.springframework.web.servlet.i18n.CookieLocaleResolver">    <beans:property name="defaultLocale" value="en" />    <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property>    <beans:property name="cookieMaxAge" value="3600"></beans:property> </beans:bean> <interceptors>    <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">        <beans:property name="paramName" value="locale" />    </beans:bean> </interceptors>
For a complete example, please read Spring Localization Example.
We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.
We would need to do following steps to configure our Spring MVC application to send JSON response:
Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:
Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:
You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.
<!-- Jackson --> <dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>${jackson.databind-version}</version> </dependency>
<!-- Configure to plugin JSON as request and response in method handler --> <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    <beans:property name="messageConverters">        <beans:list>            <beans:ref bean="jsonMessageConverter"/>        </beans:list>    </beans:property> </beans:bean>     <!-- Configure bean to convert JSON to POJO and vice versa --> <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </beans:bean>
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET) public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {    logger.info("Start getEmployee. ID="+empId);        return empData.get(empId); }
For a complete example, please read Spring Restful Webservice Example.
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it. For a complete example, please refer Spring File Upload Example.
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
For custom validator implementation, we need to configure it in the controller class. For a complete example, please read Spring MVC Form Validation Example.
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too. For a detailed example, please refer Spring MVC Interceptor Example.
Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
For JdbcTemplate example, please refer Spring JDBC Example.
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
Sample configuration would be:
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">    <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean>
For complete example, please refer Spring Tomcat JNDI Example.
Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure the transaction manager for the DataSource in the spring bean configuration file.
<bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" /> </bean>
Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.
Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for Hibernate boiler-plate code for transaction management.
For better understanding you should go through following tutorials:
Spring Hibernate Integration Example
Spring MVC Hibernate Integration Example
Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.
It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through the following posts to learn how to use the Spring Security framework.
Spring Security in Servlet Web Application
Spring MVC and Spring Security Integration Example
We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies. For example;
<bean id="propertyConfigurer"  class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">    <property name="location" value="/WEB-INF/application.properties" /> </bean> <bean class="com.journaldev.spring.EmployeeDaoImpl">    <property name="maxReadResults" value="${results.read.max}"/> </bean>
If you are using annotation to configure the spring bean, then you can inject property like below.
@Value("${maxReadResults}") private int maxReadResults;
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
Some of the best practices for Spring Framework are:
Avoid version numbers in schema reference, to make sure we have the latest configs.
Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
For smaller applications, annotations are useful but for larger applications, annotations can become a pain. If we have all the configuration in XML files, maintaining it will be easier.
Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
That’s all for Spring Framework interview questions. I hope these questions will help you in coming Java EE interview. I will keep on adding more questions to the list as soon as I found them. If you know some more questions that should be part of the list, make sure to add a comment for it and I will include it
0 notes
diedinpompeji · 5 years ago
Text
JSP Interview questions
What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the servlet technology. A JSP page is internally converted into servlet.
What are advantages of using JSP?
JSP has several advantages as listed below
JSP Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself. JSP are always compiled before it’s processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. JSP are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
What are the life-cycle methods for a jsp?
JSP life cycle methods are listed below :
public void jspInit() : It is invoked only once, same as init method of servlet. public void _jspService(ServletRequest request,ServletResponse) throws ServletException,IOException : It is invoked at each request, same as service() method of servlet. public void jspDestroy() : It is invoked only once, same as destroy() method of servlet.
What are the advantages of JSP over Active Server Pages (ASP)?
The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
What are the advantages of JSP over Pure Servlets?
It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are:
Embedding of Java code in HTML pages. Platform independence. Creation of database-driven Web applications. Server-side programming capabilities.
What are the advantages of JSP over JavaScript?
JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.
What is difference between hide comment and output comment?
The jsp comment is called hide comment whereas html comment is called output comment. If user views the source of the page, the jsp comment will not be shown whereas html comment will be shown.
Explain lifecycle of a JSP.
A JSP Lifecycle consists of following steps:
Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests Execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc. Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
What are the JSP implicit objects?
JSP provides 9 implicit objects by default. They are as follows:
out : the out is type of JspWriter request : the request is type of HttpServletRequest response : the response is type of HttpServletResponse config : the config is type of ServletConfig session : the session is type of HttpSession application : the application is type of ServletContext pageContext : the pageContext is type of PageContext page : the page is type of Object, it refer to this exception : the exception is type of Throwable
What is a sciptlet in JSP and what is its syntax?
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet: ? 1
<% some java code %>
What are JSP declarations?
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. ? 1
<%! some variable declaration; %>
What are JSP expressions?
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is: ? 1
<%= expression %>
What are JSP comments?
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or “comment out” part of your JSP page.
Following is the syntax of JSP comments: ? 1
<%-- This is JSP comment --%>
What are JSP Directives?
A JSP directive affects the overall structure of the servlet class. It usually has the following form: ? 1
<%@ directive attribute="value" %>
What are the types of directive tags?
The types directive tags are as follows:
<%@ page ... %> : Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. <%@ include ... %> : Includes a file during the translation phase. <%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page.
What are JSP actions?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Its syntax is as follows: ? 1
Name some JSP actions.
Some of the JSP Actions : jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text
What are JSP literals?
Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals:
Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; ” is escaped as \”, ‘ is escaped as \’, and \ is escaped as \\. Null: null
What is a page directive?
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.
What is difference between include directive and include action?
include directive
The include directive includes the content at page translation time. The include directive includes the original content of the page so page size increases at runtime. It’s better for static pages.
include action
The include action includes the content at request time. The include action doesn’t include the original content rather invokes the include() method of Vendor provided class. It’s better for dynamic pages.
Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page.
How can we handle the exceptions in JSP ?
There are two ways to perform exception handling, one is by the errorPage element of page directive, and second is by the error-page element of web.xml file.
What are the two ways to include the result of another page. ?
There are two ways to include the result of another page:
By include directive By include action
Can we use the exception implicit object in any jsp page?
No. The exception implicit object can only be used in the error page which defines it with the isErrorPage attribute of page directive.
How is JSP used in the MVC model?
JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.
What are the different scope values for the tag?
There are 4 values:
page request session application
What is the difference between ServletContext and PageContext?
ServletContext gives the information about the container whereas PageContext gives the information about the Request.
What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
request.getRequestDispatcher(path) is used in order to create it we need to give the relative path of
the resource whereas context.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.
What is EL in JSP?
The Expression Language(EL) is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session etc.
What is basic differences between the JSP custom tags and java beans?
Custom tags can manipulate JSP content whereas beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
Can an interface be implemented in the jsp file?
No.
What is JSTL?
JSP Standard Tag Library is library of predefined tags that ease the development of JSP.
How many tags are provided in JSTL?
There are 5 type of JSTL tags.
core tags sql tags xml tags internationalization tags functions tags
Which directive is used in jsp custom tag?
The jsp taglib directive.
What are the 3 tags used in JSP bean development?
jsp:useBean jsp:setProperty jsp:getProperty
How to disable session in JSP?
<%@ page session="false" %>
What are various attributes Of page directive?
Page directive contains the following 13 attributes.
language extends import session isThreadSafe info errorPage isErrorpage contentType isELIgnored buffer autoFlush isScriptingEnabled
What is a include directive?
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows: ? 1
<%@ include file="relative url" >
What is a taglib directive?
The taglib directive follows the following syntax: ? 1
<%@ taglib uri="uri" prefix="prefixOfTag">
uri : attribute value resolves to a location the container understands
prefix : attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax: ? 1
<%@ taglib uri="uri" prefix="prefixOfTag" >
what is the function of action?
This action lets you insert files into the page being generated. The syntax looks like this: ? 1
Where page is the the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.
What is Action?
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the ? 1
or
tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
What is difference between GET and POST method in HTTP protocol?
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.
0 notes
digitallearning1505-blog · 5 years ago
Video
youtube
14 Servlet & JSP ServletContext and ServletConfig
0 notes
syakuis · 8 years ago
Text
junit Spring sevletContext 얻기
ServletContext servletContext = new MockServletContext("/src/main/webapp", new FileSystemResourceLoader()); or @WebAppConfiguration ... skin ... @Autowired private ServletContext servletContext;
0 notes
crmmanagemet · 8 years ago
Text
Get paid ($$$) : What is differences between ServletContext and ServletConfig
http://dlvr.it/NqbkWT
0 notes
javatutorialandtraining · 10 years ago
Link
Learning pad
Reading initializaion parameters from ServletContext by Neeraj Sir
0 notes
borislit · 12 years ago
Link
0 notes
tccicomputercoaching · 6 years ago
Link
What is difference between servletconfig and servletcontext? tccicomputercoaching.com
0 notes
tccicomputercoaching · 6 years ago
Text
What is difference between servletconfig and servletcontext? tccicomputercoaching.com
Purpose:
The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. It is used for intializing purposes.
The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application. It is application scoped and thus globally accessible across the pages.
Tumblr media
No. of Object:
There is one ServletConfig parameter per servlet.
There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
When created?
Object of ServletConfig will be created during initialization process of the servlet.
Object of ServletContext will be created at the time of web application deployment.
Scope:            
As long as a servlet is executing, ServletConfig object will be available, it will be destroyed once the servlet execution is completed.
As long as web application is executing, ServletContext object will be available, and it will be destroyed once the application is removed from the server.
Availabiltity:
We should give request explicitly, in order to create ServletConfig object for the first time.
ServletContext object will be available even before giving the first request 
Appearance in Web-xml
In web.xml – <init-param> tag will be appear under <servlet-class> tag.
In web.xml – <context-param> tag will be appear under <web-app> tag.
If you like this post then share and like the post.
For more information about Programming concepts, Java Programming, Object Oriented concepts , Computer coaching
Call us @ 9825618292
Visit us @ http://tccicomputercoaching.com/blog/
0 notes
tccicomputercoaching · 5 years ago
Text
Learn generic servlet in Advance Java - tccicomputercoaching.com
What is Generic Servlet class?
- This class implements Servlet and Servlet Config interfaces.
Tumblr media
- It can be extended by a servlet.  - It is a common practice that a servlet class extends protocol-specific, such as HttpServlet class.  - With the help of using life cycle methods, it makes simpler and easier to develop servlets applications.  - To write a generic servlet, the developer need only to override the service() method.  - Additionally, the log method of ServletContext interface is also implemented by Generic Servlet.
To learn more in detail about Generic Servlet and Advance Java
Call us @ 9825618292
Visit us @ http://tccicomputercoaching.com/
0 notes
tccicomputercoaching · 6 years ago
Text
What is difference between servletconfig and servletcontext? tccicomputercoaching.com
Purpose:
The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. It is used for intializing purposes.
The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application. It is application scoped and thus globally accessible across the pages.
No. of…
View On WordPress
0 notes
crmmanagemet · 8 years ago
Text
Get paid ($$$) : What is difference between ServletConfig and ServletContext?
http://dlvr.it/N2SP03
0 notes