简体   繁体   中英

Using a function from one jsp in another jsp

I have a jsp file were the db connection is created and queries can be executed. I want to call these functions (of connecting to a database and executing query) from another jsp simply to add new record to a database and to stay on a same page.

I read here about an "import" tag but i don't have any packages. Also i'm not allowed to use JSTL.

Little help?

Thanks for considering my question.

You can use <%@include %> directive to statically include JSP fragments.

<%@include file="db.jsp" %>

Writing JSPs this way is however considered poor practice . Java code belongs in a Java class, not in a JSP file. You could for example use a preprocessing servlet class wherein you do the job in doGet() method and have a reuseable DAO class wherein you hide all the JDBC boilerplate code away.

Mainly we used to import two types of pages into a jsp page,

  • Java pages
  • JSP pages

If you want to import a java page into your jsp page, syntax is

<%@ page import="package_name.java_page" %>

If you want to import a jsp page, syntax is

<%@ include file='jsp_page_name.jsp'%>

while adding a jsp page, if it is in an another folder, you just need to specify the paths also.

You shouldn't program in your jsp. Put that connection logic out into a class and use that in your jsps.

Afterwards you can import your class with:

<%@ page import="package.yourclass" %> 

In general you should consider using frameworks like Spring MVC or Struts . Using JSF could be another option.

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