Hi friends,
In this post , I am sharing interview questions answers asked in Candela Labs in round - 2.
Is the DispatcherServlet instantiated via Application context?
Answer:
No,the DispatcherServlet is instantiated by Servlet containers like tomcat or jetty. We must define the Dispatcher Servlet into the web.xml file.
We also include load-on-startup tag = 1, which means DispatcherServlet is instantiated when you deploy the spring MVC application to Tomcat or any other servlet container.
During instantiation, it looks for a file servlet-name-context.xml and then initializes beans defined in this file.
Question 2:
Do we need spring-mvc.jar in our classpath or is it part of spring-core?
Answer:
The spring-mvc.jar is not part of spring-core, which means that if we want to use spring MVC framework in the java project, we must include spring-mvc.jar in the application's classpath.
In a java web application, spring-mvc.jar is usually placed inside the /WEB-INF/lib folder.
Question 3:
How Spring MVC framework works? How HTTP request is processed?
Answer:
- Client sends a request to a URL.
- That request hit the web container e.g. Tomcat or Jetty. Then it looks into web.xml and find the servlet or filter which is mapped to that URL.
- It then delegates the control to servlet or filter to process the request. Web container(Tomcat) is responsible for creating servlet and filter instances and invoking their various lifecycle methods e.g. init(), service() and destroy(). In the case of HTTP request, HTTPServlet handles that and depending upon the HTTP request method, various do...() methods are invoked by container e.g. doGet(), doPost() to process GET request and POST request.
- To enable spring MVC, we need to declare the DispatcherServlet from spring MVC jar into web.xml. This servlet listens for a URL pattern * as shown below in web.xml, which means all requests are mapped to DispatcherServlet.
- Then DispatcherServlet then passes the request to a specific controller depending on the URL requested. It uses handler mapping [@RequestMapping annotation] or spring mvc configuration file to find out the mapping of request URL to difference controllers. Controller classes are also identified using @Controller and @RestController annotations.
- After processing the request , controller returns a logical view name and model to DispatcherServlet and it consults view resolvers until an actual view is determined to render the output.
- DispatcherServlet then contacts the chosen view e.g. Freemarker or JSP with model data and it renders the output.
- This rendered output is returned to the client as HTTP response. On it's way back, it can pass to any configured filgter as well e.g. Spring security filter chain or filters configured to convert the response to JSON or XML.
Question 4:
Which cache you have used and explain the steps to use that cache?
Answer:
There are multiple types of caches:
- Caffeine
- HazelCast
- Redis
- EHCache
- CouchBase
I have used Redis cache.
Redis is an open source in-memory data structure store used as a database, cache and message broker.
It supports data structures such as strings, hashes, lists, set, sorted set and streams.
Redis has built-in replication.
Redis cache limits:
On 32-bit machine,it can store upto 3 GB of data. When cache size reaches the memory limit, old data is removed to make place for new one.
Annotations used:
- @Cacheable : To cache some values
- @Cacheput : To update the cache
- @CacheEvict : To empty the cache
Maven Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application properties:
#Redis config:
spring.cache.type=redis
spring.redis.host-localhost
sprint.redis.port=6379
@EnableCaching annotation on SpringBootApplication main class.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository{
}
@RestController
public class UserController{
private final Logger log = LoggerFactory.getLogger(getClass());
private final UserRepository userRepository;
@Autowired
public UserController(userRepository userRepository){
this.userRepository = userRepository;
}
@Cacheable(value="users", key="#userId", unless="#result.followers<12000")
@RequestMapping(value"/{userId}", method=RequestMethod.GET)
public user getUser(@PathVariable String userId){
log.info("Getting user with ID {}", userId);
return userRepository.findOne(Long.valueOf(userId));
}
}
Question 5:
What will be the output of below code?
public class StringClass{
public static void main(int[] args){
final String str = "First String is computer";
String str1 = str.replaceAll("First", "Last");
System.out.println(str);
}
}
Answer:
It says, main type is not found. Because JVM requires a main method with String[] as arguments.
In the same code, if we try replacing str1 with str, then compiler shows exception that str is declared as final and cannot be changed.
Question 6:
What happens internally when we invoke main method?
Answer:
The purpose of main method in java is to be program execution start point.
When we run java.exe,it makes some JNI calls. These calls load the DLL that is really the JVM.
It will parse the command line arguments , creates a new string array in the JVM to hold these arguments , parses the class name that we specify as containing main() method, uses JNI calls to find the main() method, then invokes the main() method passing the parameters list.
Thanks for reading!!
No comments:
Post a Comment