JSP Question

How can I run a snippet of code upon a user request using JSP? It seems that whether the code is within <% %> or <%= %>, it is always run once the page is displayed. In javascript I am able to run a section of code in this fashion:
<a href="javascript:someCode()"></a>
Is there any way to do something similar using JSP?

If you want to execute java code which is present in the same JSP upon some action of the user, then post the page to itself, for eg.
if your jsp page is Test.jsp residing at address
http:\\127.0.0.1:8080\test\Test.jsp then in ur JSP, in the html form tag specify the action as
<form name="frmTest" method="post" action="Test.jsp">
(Note: the host ip is not required if ur calling the same JSP)
you could use the following eg.JSP name :BTLogin.jsp
<%@ page autoFlush="true" errorPage="ErrorPage.jsp" %>
<jsp:useBean class="LoginBean" id="loginBean" scope="page"/>
<%
// check the request out if this page was called by itself, if so then
// request.getParameter will contain values, else it will be null
userName = request.getParameter("txtUserName");
password = request.getParameter("txtPassword");
if (userName != null && password != null)
retStatus = loginBean.login(userName,password);
%>
<Html>
<Body background="beige">
<form Action="BTLogin.jsp" Method="post" Name="frmLogin">
<Table align="center">
<tr>
User Name :<input ID="txtUserName" Name="txtUserName" Type="text">
</tr>
<tr>
Password :<input ID="txtPassword" Name="txtPassword" Type="password">
</tr>
<tr>
<input ID="btnReset" Name="btnReset" Type="reset" Value="Reset">
<input ID="btnLogin" Name="btnLogin" Type="submit" Value="Login">
</tr>
</table>
</form>
<center>
</center>
</body>
</Html>

