Methods in JSP (repetitive things)

I had posted this question before but didnt solve me problem.Here I ask it again.
I alway thought that JSP should be used for display purpose.In that what to do if some lines of code are repeated many number of times,and since I cant have a method inside a JSP then I am wondering the solution will be to create a class and then write the output to the out variable.
Please help.
Thanks
MS

Coding to generate multiple table rows (or similar function) in a JSP should still be considered presentation-layer stuff. In other words, a method to repeatedly generate table rows is a display purpose, generally speaking. That said, custom tags go a long way to keeping your JSPs clean and pretty.

Similar Messages

  • How to access java method in JSP

    Hi all,
    I need to access java class (abstract portal component) method doContent() in a JSP which is under PORTAL-INF/jsp folder.
    I did
    <%@ page import = "com.mycompany.Aclass" %>
    <%com.mycompany.Aclass a = new com.mycompany.Aclass (); %>
    Aclass is coming as autofill/prepopulated with cntrl+space
    Till this time, it is working. no errors. But when I do
    a.
    a. (a dot) no methods are populating (autofill..cntrl+space) or If I forcebly add method a.doContent(req,res)... at runtime its giving error.
    It's not only with doContent method... Its with any simple methods in that class or any other class.
    (Other than doContent method in the APC java class are prepopulating/autofilling but giving error in runtime)
    Can anyone help me... how to access java method in JSP.
    I already gone through many SDN forum post... and implemented too---but no use I refered below forum thread
    Retrieve values from Java class to JSP
    URGENT! How to call a java class from JSP.
    Calling a java method from jsp file -
    this thread is same as my issue
    Thanks,
    PradeeP

    1st. The classes must be in packages. 2nd, the package that they are in must be under the WEB-INF/classes directory. 3rd Look on google and/or this site for web application deployment

  • How to use protected method in jsp code

    Could anyone tell me how to use protected method in jsp code ...
    I declare a Calendar class , and I want to use the isTimeSet method ,
    But if I write the code as follows ..
    ========================================================
    <%
    Calendar create_date = Calendar.getInstance();
    if (create_date.isTimeSet) System.out.println("true");
    %>
    ============================================================
    when I run this jsp , it appears the error wirtten "isTimeSet has protected access in java.util.Calendar"

    The only way to access a protected variable is to subclass.
    MyCalendar extends Calendar
    but I doubt you need to do this. If you only want to tell if a Calendar object has a time associated with it, try using
    cal.isSet( Calendar.HOUR );

  • Problems using GET method in JSP

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET method in JSP?
    If anyone have solutions, please let me know.
    thanks.

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in
    windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is
    good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET
    method in JSP?
    If anyone have solutions, please let me know.
    thanks.This problem appears, when one use UTF-16 encoding in JSP - am I right?
    If so there are two solutions:
    1) Temporary: Use "UTF-8" - or any other 8 bit encoding scheme and
    encode Korean symbols with "&1234;" kind of escapes - though it
    may not work
    2) Absolute: get my piece of code, which I have managed to write
    just a month ago resolving absolutely similar problem with UTF-16
    in code using Chinese/Russian/English encodings
    But I wouldn't say that it's costs 10 DDs :) - it's much more
    expensive... So try 1st variant if it wouldn't help - let me know.
    I'll figure :)
    Paul

  • How can we write methods in Jsp ?

    I want to write methods in jsp in such a way that in one method I should have "Creating database connection" and in another method I want to create ResultSet and in another method I want to access the ResultSet.

    u can write methods in jsp using the following tag
    <%!
    public void myMethod()
    %>

  • Calling method from jsp file

    Hi
    is it possible to call any method with in the class except handle method from jsp file?

    You can call , but it would not be a good design approach.A droplet can do the same task for you.
    otherwise :
    eg :
    <%@ page import="com.mypackage.MyClass"%>
    for Static access :
    <%
    String test= MyClass.myMethod();
    %>
    for normal classes :
    <%
    MyClass object = new MyClass();
    String test= object .myMethod();
    %>
    http://stackoverflow.com/questions/10918526/call-java-method-in-jsp-file
    http://www.javaworld.com/javaworld/jw-05-2003/jw-0523-calltag.html?page=2
    ```
    Praveer
    Edited by: Praveer Rai on Mar 26, 2013 5:08 PM

  • Using bean methods within JSP declaration

    Is it true that bean methods will not work in JSP Methods ?
    For example:
    // get the bean
    <jsp:useBean id="FormValidate" scope="session" class="fsm.frontendCtr.FormValidate" />
    // build a new method in jsp
    <%!
    boolean validate(HttpServletRequest req, String submitFlag) {
    FormValidate.checkMandatory("ADRNACHNAME");
    %>ServletExec return:
    Undefined Variable or class name: FormValidate
    If i use the bean Methods outside the method it worx.
    Is there a trick with which I can use BeanMethods in a JSP Method?

    Is it true that bean methods will not work in JSP
    Methods ?
    For example:
    // get the bean
    <jsp:useBean id="FormValidate" scope="session"
    class="fsm.frontendCtr.FormValidate" />
    // build a new method in jsp
    <%!
    boolean validate(HttpServletRequest req, String
    submitFlag) {
    FormValidate.checkMandatory("ADRNACHNAME");
    %>ServletExec return:
    Undefined Variable or class name: FormValidate
    If i use the bean Methods outside the method it worx.
    Is there a trick with which I can use BeanMethods in a
    JSP Method?FormValidate is this Object. If you need others, pass them from parameters. Try to understand the structure of servlet generated by your JSP.
    <%!
    boolean validate(HttpServletRequest req, String submitFlag) {
    this.checkMandatory("ADRNACHNAME");
    %>
    hope this helps,
    yang

  • Can we overide jspService() method in jsp?

    can we overide jspService() method in jsp? Pls reply

    uh, what exactly do you know about the internals of JSP compilation?
    Apparently not enough to even think about doing anything like that or you'd know what your question makes no sense at all!
    The service method is generated at compile/generation time from the content of your JSP, which should give you a pretty good idea about why you can NOT override it inside the JSP...
    And seeing as you should never use scriptlets there's no place you should ever use where you could even define the overridden method.
    Nor is there any name you could give it as the name isn't predefined.

  • How to call java method using jsp

    how to call java method using jsp.....
    anyone can help me.....i having problem here...coz i very new in java and jsp.....
    thanks.....

    keep an eye on this person's thread...they have code there and everything.
    http://forum.java.sun.com/thread.jspa?threadID=777263&tstart=0

  • Calling a external Java method from JSP - using Tomcat server

    Hi all,
    I am trying to call a method in an external Java file from my JSP. I am using Tomcat server.
    I have my class within the package package "mypackage" and it is called myclass.class. It has only one static method mymethod() which reads from a file and writes to a file.
    I compiled the java class and I put the class file under webapps/ROOT/web-inf/classes/mypackage/myclass.class
    I am trying to say something like this from my JSP file(which is under webapps/ROOT) :
    <%@ page import = "mypackage.myclass"%>
    <% myclass.mymethod(); %>
    I am not instatiating the class as its a static method.
    This is what I get while accessing my jsp file :
    javax.servlet.ServletException: try to access class mypackage.myclass from class org.apache.jsp.index_005ftest_jsp
    To put my problem in a nutshell, Can someone guide me how to access a method of an external class from a JSP page? I have a bunch of pages doing the same operation so I thought I would have it in a method and call it from every page. Even though I tried to put the file under web-inf/classes, The JSP is not able to see the class.
    Please help.
    Thanks
    -Uday

    I have a situation that is a bit similar. I have successfully used beans for storing methods used in JSPs and used by other methods in the same class as was suggested above. Now I would like to break some methods into another (utility) class since they are lower level and can be used by lots of things. They are for database operations (given a String query and String dbname, it queries and returns ResultSet for example). I want to have them in a separate class for reusability and OOP.
    I am having problems calling those public static methods in the public class from my bean that communicates with the JSP. I can't compile the class that calls the method in the database ops class. I get an error like :
    loginHelper.java:45: cannot find symbol
    symbol : variable sqlHelper
    location: class dbHelperBean.loginHelper
    and when I include the package name in the call I get
    loginHelper.java:45: cannot find symbol
    symbol : class sqlHelper
    location: package dbHelperBean
    That's strange since the package of both classes is dbHelperBean and the class is indeed called sqlHelper. I tried to compile it in the same directory as sqlHelper as well. What am I doing wrong?
    Thanks for any help.

  • Applying Private & Protected methods inside JSP

    I am trying to apply (or copy) codings from Servlet into JSP.
    One of the issue that I encountered was bringing Private and Protected methods that were listed inside the Servlet class (this case: public abstract class CatalogPage).
    If I only copy everything inside "Public void doGet", JSP would not work.
    1) My question is, is it better approach to apply Private and Protected method beside wrapping around with ( <%! %> (with !)) (like below)?
    I think I heard about using " ! " for private methods somewhere in the internet..
    Here is what I have at JSP.
    <%!
    Private CatalogItem[] items;
    Private String[] itemIDs;
    private String title;
    protected void setItems(String[] itemIDs) {
    protected void setTitle(String title) {
    %>
    <%
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    %>
    2) Is there any other ways I could make the functionality of Private and Protected methods
    work inside the JSP's <% %>?
    Thank you.
    Here is the original Servlet code.
    public abstract class CatalogPage extends HttpServlet {
      private CatalogItem[] items;
      private String[] itemIDs;
      private String title;
      protected void setItems(String[] itemIDs) {
        this.itemIDs = itemIDs;
        items = new CatalogItem[itemIDs.length];
        for(int i=0; i<items.length; i++) {
          items[i] = Catalog.getItem(itemIDs);
    protected void setTitle(String title) {
    this.title = title;
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    CatalogItem item;
    for(int i=0; i<items.length; i++) {
    out.println("<HR>");
    item = items[i];
    // Show error message if subclass lists item ID
    // that's not in the catalog.
    if (item == null) {
    out.println("<FONT COLOR=\"RED\">" +
    "Unknown item ID " + itemIDs[i] +
    "</FONT>");
    } else {
    out.println();
    String formURL =
    "/servlet/coreservlets.OrderPage";
    // Pass URLs that reference own site through encodeURL.
    formURL = response.encodeURL(formURL);
    out.println
    ("<FORM ACTION=\"" + formURL + "\">\n" +
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\" " +
    " VALUE=\"" + item.getItemID() + "\">\n" +
    "<H2>" + item.getShortDescription() +
    " ($" + item.getCost() + ")</H2>\n" +
    item.getLongDescription() + "\n" +
    "<P>\n<CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\" " +
    "VALUE=\"Add to Shopping Cart\">\n" +
    "</CENTER>\n<P>\n</FORM>");
    out.println("<HR>\n</BODY></HTML>");
    null

    I am trying to apply (or copy) codings from Servlet into JSP.What benefit is there to copying code from a servlet to a JSP? Is the servlet "working"?
    One of the issue that I encountered was bringing
    Private and Protected methods that were listed inside
    the Servlet class.
    If I just copy everything inside "Public void doGet",
    JSP would not work.Sounds like you need a redesign.
    1) My question is, is it better approach to apply
    Private and Protected method beside wrapping around
    with ( <%! %> (with !)) (like below)?
    I think I heard about using " ! " for private
    methods somewhere in the internet..Never heard of such a thing. Please cite the link if you have it.
    Here is what I have at JSP.Please, I can't look. This is wrong on so many levels. You've got scriptlet code, CSS style stuff, embedded HTML in one unmaintainable mess.
    Learn JSTL and CSS. Do not, under any circumstances, put scriptlet code in your JSP.
    The right way is to use the JSP purely as display and keep those protected and private methods on the server side where they belong. Have the JSP make a request to another object to do some work, get the result, and displa it.
    %

  • How to access class method in jsp page

    hi ,
    I am new to JSP . I want to access a method returning an arraylist
    of a class.
    this class i saved in WEB-INF>classes folder > where other classes like logonform , etc. are saved ....
    import stmt is <%@ page import="java.io.*, java.util.*, readXml " %>
    <% readXml rd= new readXml();
    Arraylist list=rd.parseDoc();
    %>
    It is not recognizing readXml class......
    Can any body help me in this regard......
    plz help .... i m in urgent need
    thanks in advance.......

    better to put class in a pkg inside webinf> classes folder ...
    but in my case constructor was not public......
    public readXml(){}
    now it works fine...... :)

  • Error while accessing EJB method from JSP

    Hi,
    I am trying to access a bean from a JSP and have the foll. code piece:
    String url = "t3://localhost:7001";
    public Context getInitialContext() throws Exception {
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    p.put(Context.PROVIDER_URL, url);
    return new InitialContext(p);
    String getStackTraceAsString(Exception e)
    // Dump the stack trace to a buffered stream, then send it's contents
    // to the JSPWriter.
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    e.printStackTrace(new PrintWriter(ostr));
    return(ostr.toString());
    %>
    <%
    String op="";
    try {
    // Contact the AccountBean container (the "AccountHome") through JNDI.
    Context ctx = getInitialContext();
    out.println("initial context got !!");
    DemoHome home = (DemoHome) ctx.lookup("demo.DemoHome");
    out.println("home got !!");
    %>
    <p>
    <%
    Demo ac = null;
    try {
    ac = (Demo) home.create();
    out.println("create called!!");
    if (ac==null)
    out.println("ac is null!");
    catch (Exception ee) {
    out.print("exception 1");
    %>
    <p>
    <%
    try {
    out.println("going to call method!");
    if (ac!= null)
    op = ac.demoSelect(); /* FAILURE POINT */
    else
    out.println("ac is null->error!!");
    out.println(ac.demoSelect());
    out.println("string got!!");
    out.println(op);
    catch (Exception e) {
    getStackTraceAsString(e);
    e.printStackTrace();
    out.println("error 2");
    catch(Exception e)
    out.println("error 3!");
    It gives an error on trying to access the method "demoSelect".
    e.printStackTrace gives the output:
    java.lang.RuntimeException: javax.ejb.EJBContext.getEnvironment is deprecated in EJB 1.1. EJB 1.1 compli
    ant containers are not required to implement this method. Use java:comp/env instead.
    <<no stack trace available>>
    JSP output is as foll.-->
    getting initial context initial context got !! home got !!
    create called!!
    going to call method! error 2
    What is wrong???
    pls help!

    Greetings,
    Hi,
    I am trying to access a bean from a JSP and have the
    foll. code piece:
    <%
    String op="";
    try {
    // Contact the AccountBean container (the "AccountHome") through JNDI.
    Context ctx = getInitialContext();
    out.println("initial context got !!");
    DemoHome home = (DemoHome) ctx.lookup("demo.DemoHome");
    out.println("home got !!");Though it doesn't seem to be the problem in this case, good EJB coding practices dictate that your code should be narrowing the home reference before calling any of it's methods (i.e. create(...) )... WebLogic may allow handling of its protocol objects in their native state, but other vendors do not... your application is not portable without narrowing.
    It gives an error on trying to access the method "demoSelect".
    e.printStackTrace gives the output:
    java.lang.RuntimeException: javax.ejb.EJBContext.getEnvironment is deprecated inThe error is not in your JSP, but in the bean... it seems your bean is attempting to acquire its "environment properties" in the pre-1.1 style, when...
    EJB 1.1. EJB 1.1 compliant containers are not required to implement this
    method. Use java:comp/env instead. ...instead, it should be looking them up in its JNDI namespace.
    What is wrong???
    pls help! Regards,
    Tony "Vee Schade" Cook

  • Calling a Method From JSP

    Hello People!!!
    I'm trying to call a method inside a viewObject from a JSP page using taglibs, but I don't know how to do this.
    Anyone can help me to do this call ??
    I need to pass a parameter to the method... this parameter is a column value!!
    thanks

    Are you trying to set a whereclause? If so you can always set the whereclause as an argument to your datasource tag.. An example of this is done in the Online Orders sample app at:
    http://otn.oracle.com/sample_code/products/jdev/content.html (see search_results.jsp)
    In general you can use the scriptable variable that you define for your BC4J Datasource to access different BC4J methods.
    Here's some code snippets showing different ways to access the BC4J Rowset (View Object) or the Application Module..
    <jbo:ApplicationModule id="Mypackage3Module" definition="Project3.Mypackage3Module" releasemode="Stateful" />
    <jbo:DataSource id="ds" appid="Mypackage3Module" viewobject="EmpView3" rangesize="3"/>
    <%
    ds.getRowSet().executeQuery();
    ds.getRowSet().first();
    ds.getRowSet()....(etc)
    // etc..
    or
    ds.getApplicationModule()....(etc)
    %>
    JSP Codeinsight will pop up your options..
    To ensure that Insight will work, make sure you have a closing scriplet marker.. "%>"...
    -Chris

  • Problem in gui components methods  in jsp dynpage

    Hi all,
    i have created an application by using jspdyn page. in that apllication  i have created a button and label . i am not geting any methods for that label and button in jsp file. i am not gettin label_id. set text, button_id setWidth etc..  methods are not getting .please help me regaurding in this issue.
    from..
    RatnaKumar

    Hi ratna,
    write this code
    <hbj:content id="myContext" >
    <hbj:page title="PageTitle">
    <hbj:form id="myFormId" >
    222
    <hbj:radioButton id="RBGenderFemale" text="female" key="rb_fem" tooltip="I am female" disabled="false" />
    <hbj:radioButton id="RBGenderMale" text="male" key="rb_male" tooltip="I am male" disabled="false" />
    111
    </hbj:form>
    </hbj:page>
    </hbj:content>

Maybe you are looking for