MCQ 3
MCQ 3
MCQ 3
Which of the following is correct statement with respect to Spring test @DirtiesContext
JSR-330 annotations JSR-330 annotations can not beuesd along with Spring framework annotations
To delete the session attribute we can call public void removeAttributes(String name) , By invoking public void
invaliddate(), In web.xml file use <session->
@RunWith(Spring.Junit4ClassRunner.class)
@ContextConfiguration(_________=MyConfig.class)
_____
@RunWith(SpringJUNIT4ClassRunner.class) @ContextConfiguration(----------=MyConfig.class) ----------(profiles="myProfile") Public class TestSpringCustomClass{
classes, @ActiveProfiles
public class TestSpringCustomClass{ @Autowired private Employee employee; } ___
___
}
Choose from below a valid combination to complete the above code____
classes , @ActivePy
@Configuration public class AppConfig { @Bean("address") public Address creatAddress() { Adsress address= new Address(); ApplicatonContext ctx=new AnnotationConfigApplicationContext(AppConfig.class); Address address=(Address)
return Address; }} ctx.getBean("addres");
1
MCQ3
Header.jsp:
<% @ page language = "java" contentType= "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1" %>
<!DOCTYPE html PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN" "HTTP://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<title> insert title here </title>
</head>
<body>
1
<h2> <font color = "blue"> This is content of Header </font> </h2>
</body>
</html>
Footer.jsp
<%@ page languages = "java" contentType = "text html; charset = ISO-8859-1" %>
How many Employee objects will be created if the below code executes successfuly in a main method?
Assume that "context" referes to spring container ApplicationContext
1
1 public static void main(String[] args) {
2 // code for ApplicationContext creation goes here
3 Employee emp1 = (Employee) context.getBean("emp");
4 Employee emp2 = (Employee) context.getBean("emp");
5 Employee emp3= emp1;
6 }
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(__________ = MyConfig.class)
3 __________________(profiles = "myProfile")
4 public class TestSpringCustomClass (
5 @Autowired
6 private Employee employee:
7 // test cases goes here
8 }
Choose from below a valid combination to complete the above code in the order as it appears.
Refer the code given below:
@Entity
class BookEntity{
@ld
private int bookld;
private String title; findByPublisherType(String pType)
private String authorName;
private String publisher Type;
// getters and setters
}
Choose from below the valid option to retrieve the books based on given publisher type by using Query Method Approach
Already Repeated Question
1 @Entity
2 public class CustomerEntity{
@Modifying
3 @Id
4 private int cid;
@Query("delete from CustomerEntity & where k where k.credit*cname)
5 private String cname;
int delete @Param(credit) double credit
6 private double credit;
7 // getter and setter methods
answer is not visible clearly
Choose the valid implementation of the delete query to delete customers who has credit less than a particular value.
2
MCQ3
<body>
<h3>
<%!
int bookld = 1;
int publish Year = 2000;
public int incrementBookld(int bookld) {
return bookld++;
}
Book Id: 2
%> publish Year: 2001
<%
publish Year++;
bookid++;
%>
</h3>
<h3> Book Id: <% = bookld %> </h3>
<h3> Publish Year: <% = publish Year %> </h3>
</body>
Mr. john has been assigned the task of creating a servlet filter to log IP addresses of the computers from which the
request originate. help him from the follwing options to identify the correct order of tags meant for servlet filters
in web.xml file.
When you want to remove the user data from session, what all the various options available in JSP? All option, other than Perform log out ...
From the following tables match the jsp implicit objects given in table A with Api's in servlets package given in table B
Table A Table B
1.out 1.Servlet c 1. OUT - JSPWRITER 2. APPLICATION- SERVLETCONFIG 3.
2.application 2.JSPWriter EXCEPTION . THROWABLE 4. PAGE - OBJECT
3.exception 3. Object
4.page 4.Throwable
which provides the basic implementation of Servlet interface except Generic Servlet
Which is an abstract class which provides the basic implementation of servlet interface except service() method? Generic Servlet
3
MCQ3
<named-query name="getPatientsData">
@Query(name="getPatientData")
<query>select p.pName,p.appointmentDate from patients p </query>
List<String> getPatientsData();
</named-query>
Select the correct methid declaration in DAO interface. Refer the patients class and patients table.
Raghav has added a method to update the details of the patients as below
public interface PatientsDAO
{
@Query(name="updateQuery1") @Modifying is not used on the method output should return the string data which i.. the updated
int updateAppointmentSlot(Patients patients, String new Appointment(Time); appointment time.
}
But he getting exception as "DML operation is not supported".What went wrong?
Raghav added the following methods in Service and DAO implementation classes to add paitent's information in db.
//service implementation
@transactional(propagation=Propagation.REQUIRED)
Integer addPatientInService(Patients patient)
{
//calling DAO method
}
addPatientInDAO() method always exceutes in a new transaction rather than the interface started in service
//DAO implementation layer of addPatientInService() method.
@transactional(propagation=Propagation.REQUIRES_NEW)
Integer addPatientInService(Patients patient)
{
//implementation
}
4
MCQ3
@Component
class Customer(
_____ @Value("#(cartObj")
private Cart cart;
}
Assume instance of the Cart is managed by Spring Container ________
Choose from below a valid SpEL to inject the cart object in Customer bean;
DriverManagerDataSource, LocalContainerEntityManagerFactoryBean,@repository,@A
_____ the incomplete code given below:
<beans>
<!--Assume rest of the configuration is written-->
<tx:annotation-driven transaction-manager____->
-----
-----
</bean>
@Repository,@PersostenceContext@Transactional(value="tx.Manager")
</beans>
____LIne 1____
public class EmployeeDAOlmpl implements____{
____Line 2_____
-------
____Line 3_____
<web-app>
--------------
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
the task of creating a serviet filter to log IP addresses of the requesis originate. help him from the following
options to identify meant for serviet filters in web.xmi file.
<web-mapping>
<filter-name>...</filter-name>
<urt-pattern>...</urt-pattern>
</filter-mapping>
----------
</web-app>
5
MCQ3
<servlet>
<servlet-name>Magazine</servlet-name>
<servlet-class>com.accenture.MagazineServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
Choose from below valid options which provides complete support for creation of JPA specific EntityManagerFactory and
LocalContainerEntityManagerFactoryBean
Transaction Management.
Please Refer the following JSP pages Header.jsp <h1> This is Content of Header</h1> 1
<web-app>
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
Mr. john has been assigned the task of creating a servlet filter to log IP addresses of the computers from which the </filter>
request originate. help him from the follwing options to identify the correct order of tags meant for servlet filters
in web.xml file.(Option is not Visible but answer is correct. just cross check in exam) <filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>
</web-app>
@RunWith(SpringJUNIT4ClassRunner.class) @ContextConfiguration(----------=MyConfig.class) ----------(profiles="myProfile")
Option 1(options not visible)
public class TestSpringCustomClass{ @Autowired private Employee employee; }
Which is an Abstract class which provides the basic implementation of Sevlet interface except Service method? Generic Servlet
Consider the code below package com.accenture.lkm @Component("address") public class Address @Value("Hyderabad-
Employee Address Banglore,Maharashtra
Telangana")
Refer the code given below @Component @Profile("myProfile") class Product{} Choose from below a valid option to activate
System.setProperty("spring.profiles.active", "myProfile");
the profile "myprofile"
6
MCQ3
about @DirtiesContext annotation it is used to closed and load the application context.......
to retrieve the recent access times of a request by user from session? getLastAccessedTime()
(i)When you makes any changes in the...........
When Servlet destroy() method will be invoked by servlet container?
(ii)Whwn you stop the server, Destroy method of the.....
Refer the incomplete code given below:
<beans>
<!--Assume rest of the configuration is written-->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager"class="org.springframework.orm.jpa.jpa">
<property name="entityManagerFactory"ref="cst_entityManagerFactory">
</bean>
</beans>
____Line1_______ @Repository,@PersistenceContext,@Transactional(value="txManager")
public class EmployeeDAolmpl implements EmployeeDAO{
_____Line2______
private EntityManager entityManager;
____Line3_______
public Integer addEmployee(EmployeeBean employeeBean)
Integer employeeID = 0;
return employeeID;
}
7
MCQ3
Assume that class "Employee" is created with property 'empid" and its setter metod
Refer teh spring configuration below
<bean id="emp" class ='com.Employee">
<property name="empID' value ="john">
</bean>
How many Emplotyees objects will be created if the below code executes successfully?
1
public static void main(String[] arg){
Employee emp1 =(Employee) context.getBean("emp");
Employee emp2 =(Employee) context.getBean("emp");
Employee emp3 = emp1;
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(_________=MyConfig.class)
_____________(profiles="myProfile")
classes, @ActiveProfile
public class TestSpringCustomClass{
@Autowired
(Option was not visible properly spelling may be different)
private Employee employee;
Test cases goes here
}
@Entity
public class CustomerEntity{
@Id @Modifying
private int cid; @Query("delete from CustomerEntity k where ......0
private String cname; int delete(@Param("cpoint") double ....
private double credit;
??getter and setter (the words which are not visible is marked as dots)
}
8
MCQ3
Refer the JSP coide given below and predict the output
<body>
<h3>
<%!
int bookId=1;
int publishYear = 2000; Book Id :2
public int incrementBookId(int bookId){ Publish Year :2001
return bookId++;
}
%>
9
MCQ3
(Not visible) is a web developer wants to create a web page which always lands in portal.accenture.com, whenever user hits on welcome button in index.html given below:
index.html
-----------------------
<form action="MyServelet" method="POST">
<input type="submit" value="welcome">
</form>
Now Blessie started writing the code, all of a sudden, she handed over the job of completing it to you due to unavoidable reasons. Incomplete code is attached below for your reference.
MyServlet.java
--------------------------- response.sendRedirect("https:/portal.accenture.com");
@WebServlet(urlPatterns="/MyServlet)
public class MyServlet extends HttpServlet{
public static final long serialVersionUID = 1L;
public myServlet(){
super();
}
..........................................
@Entity
Which of the following are with respect to Spring transaction propagation types:
(i) propagation type Propagation.REQUIRED starts a new transaction, if a method is provided from another method and a transaction does not exist.
both (i) and (ii)
(ii) propagation type Propagation.REQUIRED_NEW starts a new transaction, if a method is invoked from another method and a transaction already exists.
index.html
.......................................
..................Not Visible....................................
when you want to remove the user data from the session,what all the various options available in JSP option starting with(to,by,in)
mr.john has been assigned the task of creating a servlet filter to log IP addresses.......................web.xml file answer not clear but i guess <web>(option 1)
Refer the following JSP pages,
Header.jsp:
<% @ page language="java" content type="text/html:charset=ISO-8859-1" 1
From the following table match the JSP implicit objects given in tabe A with APIs in servlet package given in table B 1-ii,2-i,3-iv,4-iii
.....which provide the basic implementation of servlet interface except GenericServlet
choose from the below the INCORRECT statement about JSR-300 annotation JSR-300 annotation.....
which of the following is/are CORRECT statement with respect to "spring Test" @DirtiesContext is used to mark the context dirty....
which is an abstract class which provide the basic implementation of servlet interface except service() method GenericServlet
10
MCQ3
11
MCQ3
<bean id="transactionManager"
class=org.springframework.orm.jpa.JpaTransactionManager">
<property name="entitymanagerFActory" ref="csf_entityMAnagerFactory"/>
</bean>
</beans>
<web-app>
<filter>
<filter-name>....</filter-name>
<filter-class>...</filter-class>
</filter>
Shed the task of creating a servlet filter to log IP addressess of the requests originate.help him from the following options
<filter-mapping>
to identify meant for servelet filters on web.xml file
<filter-name>....</filter-name>
<uri-pattern>...<uri-pattern>
</filter-mapping>
.....
</web-app>
12
MCQ3
<bean id="messageSource"
rohit wants to externalize the validation error messages. So, he defined the messages in
class="org springframework.support
'com/accenture/lkm/resoruces/messages_en.properties files'.Help rohit to configure the MesageSource beam in the context file
<property name="name" value="classpath\com\accenture\lkm\resources/messages_en.properties"/>
by choosing a valid option from beiow
</bean>
Rohit deployed the application in the Apache Tomcat Server. But he got an exception as "org.springframework.beans.factory. A) Configure<context:component-scan base-package="com.accenture.lkm.dao"/> in the root context
NoSuchBeanDefinitionException:No qualifying vean of type [com.accenture.lkm.dao.PruchaseDAO]". Choose from below valid confifuration
options to succesfully execute his application C) Configure <mvc:annotation-driven/> in the child context configuration
Rohit wants to display all the validation error messages in purchase jsp. <form:form method="POST" modelAttribute="bean" action="store.html">
Help him to display those messages at the bottom of the page. <table border="3">
Choose from below a valid option. Asssume the below taglib <!--Assume form elements are mentioned appropriately -->
directives are added in the jSP. </table>
<%@taglib url="http://springframework.org/tags/form" prefix="form"%> <spring:hasBindErrors name="bean">
<%@taglib
Consider theurl="http://springframework.org/tags"
code given below: prefix="spring"%> <h3>All Errors</h3>
package com.accenture.lkm; <form:errors path="*" cssClass="error"/>
public class Employee { </spring:hasBindErrors>
private list<String>hobbies: </form:form>
//Getters and Setters are already coded
}
<beans>
<bean id ="employee" class="com.accenture.lkm.Employees">
<property name="hobbies">
<list> Employee 2 hobbies [Playing Cricket Watching Movies]
<value Playing Cricket </value>
<value Watching Movies </value>
<list>
</property>
</bean>
</beans>
public class UIT Tester {
public static void main(String
<web-app>
.......
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
the task of creating a servlet filter to log IP addresses of the request originate. Help him from the following options to identify
meant forservlet filters in web.xml file.
<filter-mapping>
<filter-name>....</filter-name>
<urf-pattern>....</urf-pattern>
</filter mapping>
.......
</web-app>
13
MCQ3
Which method is used to retrieve the recent access time of a equeste by user from session?
getLastAccessedTime()
choose from below valid option.
Rohit wants to validate the quantity entered by the customer as mentioned in requirement 2. Choose from the below valid Add @Range(min=1, max=10)anotation in the Bean class
option.[Choose 2] The request handler method should include @Valid to @ModelAnnotation parameter
Rohit wants to receive the requests from customers and forward those request to other components of the application for
further processing . Choose from the most appropriate option, which Rohit performs as his first step as per Spring-MVC
workflow.
A
<bean class="org.springframework>
<property name="prefix">
Rohit wants to navigate to success.jsp page on successful submission. Assume he wrote a handler method to return <value>/WEB-INF/jspViews/</value>
ModelAndView with logical view name as success. He needs to configure a View Resolver bean in child configuration file to </property>
resolve the logical view name.Choose from below a valid option <property name="suffix">
<value>jsp</value>
</property>
</bean>
Rohit wants to create a request handler method in controller that can handle customer request and send the response back to Create a request handler method in the controller to map the request using @RequestMapping annotation and
the response back to the customer. Help rohit to achieve this with a valid option given below. return the ModelAndView object.
Rohit wants to auto populate the items available for the selected SportsType to the respective drop-down box. Assume he A
defined the respective method in the controller which can return Map<String,Double>. Rohit is supposed to bind the key as OPTION NOT VISIBLE
label attribute, value as value attribute in the drop-down box. Choose from below a valid option.
Rohit wants to create an auto populated drop-down box in purchase.jsp page. Help Rohit to implement a proper handler Create a method in the controller to invoke DAO layer method which returns the Map of SportsType with
method in controller that can retrieve sportsType defined in DAO layer. Choose from below a valid option. @ModelAttribute annotation.
From the following tables match the JSP implicit objects given in table A with APIs in
sevlets package given in table B. 1 - ii
Table A Table B 2-i
1) out i) ServletContext
2) application ii) JSPWriter 3 - iv
3) exception
4) page
iii) Object
iv) Threwable
4 - iii
14
MCQ3
Header.jsp:
<% @ page language = "java" contentType= "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1" %>
<!DOCTYPE html PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN" "HTTP://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<title> insert title here </title>
</head>
<body>
1
<h2> <font color = "blue"> This is content of Header </font> </h2>
</body>
</html>
Footer.jsp
<%@ page languages = "java" contentType = "text html; charset = ISO-8859-1" %>
How many Employee objects will be created if the below code executes successfuly in a main method?
Assume that "context" referes to spring container ApplicationContext
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(__________ = MyConfig.class)
3 __________________(profiles = "myProfile")
4 public class TestSpringCustomClass (
5 @Autowired
6 private Employee employee:
7 // test cases goes here
8 }
Choose from below a valid combination to complete the above code in the order as it appears.
Refer the code given below:
@Entity
class BookEntity{
@ld
private int bookld;
private String title; findByPublisherType(String pType)
private String authorName;
private String publisher Type;
// getters and setters
}
Choose from below the valid option to retrieve the books based on given publisher type by using Query Method Approach
1 @Entity
2 public class CustomerEntity{
@Modifying
3 @Id
4 private int cid;
@Query("delete from CustomerEntity & where k where k.credit*cname)
5 private String cname;
int delete @Param(credit) double credit
6 private double credit;
7 // getter and setter methods
answer is not visible clearly
Choose the valid implementation of the delete query to delete customers who has credit less than a particular value.
15
MCQ3
<body>
<h3>
<%!
int bookld = 1;
int publish Year = 2000;
public int incrementBookld(int bookld) {
return bookld++;
}
Book Id: 2
%> publish Year: 2001
<%
publish Year++;
bookid++;
%>
</h3>
<h3> Book Id: <% = bookld %> </h3>
<h3> Publish Year: <% = publish Year %> </h3>
</body>
16
Question-wise Details
Section #1
Choose from below the CORRECT statement about Collection Injection in a bean.
of any type.
Joy is building a web application using servlet. He decided to use servlet filter for intercepting the request and response. Help him
to select the appropriate code from the below options to create a filter
throws ServletException {
stub
2/19
stub
ServletException {
PrintWriter out=response.getWriter();
execution<br>");
chain.doFilter(request, response);
execution");
throws ServletException {
stub
stub
IOException, ServletException {
PrintWriter out=response.getWriter();
execution<br>");
chain.doFilter(request, response);
execution");
throws ServletException {
stub
stub
3/19
public void doFilter(ServletRequest
ServletException {
PrintWriter out=response.getWriter();
execution<br>");
chain.forward(request, response);
execution");
throws ServletException {
stub
stub
PrintWriter out=response.getWriter();
execution<br>");
chain.doFilter(request, response);
execution");
4/19
index.jsp
-----------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:include page="display.jsp">
<jsp:param value="John" name="userName"/>
<jsp:param value="[email protected]" name="email"/>
</jsp:include>
display.jsp
-----------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Username : __________Line1___________
<br/>
Email :__________Line2___________
Choose from below the valid options [Choose 2], in the order as it appears, to print the values of userName and email.
<%=request.getParameter("userName") %>
<%=request.getParameter("email") %>
out.println(request.getParameter("userName"))
out.println(request.getParameter("email"));
<@request.getParameter("userName") %>
<%@request.getParameter("email") %>
<c:out value="${param.userName}"></c:out>
<c:out value="${param.email}"></c:out>
5/19
Refer the incomplete code given below:
package com.accenture.lkm.entity;
@Entity
@Table(name="Doctor")
public class DoctorEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
//setters and getters
}
package com.accenture.lkm.dao;
public interface DoctorDAO extends __________Line1___________{
List<DoctorEntity> __________Line2________________(String firstName);
}
Choose from below the valid option, in the order as it appears, to get doctors details, whose first name starts with 'J' by using
Query Method Approach.
CrudRepository<DoctorEntity, Integer>,
findByFirstNameLike
CurdRepository<DoctorEntity, Integer>,
searchByFirstNameLike
CrudRepository<Integer, DoctorEntity>,
getByFirstNameLike
CrudRepository<DoctorEntity, int>,
selectByFirstNameLike
BookMyBus application allows users to search for bus services in a route. It has a servlet by name SearchBus to respond to such
requests. Given that it is likely to recieve 100 or more requests simultaneously. How likely the web container would respond?
6/19
Options Response Answer
spawning threads.
7/19
Refer the incomplete code given below:
package com.accenture.lkm;
public class Product {
private int productNum;
private String name;
private int barCode;
// Assume setter and getter are generated
}
Below configuration is available in the file located at /com/accenture/lkm/resources/my_springbean.xml
<bean class="com.accenture.lkm.Product" id="prodobj">
<property name="productNum" value="100"></property>
<property name="name" value="Laptop"></property>
<property name="barCode" value="200000"></property>
</bean>
package com.accenture.lkm.test;
@RunWith(SpringJUnit4ClassRunner.class)
_______________1_____________________
public class TestProductClass {
@Autowired
private Product product;
@Test
public void testProduct(){
System.out.println("prod");
Assert.assertTrue(product!=null);
}
____________________2_______________________
@Test
public void testProductBarCode(){
Assert._______3________(product.getBarCode()!=200000);
}
}
Choose from below a valid option to complete the above code, in order to load ApplicationContext for every test method and to
complete the test
8/19
Options Response Answer
@Configuration(locations="/com/accenture/lkm
/resources/my_springbean.xml"),
@DirtiesContext(methodMode=MethodMode.B
EFORE_METHOD), assertFalse
@TestConfiguration(locations="/com/accentur
e/lkm/resources/my_springbean.xml"),
@DirtiesContext, assertFalse
@Configuration(locations="/com/accenture/lkm
/resources/my_springbean.xml"),
@CreateContext(methodMode=MethodMode.
BEFORE_METHOD), assertFalse
@ContextConfiguration(locations="/com/accen
ture/lkm/resources/my_springbean.xml"),
@DirtiesContext(methodMode=MethodMode.B
EFORE_METHOD), assertFalse
From the following help Miss.Nancy to identify CORRECT JSTL tags for creating such table in a JSP page.MovieBean is a bean
with fields movieName, genre and language with getters and setters.
<%@page
import="com.accenture.lkm.business.bean.Mo
vieBean"%>
<%@page import="java.util.ArrayList"%>
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%>
9/19
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sample</title>
</head>
<body>
<%
one.setMovieName("Dunkirk");
one.setGenre("History");
one.setLanguage("English");
two.setMovieName("Spartans 300");
two.setGenre("War film");
two.setLanguage("English");
list.add(one);
list.add(two);
request.setAttribute("movieList", list);
%>
<table>
<tr>
<th>Movie Name</th><th>Genre</th>
<th>Language</th></tr>
<tr><td>${movie.movieName }</td>
<td>${movie.genre}</td>
<td>${movie.language}</td></tr>
</c:forEach>
</table>
</body>
</html>
<%@page
import="com.accenture.lkm.business.bean.Mo
vieBean"%>
<%@page import="java.util.ArrayList"%>
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%>
10/19
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sample</title>
</head>
<body>
<%
one.setMovieName("Dunkirk");
one.setGenre("History");
one.setLanguage("English");
two.setMovieName("Spartans 300");
two.setGenre("War film");
two.setLanguage("English");
list.add(one);
list.add(two);
requestScope.setAttribute("movieList", list);
%>
<table>
<tr>
<th>Movie Name</th><th>Genre</th>
<th>Language</th></tr>
<tr><td>${movie.movieName }</td>
<td>${movie.genre}</td>
<td>${movie.language}</td></tr>
</c:forEach>
</table>
</body>
</html>
<%@page
import="com.accenture.lkm.business.bean.Mo
vieBean"%>
<%@page import="java.util.ArrayList"%>
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
11/19
<meta charset="ISO-8859-1">
<title>Sample</title>
</head>
<body>
<%
one.setMovieName("Dunkirk");
one.setGenre("History");
one.setLanguage("English");
two.setMovieName("Spartans 300");
two.setGenre("War film");
two.setLanguage("English");
list.add(one);
list.add(two);
request.setAttribute("movieList", list);
%>
<table>
<tr>
<th>Movie Name</th><th>Genre</th>
<th>Language</th></tr>
<tr><td>${movie.movieName }</td>
<td>${movie.genre}</td>
<td>${movie.language}</td></tr>
</c:forEach>
</table>
</body>
</html>
12/19
Utility.java:
package com.accenture.lkm;
import java.util.*;
public class Utility {
public List<CustomerBean>getCustomerDetails(){
List<CustomerBean> cList=new ArrayList<CustomerBean>();
CustomerBean c1=new CustomerBean();
c1.setCustomerId(1000);
c1.setCustomerName("John");
CustomerBean c2=new CustomerBean();
c2.setCustomerId(1001);
c2.setCustomerName("Mark");
cList.add(c1);
cList.add(c2);
return cList;
}
}
JSTLDemo.jsp:
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page import="com.accenture.lkm.Utility" %>
<%@page import="com.accenture.lkm.CustomerBean" %>
<%@page import="java.util.List" %>
<body>
<%
Utility u=new Utility();
List<CustomerBean> customerList=u.getCustomerDetails();
request.setAttribute("custList",customerList);
%>
<table border="1">
<c:forEach var="index" items="${custList}">
<tr> <td><c:out value="${index.customerId}"></c:out></td>
<td><c:out value="${index.customerName}"></c:out></td>
</tr>
</c:forEach>
</table>
</body>
</html>
13/19
Options Response Answer
1000 John
1001 Mark
1000 Mark
1001 John
1001 Mark
1002 John
1001 John
1002 Mark
14/19
Refer the following code
LoginForm.html:
<html>
<body>
<form action="Login.jsp">
<table border="1">
<tr> <td> User Name </td><td> <input type="text" name="uname"> </td></tr>
<tr> <td> Password </td><td> <input type="password" name="pwd"> </td>
</table>
<input type="submit" value="submit" />
</form>
</body>
</html>
Login.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<body>
<c:if test="${param.uname=='System' and param.pwd=='admin'}">
<jsp:forward page="Success.jsp">
<jsp:param value="${param.uname}" name="share"/>
</jsp:forward>
</c:if>
</body>
</html>
Success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<body>
<h2> Login Success, Welcome <c:out value="${param.share}"></c:out> </h2>
</body>
</html>
What will be the outcome if the user is entering the following data in LoginForm.html?
uname: System
pwd: admin
15/19
Options Response Answer
No output
Assume that you are creating a web app to get book details from the user and to display it in the response page using Servlet,
JSP and JSTL
Refer below BookForm.jsp - is used to get book details from the user
Refer below BookServlet.java is used to set the book details in the session so that it can be displayed in Book.jsp page
@WebServlet(value="/book")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BookServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
Book book=new Book();
book.setBookId(Integer.parseInt(request.getParameter("bookId")));
16/19
book.setBookName(request.getParameter("bookName"));
book.setAuthor(request.getParameter("author"));
book.setPrice(Double.parseDouble(request.getParameter("price")));
session.setAttribute("bookBean", book);
RequestDispatcher rd=request.getRequestDispatcher("/Book.jsp");
rd.forward(request, response);
}
}
Check below in Book.jsp jsp comment line is added , we must fill code in it to display the book details added in session from
BookServlet using JSTL. Assume that jstl core library is added in the application.
Book.jsp
--------
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<body>
<%@ page import="com.accenture.bean.Book" %>
</body>
17/19
Options Response Answer
<c:set var="bean"
value="${requestScope.bookBean}"/>
<br>
${bean.bookName}"/><br>
<br>
<c:set var="bean"
value="${sessionScope.bookBean}"/>
<br>
${bean.bookName}"/><br>
<br>
<br>
${bean.bookName}"/><br>
<br>
${bean.getBookId}"/><br>
${bean.getBookName}"/><br>
<c:out value="Author:
${bean.getAuthor}"/><br>
<br>
18/19