You are on page 1of 15

MVC in JSP

MVC stands for Model View and Controller. It is a design pattern that separates the business logic,
presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
1. Navigation Control is centralized
2. Easy to maintain the large application

Example of following MVC in JSP
In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a
model.
In this example, we have created 5 pages:
index.jsp a page that gets input from the user.
ControllerServlet.java a servlet that acts as a controller.
login-success.jsp and login-error.jsp files acts as view components.
web.xml file for mapping the servlet.
File: index.jsp
1. <form action="ControllerServlet" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>
File: ControllerServlet
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class ControllerServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14.
15. String name=request.getParameter("name");
16. String password=request.getParameter("password");
17.
18. LoginBean bean=new LoginBean();
19. bean.setName(name);
20. bean.setPassword(password);
21. request.setAttribute("bean",bean);
22.
23. boolean status=bean.validate();
24.
25. if(status){
26. RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
27. rd.forward(request, response);
28. }
29. else{
30. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
31. rd.forward(request, response);
32. }
33.
34. }
35.
36. @Override
37. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
38. throws ServletException, IOException {
39. doPost(req, resp);
40. }
41. }
File: LoginBean.java
1. package com.javatpoint;
2. public class LoginBean {
3. private String name,password;
4.
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17. public boolean validate(){
18. if(password.equals("admin")){
19. return true;
20. }
21. else{
22. return false;
23. }
24. }
25. }
File: login-success.jsp
1. <%@page import="com.javatpoint.LoginBean"%>
2.
3. <p>You are successfully logged in!</p>
4. <%
5. LoginBean bean=(LoginBean)request.getAttribute("bean");
6. out.print("Welcome, "+bean.getName());
7. %>
File: login-error.jsp
1. <p>Sorry! username or password error</p>
2. <%@ include file="index.jsp" %>
File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
5. id="WebApp_ID" version="3.0">
6.
7. <servlet>
8. <servlet-name>s1</servlet-name>
9. <servlet-class>com.javatpoint.ControllerServlet</servlet-class>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>s1</servlet-name>
13. <url-pattern>/ControllerServlet</url-pattern>
14. </servlet-mapping>
15. </web-app>

Custom Tags in JSP
Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates the
business logic from the JSP page.
The same business logic can be used many times by the use of costom tag.
Advantages of Custom Tags
The key advantages of Custom tags are as follows:
1. Eliminates the need of srciptlet tag The custom tags eliminates the need of scriptlet tag
which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic from
the JSP page so that it may be easy to maintain.
3. Reusability The custom tags makes the possibility to reuse the same business logic again and
again.
Syntax to use custom tag
There are two ways to use the custom tag. They are given below:
1. <prefix:tagname attr1=value1....attrn=valuen />
1. <prefix:tagname attr1=value1....attrn=valuen >
2. body code
3. </prefix:tagname>
JSP Custom Tag API
The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API. The JspTag
is the root interface in the Custom Tag hierarchy.

JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a marker
interface.
Tag interface
The Tag interface is the sub interface of JspTag interface. It provides methods to perform action at the
start and end of the tag.
Fields of Tag interface
There are four fields defined in the Tag interface. They are:
Field Name Description
public static int EVAL_BODY_INCLUDE it evaluates the body content.
public static int EVAL_PAGE it evaluates the JSP page content after the custom tag.
public static int SKIP_BODY it skips the body content of the tag.
public static int SKIP_PAGE it skips the JSP page content after the custom tag.
Methods of Tag interface
The methods of the Tag interface are as follows:
Method Name Description
public void
setPageContext(PageContext pc)
it sets the given PageContext object.
public void setParent(Tag t) it sets the parent of the tag handler.
public Tag getParent() it returns the parent tag handler object.
public int doStartTag()throws
JspException
it is invoked by the JSP page implementation object. The
JSP programmer should override this method and define the
business logic to be performed at the start of the tag.
public int doEndTag()throws
JspException
it is invoked by the JSP page implementation object. The
JSP programmer should override this method and define the
business logic to be performed at the end of the tag.
public void release() it is invoked by the JSP page implementation object to
release the state.

IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional method to
reevaluate the body.
Field of IterationTag interface
There is only one field defined in the IterationTag interface.
public static int EVAL_BODY_AGAIN it reevaluates the body content.
Method of Tag interface
There is only one method defined in the IterationTag interface.
public int doAfterBody()throws JspException it is invoked by the JSP page implementation
object after the evaluation of the body. If this method returns EVAL_BODY_INCLUDE, body
content will be reevaluated, if it returns SKIP_BODY, no more body cotent will be evaluated.

TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag
Handlers. It provides some additional methods also.
Example of JSP Custom Tag
In this example, we are going to create a custom tag that prints the current date and time. We are
performing action at the start of tag.
For creating any custom tag, we need to follow following steps:
1. Create the Tag handler class and perform action at the start or at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file
Understanding flow of custom tag in jsp