Similar Messages

  • Which forum should I use if I have JSP questions?

    Hi, pals!
    Which forum should I use if I have JSP questions?
    Cheers,
    George

    http://forum.java.sun.com/forum.jsp?forum=45

  • Abstract portal component and JSP question

    Can we use htmlb components in abstractportal components.
    I am using isolatedhtmlcontainer in abstractportal component and it is not compiling. It works fine with Dynpage component
    Also one more question can we just write a JSP to get the userid of the portal. I tried typecasting request object to IPortalComponentRequest , but iam not able to get the userid . Can anyone suggest anything . I want get the userid from the jsp and pass this userid to asp as query string
    Thanks
    LAK

    Yes you can create a JSPDynPage and define the component type as NativeJSP in portalapp.xml for e.g.
      <i>      <property name="ComponentType" value="jspnative"/>
            <property name="JSP" value="pagelet/YourJSP.jsp"/></i>
    The explicit object for IPortalComponentRequest is componentRequest in JSP. The other way to get componentRequest is
    IPortalComponentRequest       currentRequest       = (IPortalComponentRequest) pageContext.getAttribute(javax.servlet.jsp.PageContext.REQUEST );
    to get the user further just call currentRequest.getUser()

  • Simple JSP question (newbie)

    Hi all,
    firstly I hope this is the right place to post this question, if not, please accept my apologies,
    I am putting together my first set of JSP pages with Tomcat, and so far everything is going very well, but I am having one small problem.
    I have 1 JSP page at the moment, and that in turn uses 1 JavaBean thing bit of code to do something.
    The problem I am having is passing an integer variable from my JSP page to my JavaBean page, I can't seem to find the right syntax for it. The following code (from the JSP page) will make this ten times clearer...
    <%! int score; %>
    <%! String scoreAsString; %>
    <%
    scoreAsString = request.getParameter("score");
    score = Integer.valueOf(scoreAsString).intValue();
    out.println("Your score of " +score +"was received, thanks very much!");
    %>
    <jsp:useBean id="converter" class="scoreApp.SaveScoreBean"/>
    <jsp:setProperty name="converter" property="scoreToSave" value="${score}" /> As you might see, the problem comes in that last line of code - I want to pass the "score" integer I've received off to the bean, but I don't know the syntax for this. I've tried "value=score", "value="score"", "value="$score"", "value="${score}"" etc. but to no avail.
    You can see this is a super-simple problem :)
    ... but my if it isn't becoming frustrating :)
    Any help at all will be most welcome, and gratefully received.
    Many thanks,
    Peter

    technologyMan wrote:
    I am learning jsp now. You´re actually at the JSF forum here.
    Now, i am a textfield control on jsp as textField1. You are? Really?
    I have created this control from Palette. in java code i am writing "textbox1." but there is no action, no intellisense while pressing ctrl + space.
    How the control is accessing from java code? Maybe my logic with visual studio .net. but i want to learn jsp logic.Uh, just write code accordingly? You can use h:commandButton/h:commandLink for that.
    Anyway, if you want to start with JSF, I can recommend you the following sources:
    Java EE tutorial part II, JSF starts at chapter 10: [http://java.sun.com/javaee/5/docs/tutorial/doc/]
    Good kickoff tutorial: [http://balusc.blogspot.com/2008/01/jsf-tutorial-with-eclipse-and-tomcat.html]
    The JSF taglib documentation: [http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/]
    The JSF API documentation: [http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/overview-summary.html]

  • WLS 7 JSP Questions

    Hi all, a couple of questions.
              WLS 7.001 (think it 001, maybe 01, whatever, it has the first SP I'm pretty
              sure), on W2K (dev) and Solaris 8 (deploy).
              Currently our app is deployed in "exploded" form within WLS, for
              developement, but will be deployed as a single EAR in production.
              Whenever we restart WLS, it seems to need to recompile the JSP as it first
              sees them, rather than taking advantage of the fact that they were compiled
              "last time". Once compiled, the system seems pretty quick, but the JSP
              compiles really crush any built up momentum.
              Is there a way around this? A way for it to not recompile "unchanged" JSPs
              after the sever is restarted?
              Second, what is the Best Practice on how to pre-compile the JSPs, so this
              can be eliminated completely. Does anyone have a good document on how to
              create a WAR filled with pre-compiled JSPs? Is there an ANT task that only
              pre-compiles the changed JSPs during a build?
              I know that there is a "compile JSPs on deploy" option, but that's just not
              practical. Our site has almost 3000 JSPs, and the deploy would just be
              eternal. Worse, the system must "re-deploy" the application whenever WLS
              starts up, which means a recompile, and that's simply not practical.
              Thanx for any advice you can provide. (Yes, I know we have a lot of JSPs,
              but that's not going to change soon...)
              Best Regards,
              Will Hartung
              ([email protected])
              

              Try to set working dir or similar in your weblogic.xml. You can use admin console
              to set/edit it and make the modified descriptors persistent.
              "Will Hartung" <[email protected]> wrote:
              >Hi all, a couple of questions.
              >
              >WLS 7.001 (think it 001, maybe 01, whatever, it has the first SP I'm
              >pretty
              >sure), on W2K (dev) and Solaris 8 (deploy).
              >
              >Currently our app is deployed in "exploded" form within WLS, for
              >developement, but will be deployed as a single EAR in production.
              >
              >Whenever we restart WLS, it seems to need to recompile the JSP as it
              >first
              >sees them, rather than taking advantage of the fact that they were compiled
              >"last time". Once compiled, the system seems pretty quick, but the JSP
              >compiles really crush any built up momentum.
              >
              >Is there a way around this? A way for it to not recompile "unchanged"
              >JSPs
              >after the sever is restarted?
              >
              >Second, what is the Best Practice on how to pre-compile the JSPs, so
              >this
              >can be eliminated completely. Does anyone have a good document on how
              >to
              >create a WAR filled with pre-compiled JSPs? Is there an ANT task that
              >only
              >pre-compiles the changed JSPs during a build?
              >
              >I know that there is a "compile JSPs on deploy" option, but that's just
              >not
              >practical. Our site has almost 3000 JSPs, and the deploy would just be
              >eternal. Worse, the system must "re-deploy" the application whenever
              >WLS
              >starts up, which means a recompile, and that's simply not practical.
              >
              >Thanx for any advice you can provide. (Yes, I know we have a lot of JSPs,
              >but that's not going to change soon...)
              >
              >Best Regards,
              >
              >Will Hartung
              >([email protected])
              >
              >
              >
              

  • Basic JSP question

    Hi,
    I'm starting to use JSP, and I have a few basic questions. I've found some tutorials online, such as the J2EE tutorial, and some others through Google, that have been helpful. However, after reading some tutorials, I still have a basic question:
    If I have a Java class file, can I access that class' methods through my web page using JSP, and then retrieve information from that class?
    For example, if I have a class MyClass, a method myMethod, and an ArrayList<String> arr, would I be able to do something like this from my web page?
    MyClass.myMethod();
    MyClass.arr.get(0);If anyone can give me some advice, or possibly link me to a tutorial that will explain this, I will be very appreciative.

    Yes you can, here is a quick example of how you could do that.
    <%@ page language="java" contentType="text/html"
        pageEncoding="ISO-8859-1"%>
    <jsp:useBean id="myObject" scope="session" class="mypackage.MyClass" />
    <html>
    <body>
    <%
         myObject.myMethod();
    %>
    <%= myObject.arr.get(0) %>
    </body>
    </html>

  • Servlet/JSP question

    Hello guys I have just been reading the HeadFirst Servlet/JSP book from O'REILLY.
    I have used it as a workbook just to see how the framework are use. After ending this book I have planned to do some stuff by my self. I'm precisely in the last chapters of the book right now so I thought about headed toward the Servlet/JSP API. Well in there I found out that the information about JSP were all just about stuff which concerned the Container. I didn't find anything about the syntax used in JSP, the EL syntax nor how the JSTL 1.1 tags looks like! And there where nothing about the DD.
    So I'm wondering were I could fins this information, and why they aren't reserved in the JSP API?
    Another question, when was the JSP2.0/Servlet2.4 specification released?

    Which edition of the book were you reading? It should have covered EL and JSP syntax right?
    Servlet2.4/JSP2.0 has been around for at least 5 years. Can't remember the exact date, but the specification was finalised November 2003.
    The JSP API is from the programming perspective. Tag library documentation is seperate.
    Useful links for you:
    [JSP reference |http://java.sun.com/products/jsp/docs.html] - JSP tags and EL.
    [JSTL Apis|http://java.sun.com/products/jsp/jstl/reference/api/index.html] THE reference for JSTL. Don't be afraid of the JSTL specifications. They are quite readable, and document all the JSTL tags fully. I refer to them constantly.
    Cheers,
    evnafets

  • Jsp question.. using random..

    hi guys ,
    have a quick question regarding jsp and database interection...wonering if this can be done?
    i have a databse where many questions are stored in a databse...
    and there are 10 questions.
    1...if the user wanted only 8 random questions to come up, how would one go about this...
    math random would prob be used but im not that familiar with the method or know it works...
    2....what if i needed to store the number of random questions..
    3.. the page should then only display the specified random question...
    any help would be appreciate.. code samples welcome!
    Thanks!

    um i dont think i have explained my self clearly..
    before the test is taken.. the teacher specifies that the system should choose a ramdom number of question to be repsented to the user for example... 15 questiosn stored ... ask random 10.
    later on the day the student takes the test and 10 questions are displayed...
    the questions are stored in a databse.. and might have to store the random number of questions.. i cant do the way suggessted as all questions appear on one page..
    the question im asking is .. how would you get the random 10 questions out of 15 from the database?

  • Javascript to JSP question...Can javascript function set session attributes

    hello,
    i have a web app that, on one of its pages, displays "tabbed pane" as an image map at the top (a la amazon.com). my problem is this: each "logical" page contains separate forms that all use the same javabean. in other words, imagine that the tabs represent an account maintenance web ui for an on-line record store. the first tab might be labeled "General," the second "Contact info," the third "Shipping Info." Each uses the same account bean and displays portions of its properties relevant to the tab at hand. what i want to do is allow a user to enter the account maintenance ui, update info on the first tab, click on tab two and have the request with the changes sent to a processing jsp. yet, since each "tab" is actually a separate URL to another page, how do i get the updated info on the first tabe without adding some sort of "SAVE" button on each tab. ive considered using javascript, but dont know how to get the request params out of the first tab whn i click on another tab. is it possible to include an "onClick" function in each URL that "grabs" the updated form fields off the preceeding tab? can a javacript function set session attributes in jsp?

    hello there,
    wow, you've created one big mammy-jammy tool.
    first, javascript cannot access, set values to the session, without having to post to another JSP. javascript is great for manipulating objects, layers, form values, etc.
    you have 2 issues [if i understand correctly]:
    1) you need to able to save user info for a specific tab without having to reloading the page.
    ---you can create a form for EACH of your tabs and POST all the information to a hidden IFRAME or LAYER for NN4. that hidden IFRAME / LAYER will load a JSP page which with all the parameters you posted to it. or you can build a FRAMESET and target that document["frame-name"].src with that same JSP.
    2) handling when the SAVE INFO action should happen: hence some javascript event handler: onMouseOver, onClick, etc
    ---i don't know the dynamics of your tabs, but if store which tab was clicked on last, then if the user clicks on some other tab, javascript can submit that FORM to a JSP [see condition above]
    you have an interesting tool. can i see?
    i hope i wasn't too confusing, but your problem is sooo interesting. =)
    -WJP

  • General JSP Questions

    Hi,
    I work at a marketing company and here we still use Classic ASP, and now we're starting to learn and implement JSP on our projects.
    We managed to get things working just like we do in ASP, however with just that I don't see any advantage at all, it's just that we currently are doing exactly the same thing we do with ASP, a form sends the user input to a code-page, we get all the parameters, insert/delete/update the DB, and return the user to another page. Everything's the same, except the language syntax that changed.
    So this is what I'd like to ask, what are some common "best practices" of using the JSP technology?
    As someone who's just started on JSP from ASP, what are the practical advantages?
    (One of the advantages - or actually the only one I can think that really saves some time are the Beans)
    Any sources/tutorials are welcome.
    Thanks,
    Daniel

    DanCoelho wrote:
    As someone who's just started on JSP from ASP, what are the practical advantages?
    (One of the advantages - or actually the only one I can think that really saves some time are the Beans)None. JSP on its own is pretty useless.
    The real power lies in the fact that you have a JVM available to you - in other words you can write and execute Java code. The trick is learning how to do this efficiently so that the web part isn't a bother, and that is where JSPs partly come into play.
    The simplest of the simplest form of Java web development that is at least somewhat of a clean design is to combine Servlet and JSP technology. Servlets are simple java classes that can serve HTTP requests - generally you will use them to handle the business logic side of a request. Database queries, complex calculations and any other kind of data manipulation is done at this point - generally you'll write specific classes to actually do all the work, and you use those classes in your servlets.
    What you do not want to do in Servlets is generate the view - the content sent back to the browser that the user will actually see. Generally this is HTML or XHTML content, but it could be something else entirely. JSPs, in combination with for example JSTL, are far better suited to fulfill this task. JSPs represent simple templates to massage data into page content, and the rule of thumb is that they are only correct when they contain absolutely no java code at all.
    So the general flow of this is:
    - user goes to your website or clicks on a link or a button. This will trigger a servlet.
    - the servlet handles all the business logic that is required
    - when the servlet is done, it forwards control to a JSP
    - the JSP generates the view, based on data that was generated in the servlet
    This may seem like a lot of work, but it really isn't once you get the hang of it. And there are still plenty of ways to make your life even easier still, using specific frameworks that exist such as Spring MVC or JavaServer faces.
    Whatever choices you make, there is one thing that is true for all of them: before you can do anything in the Java web development world, you'll need to know core Java. Intimately.

  • Newbie jsp question

    Hello, I am coming from php, and I was looking for a server side language I could use, but would also hide the source code(meaning i can give people a binary to put on there servers liek with regular java,c,or c++). I searched around for information reagrding this and jsp, and I am unable to tell if i can just give the jsp server a compiled app to run. I am interestd in writing some simple webapps such as a webmial interface, do you think that js pis too overboard for a project like that? Do you guys know of any other server side langauges that might be more useful to me in a situation like that, but can also run off compiled programs instead of reading a script like php and perl? Sincerely,
    Jason

    java binaries (bytecode) do not hide implementation. All that is lost in compiling java sources are tho comments and variable names. Even more, if compiled without the parameter -g:none, some debuging info is left in the bytecode, so it is possible to determine the name of the local variables. For someone who is familiar to java, reading a decompiled source is not very difficult.

  • Simple HTML-JSP Question

    Hi Friends,
    I've a check box and combo in my jsp.I need that only when the checkbox is checked ,combo values
    should be read otherwise not.But whenever the page reloads,the checkbox is selected by default.Can somebody
    tell me how to stop this behaviour i.e initially i need the checkbox as not null...here's part of my code:
    String chk =null,opt=null;
    chk = request.getParameter("chckbox");
    if(chk != null)
      opt = request.getParameter("combo");
    //do something
    <td><input type="checkbox" value="checkd" name="chckbox">Use Options</td>
    <SELECT NAME="combo">
                 <option value="one"<%= (("one".equals(opt))?"selected=\"selected\"":"")%>>YESTERDAY</option>
                 <option value="two"<%= (("two".equals(opt))?"selected=\"selected\"":"")%>>LAST TWO DAYS</option>          
                 </select></td>Thanks

    In HTML you set the check box initial value to checked:
    <input type="checkbox" checked>
    or unchecked:
    <input type="checkbox">
    when you reload the page, if you want to keep the previous value you will need to pass the old value as a parameter and insert this as a variable in the above html
    <input type="checkbox" <%yourJspParameter%>>

  • Simple JSP question

    Help!
    I have a jsp file which retrieves some form input and processes that.
    This is my code:
    String area = request.getParameter("areaname");
    if(area == "Statewide")
    sqlst = "SELECT distinct primarysic, sictitle from utempdb, siccode " +
    " where siccode.siccode = utempdb.primarysic " +
                        " and siccode.sicdiv= '" + indDiv + "'";
    else
    sqlst = "select distinct primarysic, sictitle from utempdb, siccode " +
    " where siccode.siccode=utempdb.primarysic " +
                        " and siccode.sicdiv= '" + indDiv + "'" + " and utempdb.county= '" + area + "'";
    Even if the area is not equal to "Statewide" it processes the second statement and it completely ignores the first statement.
    What is wrong with my code?
    Thanks for any help
    Sue     

    "==" compares references, not contents and so will always be false.
    Try
    if ( "Statewide".equals(area))

  • JSP Question..Very Very Urgent....Please help....

    Hi...
    I am working on customizing existing JSP Page. The idea is to retrieve the customer name as show in 1 and send is as run time parameter to SQL query and use the result of select statement to pass it to 2.
    <INPUT TYPE="HIDDEN" NAME="soldtoCustPartyName" VALUE="<%= soldtoCustPartyName %>">.............1
    The above line of code gives the customer name. We need to find the site id for the above customer and pass it to the following line of code. site id will replace the hardcoded number '7945'.
    pageContext.setAttribute("party_site_id", new BigDecimal(7945), PageContext.REQUEST_SCOPE);...............2
    Hence we create database connection to find out site id. The query will return the site id depending upon the customer name as in 1. SQL statement will be something like:
    select site_id from ..... where fixed conditions and sitename = (from 1).
    How can we create SQL statement to take run time values.
    For eg. we do the following to execute Query after connecting to the databse..
    Statement statement = connection.createStatement();
    ResultSet rs = null;
    rs = statement.executeQuery("SELECT party_id from apps.hz_party_sites where cust_name='IBM'");
    <% rs.next(); %>
    <% out.print(rs.getInt("party_id")); %>
    How can the above query be modified to take run time value for cust_name.
    THIS IS VERY VERY URGENT.....PLEASE HELP.......

    Where are these run time values coming from? The user is entering the values into a form with that input?
    If so, then the user will need to submit the form, you need a servlet to process the form, take the value from the parameter with the same name as the input, insert it into the SQL statement, and run the database query, get the results and store them in the context you want.

  • JSP question on includes

    Okay here's what is happening.
    We have a header and footer file that we want to include across all jsp's in the site.
    We also have a an organization that looks something like this
    /example
    /graphics
    icon1.jpg
    icon2.jsp
    /admin
    admin.jsp
    adminResult.jsp
    /example
    example.jsp
    exampleResult.jsp
    index.jsp
    news.jsp
    profile.jsp
    header.jsp
    footer.jsp
    The problem is that header and footer are both referencing images in their folder, but when admin or example try to view them, the images can't be found because I'm using the base tag. (If I didn't have the base tag, I'd see some strange results.)
    Is there an easy way around this problem so that all the jsps can correctly include the header and footer without the busted graphics?
    TIA.

    One way would be to use an absolute path to the images.

Maybe you are looking for