mvc in jsp

Upload: monalish-panda

Post on 03-Jun-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 MVC in JSP

    1/15

    MVC in JSP

    MVCstands for Model View and Controller. It is a design patternthat separates the business logic,

    presentation logic and data.

    Controlleracts as an interface between View and Model. Controller intercepts all the incoming requests.

    Modelrepresents the state of the application i.e. data. It can also have business logic.

    Viewrepresents 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.jspa page that gets input from the user.

    ControllerServlet.javaa servlet that acts as a controller.

    login-success.jspand login-error.jspfiles acts as view components.

    web.xmlfile for mapping the servlet.

    File: index.jsp1. 2. Name:
    3. Password:
    4. 5.

    File: ControllerServlet1. packagecom.javatpoint;2. importjava.io.IOException;3. importjava.io.PrintWriter;

    4. importjavax.servlet.RequestDispatcher;5. importjavax.servlet.ServletException;

    6. importjavax.servlet.http.HttpServlet;7. importjavax.servlet.http.HttpServletRequest;8.

    importjavax.servlet.http.HttpServletResponse;9. publicclassControllerServlet extendsHttpServlet {

  • 8/11/2019 MVC in JSP

    2/15

    10. protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)11. throwsServletException, 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=newLoginBean();19. bean.setName(name);20. bean.setPassword(password);21. request.setAttribute("bean",bean);22.23. booleanstatus=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. @Override37. protectedvoiddoGet(HttpServletRequest req, HttpServletResponse resp)38. throwsServletException, IOException {

    39. doPost(req, resp);

    40. }41. }

    File: LoginBean.java1. packagecom.javatpoint;2. publicclassLoginBean {

    3.

    privateString name,password;4.

    5. publicString getName() {6. returnname;

    7. }8. publicvoidsetName(String name) {9. this.name = name;10. }

    11. publicString getPassword() {12. returnpassword;13. }14. publicvoidsetPassword(String password) {15. this.password = password;

    16. }

    17.

    publicbooleanvalidate(){18. if(password.equals("admin")){19. returntrue;20. }21. else{

    22. returnfalse;23. }24. }25. }

    File: login-success.jsp1. 2.

    3.

    You are successfully logged in!

    4.
  • 8/11/2019 MVC in JSP

    3/15

    File: login-error.jsp1.

    Sorry! username or password error

    2.

    File: web.xml1. 2. 6.7.

    8. s19. com.javatpoint.ControllerServlet

    10. 11. 12. s113. /ControllerServlet

    14. 15.

    Custom Tags in JSP

    Custom tagsare 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 tagThe custom tags eliminates the need of scriptlet tagwhich 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. ReusabilityThe custom tags makes the possibility to reuse the same business logic again andagain.

    Syntax to use custom tag

    There are two ways to use the custom tag. They are given below:

  • 8/11/2019 MVC in JSP

    4/15

    1.

    1.

    2. body code3.

    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:

  • 8/11/2019 MVC in JSP

    5/15

    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, bodycontent 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.

  • 8/11/2019 MVC in JSP

    6/15

    For creating any custom tag, we need to follow following steps:

    1. Create the Tag handler classand perform action at the start or at the end of the tag.

    2. Create the Tag Library Descriptor (TLD) fileand 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 classand overriding its

    methoddoStartTag().To write data for the jsp, we need to use the JspWriter class.

    The PageContextclass provides getOut()method that returns the instance of JspWriter class.

    TagSupport class provides instance of pageContext bydefault.

    File: MyTagHandler.java1. packagecom.javatpoint.sonoo;2. importjava.util.Calendar;3. importjavax.servlet.jsp.JspException;4. importjavax.servlet.jsp.JspWriter;5. importjavax.servlet.jsp.tagext.TagSupport;

    6. publicclassMyTagHandler extendsTagSupport{7.

    8. publicintdoStartTag() throwsJspException {9. JspWriter out=pageContext.getOut();//returns the instance of JspWriter10. try{

    11. out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter12. }catch(Exception e){System.out.println(e);}13. returnSKIP_BODY;//will not evaluate the body content of the tag14. }15. }

    2) Create the TLD file :Tag Library Descriptor(TLD) file contains information of tag and TagHander classes. It must be contained inside the WEB-INFdirectory.

    File: mytags.tld1. 2. 5.

    6.

    7.

    8. 1.09. 1.210. simple11. http://tomcat.apache.org/example-taglib12.

    13.

    14. today15. com.javatpoint.sonoo.MyTagHandler

  • 8/11/2019 MVC in JSP

    7/15

    16. 17.

    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 taglibdirective to use the tags defined in the tld file.

    File: index.jsp1.

    2. Current Date and Time is:

    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.

    2.3. Cube of 4is:

    CubeNumber.java1. packagecom.javatpoint.taghandler;

    2.

    3. importjavax.servlet.jsp.JspException;4. importjavax.servlet.jsp.JspWriter;5. importjavax.servlet.jsp.tagext.TagSupport;

    6.

    7. publicclassCubeNumber extendsTagSupport{

    8. privateintnumber;

  • 8/11/2019 MVC in JSP

    8/15

    9.10. publicvoidsetNumber(intnumber) {

    11. this.number = number;12. }13.14. publicintdoStartTag() throwsJspException {

    15. JspWriter out=pageContext.getOut();

    16.

    try{17. out.print(number*number*number);18. }catch(Exception e){e.printStackTrace();}19.20. returnSKIP_BODY;21. }22. }

    mytags.tld

    1.

    2.

    5.6. 7.

    1.08. 1.2

    9. simple10. http://tomcat.apache.org/example-taglib11. A simple tab library forthe examples12.13.

    14. cube

    15. com.javatpoint.taghandler.CubeNumber16. 17. number18. true19. 20.

    21.

    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_AGAINconstant 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. 2.

    3. 3^ 5= 4. body5.

    PowerNumber.java

    1. packagecom.javatpoint.taghandler;2.

  • 8/11/2019 MVC in JSP

    9/15

    3. importjavax.servlet.jsp.JspException;4. importjavax.servlet.jsp.JspWriter;

    5. importjavax.servlet.jsp.tagext.TagSupport;6.7. publicclassPowerNumber extendsTagSupport{8. privateintnumber;

    9. privateintpower;

    10.

    privatestaticintcounter;11. privatestaticintresult=1;12.13. publicvoidsetPower(intpower) {14. this.power = power;15. }16.

    17. publicvoidsetNumber(intnumber) {18. this.number = number;19. }20.

    21. publicintdoStartTag() throwsJspException {22. returnEVAL_BODY_INCLUDE;

    23. }

    24.25. publicintdoAfterBody() {

    26. counter++;

    27. result *= number;28. if(counter==power)29. returnSKIP_BODY;30. else31. returnEVAL_BODY_AGAIN;

    32. }

    33.

    34. publicintdoEndTag() throwsJspException {35. JspWriter out=pageContext.getOut();36. try{37. out.print(result);

    38. }catch(Exception e){e.printStackTrace();}39.

    40. returnEVAL_PAGE;41. }42. }

    mytags.tld1. 2. 5.6. 7. 1.0

    8.

    1.29. simple10. http://tomcat.apache.org/example-taglib

    11. A simple tab library forthe examples12.13.

    14. power15. com.javatpoint.taghandler.PowerNumber16.17.

    18. number19. true20. 21.22.

    23. power

    24. true

  • 8/11/2019 MVC in JSP

    10/15

    25. 26.

    27. 28.

    Looping using Iteration Tag (creating tag for loop)

    Let's create a loop tag that iterates the body content of this tag.

    File: index.jsp1.

    2. 3.

    4. Insert title here5. 6. 7.

    8. 9.

    10.

    My Name is khan

    11.

    12.

    13. 14.

    File: mytags.tld1. 2.

    5. 6. 1.07. 1.28. abc

    9.

    10. sssuri

    11. 12. loop13. com.javatpoint.customtag.Loop14.15.

    16. start17. true18. 19.20.

    21. end

    22. true

    23.

    24. 25.26.

    File: Loop.java1. packagecom.javatpoint.customtag;2. importjavax.servlet.jsp.JspException;

    3. importjavax.servlet.jsp.tagext.TagSupport;4.5. publicclassLoop extendsTagSupport{6. privateintstart=0;

    7. privateintend=0;8.9. publicvoidsetStart(intstart) {

    10.

    this.start = start;11. }

  • 8/11/2019 MVC in JSP

    11/15

  • 8/11/2019 MVC in JSP

    12/15

    index.jsp

    1.

    2. Today is:

    web.xml

    1.

    2.

    5.6.

    7.

    8. 9. 10. mytags11. /WEB-INF/mytags.tld12.

    13. 14.15.

    mytags.tld

    1. 2. 5.6.

    7. 1.08. 1.2

    9. simple10. mytags11. A simple tab library forthe examples12.

    13.

    14. today

    15. com.javatpoint.taghandler.PrintDate16. 17.

    PrintDate.java

    1. packagecom.javatpoint.taghandler;2.3. importjavax.servlet.jsp.JspException;

    4. importjavax.servlet.jsp.JspWriter;5. importjavax.servlet.jsp.tagext.TagSupport;6.

    7.

    publicclassPrintDate extendsTagSupport{8.9. publicintdoStartTag() throwsJspException {

    10. JspWriter out=pageContext.getOut();11. try{12. out.print(java.util.Calendar.getInstance().getTime());13. }catch(Exception e){e.printStackTrace();}

    14.

    15. returnSKIP_BODY;16. }17.18.19. }

    1)What is JSP?

  • 8/11/2019 MVC in JSP

    13/15

    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 atpage translation time.

    1) The include action includes the content at requesttime.

    2) The include directive includes the originalcontent of the page so page size increases atruntime.

    2) The include action doesn't include the originalcontent rather invokes the include() method of Vendorprovided class.

    3) It's better for static pages. 3) It's better for dynamic pages.

    6)Is JSP technology extensible?

    http://www.javatpoint.com/jsphttp://www.javatpoint.com/jsphttp://www.javatpoint.com/jsp-implicit-objectshttp://www.javatpoint.com/jsp-implicit-objectshttp://www.javatpoint.com/jsp-implicit-objectshttp://www.javatpoint.com/jsp
  • 8/11/2019 MVC in JSP

    14/15

    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 andDisadvantages of using it?

    You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is

    done by adding the directive within your JSP page.

    8)How do I prevent the output of my JSP or Servlet pages from being cached by thebrowser?

    (OR) How to disable caching on back button of the browser?

    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:

    Byinclude directive

    Byinclude 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.

    http://www.javatpoint.com/exception-handling-in-jsphttp://www.javatpoint.com/exception-handling-in-jsphttp://www.javatpoint.com/jsp-include-directivehttp://www.javatpoint.com/jsp-include-directivehttp://www.javatpoint.com/jsp-include-directivehttp://www.javatpoint.com/jsp-include-actionhttp://www.javatpoint.com/jsp-include-actionhttp://www.javatpoint.com/jsp-include-actionhttp://www.javatpoint.com/jsp-action-tags-forward-actionhttp://www.javatpoint.com/jsp-action-tags-forward-actionhttp://www.javatpoint.com/exception-implicit-objecthttp://www.javatpoint.com/exception-implicit-objecthttp://www.javatpoint.com/exception-implicit-objecthttp://www.javatpoint.com/jsp-action-tags-forward-actionhttp://www.javatpoint.com/jsp-include-actionhttp://www.javatpoint.com/jsp-include-directivehttp://www.javatpoint.com/exception-handling-in-jsp
  • 8/11/2019 MVC in JSP

    15/15

    14)What are context initialization parameters?

    Context initialization parameters are specified by the 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 ?

    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() andcontext.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.