1) Create the Tag handler class
To create the Tag Handler, we are inheriting the TagSupport class and overriding its
methoddoStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.
File: MyTagHandler.java
1. package com.javatpoint.sonoo;
2. import java.util.Calendar;
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6. public class MyTagHandler extends TagSupport{
7.
8. public int doStartTag() throws JspException {
9. JspWriter out=pageContext.getOut();//returns the instance of JspWriter
10. try{
11. out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter
12. }catch(Exception e){System.out.println(e);}
13. return SKIP_BODY;//will not evaluate the body content of the tag
14. }
15. }
2) Create the TLD file :Tag Library Descriptor (TLD) file contains information of tag and Tag
Hander classes. It must be contained inside the WEB-INF directory.

File: mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7.
8. <tlib-version>1.0</tlib-version>
9. <jsp-version>1.2</jsp-version>
10. <short-name>simple</short-name>
11. <uri>http://tomcat.apache.org/example-taglib</uri>
12.
13. <tag>
14. <name>today</name>
15. <tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
16. </tag>
17. </taglib>
3) Create the JSP file
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is
recommended to use the uri name instead of full path of tld file. We will learn about uri later.
It uses taglib directive to use the tags defined in the tld file.
File: index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2. Current Date and Time is: <m:today/>

Output

Next Topic
Attributes in JSP Custom Tag
There can be defined too many attributes for any custom tag. To define the attribute, you need to
perform two tasks:
Define the property in the TagHandler class with the attribute name and define the setter
method
define the attribute element inside the tag element in the TLD file
Example to use attribute in JSP Custom Tag
In this example, we are going to use the cube tag which return the cube of any given number. Here, we
are defining the number attribute for the cube tag. We are using the three file here:
index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2.
3. Cube of 4 is: <m:cube number="4"></m:cube>
CubeNumber.java
1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class CubeNumber extends TagSupport{
8. private int number;
9.
10. public void setNumber(int number) {
11. this.number = number;
12. }
13.
14. public int doStartTag() throws JspException {
15. JspWriter out=pageContext.getOut();
16. try{
17. out.print(number*number*number);
18. }catch(Exception e){e.printStackTrace();}
19.
20. return SKIP_BODY;
21. }
22. }
mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>http://tomcat.apache.org/example-taglib</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>cube</name>
15. <tag-class>com.javatpoint.taghandler.CubeNumber</tag-class>
16. <attribute>
17. <name>number</name>
18. <required>true</required>
19. </attribute>
20. </tag>
21. </taglib>
Iteration using JSP Custom Tag
We can iterate the body content of any tag using thedoAfterBody() method of IterationTag
interface.
Here we are going to use the TagSupport class which implements the IterationTag interface. For
iterating the body content, we need to use the EVAL_BODY_AGAIN constant in the doAfterBody()
method.
Example of Iteration using JSP Custom Tag
In this example, we are going to use the attribute in the custom tag, which returns the power of any
given number. We have created three files here
index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2.
3. 3 ^ 5 = <m:power number="3" power="5">
4. body
5. </m:power>

PowerNumber.java
1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class PowerNumber extends TagSupport{
8. private int number;
9. private int power;
10. private static int counter;
11. private static int result=1;
12.
13. public void setPower(int power) {
14. this.power = power;
15. }
16.
17. public void setNumber(int number) {
18. this.number = number;
19. }
20.
21. public int doStartTag() throws JspException {
22. return EVAL_BODY_INCLUDE;
23. }
24.
25. public int doAfterBody() {
26. counter++;
27. result *= number;
28. if (counter==power)
29. return SKIP_BODY;
30. else
31. return EVAL_BODY_AGAIN;
32. }
33.
34. public int doEndTag() throws JspException {
35. JspWriter out=pageContext.getOut();
36. try{
37. out.print(result);
38. }catch(Exception e){e.printStackTrace();}
39.
40. return EVAL_PAGE;
41. }
42. }

mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>http://tomcat.apache.org/example-taglib</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>power</name>
15. <tag-class>com.javatpoint.taghandler.PowerNumber</tag-class>
16.
17. <attribute>
18. <name>number</name>
19. <required>true</required>
20. </attribute>
21.
22. <attribute>
23. <name>power</name>
24. <required>true</required>
25. </attribute>
26.
27. </tag>
28. </taglib>
Looping using Iteration Tag (creating tag for loop)
Let's create a loop tag that iterates the body content of this tag.
File: index.jsp
1. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2. <html>
3. <head>
4. <title>Insert title here</title>
5. </head>
6. <body>
7.
8. <%@taglib prefix="m" uri="sssuri" %>
9. <m:loop end="5" start="1">
10. <p>My Name is khan</p>
11. </m:loop>
12.
13. </body>
14. </html>
File: mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5. <taglib>
6. <tlib-version>1.0</tlib-version>
7. <jsp-version>1.2</jsp-version>
8. <short-name>abc</short-name>
9.
10. <uri>sssuri</uri>
11. <tag>
12. <name>loop</name>
13. <tag-class>com.javatpoint.customtag.Loop</tag-class>
14.
15. <attribute>
16. <name>start</name>
17. <required>true</required>
18. </attribute>
19.
20. <attribute>
21. <name>end</name>
22. <required>true</required>
23. </attribute>
24. </tag>
25.
26. </taglib>
File: Loop.java
1. package com.javatpoint.customtag;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.tagext.TagSupport;
4.
5. public class Loop extends TagSupport{
6. private int start=0;
7. private int end=0;
8.
9. public void setStart(int start) {
10. this.start = start;
11. }
12. public void setEnd(int end) {
13. this.end = end;
14. }
15.
16. @Override
17. public int doStartTag() throws JspException {
18. return EVAL_BODY_INCLUDE;
19. }
20.
21. @Override
22. public int doAfterBody() throws JspException {
23. if(start<end){
24. start++;
25. return EVAL_BODY_AGAIN;
26. }else{
27. return SKIP_BODY;
28. }
29.
30. }
31.
32.
33. }
File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/
web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/jav
aee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
3.
4. <jsp-config>
5. <taglib>
6. <taglib-uri>sssuri</taglib-uri>
7. <taglib-location>/WEB-INF/mytags.tld</taglib-location>
8. </taglib>
9. </jsp-config>
10.
11. </web-app>
Output
Custom URI in JSP Custom Tag
We can use the custom URI, to tell the web container about the tld file. In such case, we need
to define the taglib element in the web.xml. The web container gets the information about the
tld file from the web.xml file for the specified URI.
Example to use custom URI in JSP Custom Tag
In this example, we are going to use the custom uri in the JSP file. For this application, we need to focus
on 4 files.
index.jsp
1. <%@ taglib uri="mytags" prefix="m" %>
2. Today is: <m:today></m:today>

web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE web-app
3. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
4. "http://java.sun.com/dtd/web-app_2_3.dtd">
5.
6. <web-app>
7.
8. <jsp-config>
9. <taglib>
10. <taglib-uri>mytags</taglib-uri>
11. <taglib-location>/WEB-INF/mytags.tld</taglib-location>
12. </taglib>
13. </jsp-config>
14.
15. </web-app>

mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>mytags</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>today</name>
15. <tag-class>com.javatpoint.taghandler.PrintDate</tag-class>
16. </tag>
17. </taglib>

PrintDate.java
1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class PrintDate extends TagSupport{
8.
9. public int doStartTag() throws JspException {
10. JspWriter out=pageContext.getOut();
11. try{
12. out.print(java.util.Calendar.getInstance().getTime());
13. }catch(Exception e){e.printStackTrace();}
14.
15. return SKIP_BODY;
16. }
17.
18.
19. }
1)What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page.It is an extension to the
servlet.A JSP is internally converted into servlet.
more details...
2)What are the life-cycle methods for a jsp?
1. public void jspInit(): It is invoked only once, same as init method of servlet.
2. public void _jspService(ServletRequest request,ServletResponse)throws
ServletException,IOException: It is invoked at each request, same as service() method of
servlet.
3. public void jspDestroy():It is invoked only once, same as destroy() method of servlet.
3)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.
4)What are the JSP implicit objects ?
JSP provides 9 implicit objects bydefault.They are as follows:
Object Type
1) out JspWriter
2) request HttpServletRequest
3) response HttpServletResponse
4) config ServletConfig
5) session HttpSession
6) application ServletContext
7) pageContext PageContext
8) page Object
9) exception Throwable
more details...
5)What is difference between include directive and include action?
1) The include directive includes the content at
page translation time.
1) The include action includes the content at request
time.
2) The include directive includes the original
content of the page so page size increases at
runtime.
2) The include action doesn't include the original
content rather invokes the include() method of Vendor
provided class.
3) It's better for static pages. 3) It's better for dynamic pages.
6)Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are
encapsulated in tag libraries.
7)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.
8)How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
(OR) How to disable caching on back button of the browser?
<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setHeader ("Expires", "0"); //prevents caching at the proxy server
%>

9)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.
more details...
10)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
11)How can we forward the request from jsp page to the servlet ?
Yes ofcourse! With the help of forward action tag, but we need to give the url-pattern of the servlet.
forward action tag
12)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.
more details...
13)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.
14)What are context initialization parameters?
Context initialization parameters are specified by the <context-param> in the web.xml file, these are
initialization parameter for the whole application and not specific to any servlet or JSP.
15)What are the different scope values for the <jsp:useBean>?
They are: 1.Page 2. request 3.session 4.application
16)What is the difference between ServletContext and PageContext?-
ServletContext gives the information about the container whereas PageContext gives the information
about the Request.
17)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.
18)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.
19)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.
20) Can an interface be implemented in the jsp file ?
No.

You might also like