简体   繁体   中英

Can we implement interface or extend class in JSP?

Can we implement interface in Jsp ? If Yes, Then how or why not?

If yes, then how can we override those unimplemented methods?

Can we extend any other class in jsp ? If no then why or how if yes.

If yes, then what will happen as jsp will be converted as servlet and servlet already extends something else.

If no, then <%@ page extend="package.className"> , what does this mean?

Thanks.

All the code written in JSP will be used to generate the code in service method for a Servlet which URL pattern matches the URL to access to your JSP. Apart of that, it is considered a bad practice to write Java code in JSP, known as scriptlet, and you should not use it anymore.

The extend means that the generated servlet must extend from the class specified in the value. But again, you should avoid using scriptlets.

Instead thinking on using any Java code (through interface, class inheritance or whatever you may come up with later), use an MVC approach and move all your business logic into controller/model. The basic approach is using a Servlet, another approach is using a web framework like Spring MVC or JSF that helps you writing this. For the cases you have to add dynamic data to your view (JSP), you can use Expression Language and libraries like JSTL to solve your problem.

More info:

The attribute extends (not extend ) specifies a class that should implement the interface javax.servlet.jsp.JspPage.

As the generated class name is not necessarily normed or straight-forward, it is not nice to extend another JSP. So extending has little value.

Implementing interfaces does not offer much value, as the JSP class cannot be reused (extended).

In fact JSPs main use should be for the View functionality of the MVC paradigm, where a servlet serves as Controller, and dispatches to the Vew / JSP, with data/Model in the attributes.

Instead of inheritance use POJOs (plain old java objects) to implement some general functionality. Such a class can be developed outside of a web container, for instance by writing unit tests: TDD, test driven development.

Also consider that a JSP can, as a servlet, forward or include another servlet/JSP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM