Rectangle 27 47

Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.

<select name="dd1" onchange="submit()">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="submit()">
    <c:if test="${empty dd2options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd2options}" var="option">
        <option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd3">
    <c:if test="${empty dd3options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd3options}" var="option">
        <option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>

Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.

Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.

<script>
    var dd2options = ${dd2optionsAsJSObject};
    var dd3options = ${dd3optionsAsJSObject};
    function dd1change(dd1) {
        // Fill dd2 options based on selected dd1 value.
        var selected = dd1.options[dd1.selectedIndex].value;
        ...
    }
    function dd2change(dd2) {
        // Fill dd3 options based on selected dd2 value.
        var selected = dd2.options[dd2.selectedIndex].value;
        ...
    }
</script>

<select name="dd1" onchange="dd1change(this)">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="dd2change(this)">
    <option>Please select parent</option>
</select>
<select name="dd3">
    <option>Please select parent</option>
</select>

One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.

  • Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery. <%@ page pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html lang="en"> <head> <title>SO question 2263996</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('#dd1').change(function() { fillOptions('dd2', this); }); $('#dd2').change(function() { fillOptions('dd3', this); }); }); function fillOptions(ddId, callingElement) { var dd = $('#' + ddId); $.getJSON('json/options?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) { $('>option', dd).remove(); // Clean old options first. if (opts) { $.each(opts, function(key, value) { dd.append($('<option/>').val(key).text(value)); }); } else { dd.append($('<option/>').text("Please select parent")); } }); } </script> </head> <body> <form> <select id="dd1" name="dd1"> <c:forEach items="${dd1}" var="option"> <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option> </c:forEach> </select> <select id="dd2" name="dd2"> <option>Please select parent</option> </select> <select id="dd3" name="dd3"> <option>Please select parent</option> </select> </form> </body> </html> ..where the Servlet behind /json/options can look like this: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dd = request.getParameter("dd"); // ID of child DD to fill options for. String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for. Map<String, String> options = optionDAO.find(dd, val); String json = new Gson().toJson(options); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?

Awesome code BalusC. If u dont mind, I want to ask a couple questions on your last method. In your function fillOption(), the line $.getJSON, it look like you send a GET request to the servlet, but where do you specify the url of the servlet. In addition, does the result that send back from the servlet get store in 'opts'. So is 'opts' like and JSON object? Can u explain this line: $('>option', dd).remove(); a bit more?

@Harry Pham: $.getJSON is documented here: api.jquery.com/jQuery.getJSON The URL is just /json/options. Also see the text (don't only look at code). You can just choose whatever URL you want. The opts is indeed JSON string as returned by servlet. Also see the JSON link to learn more about it. If you know Javabeans good, then JSON should look familiar enough. The $('>option', dd).remove() removes all previous options from the dropdown, otherwise it would only be appended, appended, etc.. By the way, if you like answers, just upvote it. I see that you almost never voted.

I see it now, the first parameter of getJSON is the url. I am a complete idiot. About the vote thing, so sorry. I did not even realize that. I will look back at my old post and update the vote. Thank you very much. If I have more question, I will come back and ask u.

So I successfully pre-populate the first combo box with some values from the db. However 1 weird thing happpen: When I select on one of the value from dd1, $('#dd1').change(fillOptions('dd2')); never got invoked again. Inside fillOptions, I put an alert box. I only see the alert box, when I first load the page, but it wont pop out when I select anything in the first combo box. Any idea why?

@BalusC: Your JQuery example won't work, as your "this" inside the fillOptions function will point to the Window object. "this" will only point to an HTMLSelectElement inside the function you passed to the .change function. I had to pass "this" to the fillOptions ("fillOptions('dd2', this)") in order to retrieve the value at the other side ("function fillOptions(ddId, callingElement)" and then "$(callingElement).val()").

Populating cascading dropdown lists in JSP/Servlet - Stack Overflow

jsp servlets drop-down-menu cascading
Rectangle 27 47

Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.

<select name="dd1" onchange="submit()">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="submit()">
    <c:if test="${empty dd2options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd2options}" var="option">
        <option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd3">
    <c:if test="${empty dd3options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd3options}" var="option">
        <option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>

Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.

Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.

<script>
    var dd2options = ${dd2optionsAsJSObject};
    var dd3options = ${dd3optionsAsJSObject};
    function dd1change(dd1) {
        // Fill dd2 options based on selected dd1 value.
        var selected = dd1.options[dd1.selectedIndex].value;
        ...
    }
    function dd2change(dd2) {
        // Fill dd3 options based on selected dd2 value.
        var selected = dd2.options[dd2.selectedIndex].value;
        ...
    }
</script>

<select name="dd1" onchange="dd1change(this)">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="dd2change(this)">
    <option>Please select parent</option>
</select>
<select name="dd3">
    <option>Please select parent</option>
</select>

One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.

  • Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery. <%@ page pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html lang="en"> <head> <title>SO question 2263996</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('#dd1').change(function() { fillOptions('dd2', this); }); $('#dd2').change(function() { fillOptions('dd3', this); }); }); function fillOptions(ddId, callingElement) { var dd = $('#' + ddId); $.getJSON('json/options?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) { $('>option', dd).remove(); // Clean old options first. if (opts) { $.each(opts, function(key, value) { dd.append($('<option/>').val(key).text(value)); }); } else { dd.append($('<option/>').text("Please select parent")); } }); } </script> </head> <body> <form> <select id="dd1" name="dd1"> <c:forEach items="${dd1}" var="option"> <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option> </c:forEach> </select> <select id="dd2" name="dd2"> <option>Please select parent</option> </select> <select id="dd3" name="dd3"> <option>Please select parent</option> </select> </form> </body> </html> ..where the Servlet behind /json/options can look like this: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dd = request.getParameter("dd"); // ID of child DD to fill options for. String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for. Map<String, String> options = optionDAO.find(dd, val); String json = new Gson().toJson(options); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?

Awesome code BalusC. If u dont mind, I want to ask a couple questions on your last method. In your function fillOption(), the line $.getJSON, it look like you send a GET request to the servlet, but where do you specify the url of the servlet. In addition, does the result that send back from the servlet get store in 'opts'. So is 'opts' like and JSON object? Can u explain this line: $('>option', dd).remove(); a bit more?

@Harry Pham: $.getJSON is documented here: api.jquery.com/jQuery.getJSON The URL is just /json/options. Also see the text (don't only look at code). You can just choose whatever URL you want. The opts is indeed JSON string as returned by servlet. Also see the JSON link to learn more about it. If you know Javabeans good, then JSON should look familiar enough. The $('>option', dd).remove() removes all previous options from the dropdown, otherwise it would only be appended, appended, etc.. By the way, if you like answers, just upvote it. I see that you almost never voted.

I see it now, the first parameter of getJSON is the url. I am a complete idiot. About the vote thing, so sorry. I did not even realize that. I will look back at my old post and update the vote. Thank you very much. If I have more question, I will come back and ask u.

So I successfully pre-populate the first combo box with some values from the db. However 1 weird thing happpen: When I select on one of the value from dd1, $('#dd1').change(fillOptions('dd2')); never got invoked again. Inside fillOptions, I put an alert box. I only see the alert box, when I first load the page, but it wont pop out when I select anything in the first combo box. Any idea why?

@BalusC: Your JQuery example won't work, as your "this" inside the fillOptions function will point to the Window object. "this" will only point to an HTMLSelectElement inside the function you passed to the .change function. I had to pass "this" to the fillOptions ("fillOptions('dd2', this)") in order to retrieve the value at the other side ("function fillOptions(ddId, callingElement)" and then "$(callingElement).val()").

Populating cascading dropdown lists in JSP/Servlet - Stack Overflow

jsp servlets drop-down-menu cascading
Rectangle 27 47

Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.

<select name="dd1" onchange="submit()">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="submit()">
    <c:if test="${empty dd2options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd2options}" var="option">
        <option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd3">
    <c:if test="${empty dd3options}">
        <option>Please select parent</option>
    </c:if>
    <c:forEach items="${dd3options}" var="option">
        <option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>

Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.

Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.

<script>
    var dd2options = ${dd2optionsAsJSObject};
    var dd3options = ${dd3optionsAsJSObject};
    function dd1change(dd1) {
        // Fill dd2 options based on selected dd1 value.
        var selected = dd1.options[dd1.selectedIndex].value;
        ...
    }
    function dd2change(dd2) {
        // Fill dd3 options based on selected dd2 value.
        var selected = dd2.options[dd2.selectedIndex].value;
        ...
    }
</script>

<select name="dd1" onchange="dd1change(this)">
    <c:forEach items="${dd1options}" var="option">
        <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
    </c:forEach>
</select>
<select name="dd2" onchange="dd2change(this)">
    <option>Please select parent</option>
</select>
<select name="dd3">
    <option>Please select parent</option>
</select>

One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.

  • Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery. <%@ page pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html lang="en"> <head> <title>SO question 2263996</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('#dd1').change(function() { fillOptions('dd2', this); }); $('#dd2').change(function() { fillOptions('dd3', this); }); }); function fillOptions(ddId, callingElement) { var dd = $('#' + ddId); $.getJSON('json/options?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) { $('>option', dd).remove(); // Clean old options first. if (opts) { $.each(opts, function(key, value) { dd.append($('<option/>').val(key).text(value)); }); } else { dd.append($('<option/>').text("Please select parent")); } }); } </script> </head> <body> <form> <select id="dd1" name="dd1"> <c:forEach items="${dd1}" var="option"> <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option> </c:forEach> </select> <select id="dd2" name="dd2"> <option>Please select parent</option> </select> <select id="dd3" name="dd3"> <option>Please select parent</option> </select> </form> </body> </html> ..where the Servlet behind /json/options can look like this: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dd = request.getParameter("dd"); // ID of child DD to fill options for. String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for. Map<String, String> options = optionDAO.find(dd, val); String json = new Gson().toJson(options); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?

Awesome code BalusC. If u dont mind, I want to ask a couple questions on your last method. In your function fillOption(), the line $.getJSON, it look like you send a GET request to the servlet, but where do you specify the url of the servlet. In addition, does the result that send back from the servlet get store in 'opts'. So is 'opts' like and JSON object? Can u explain this line: $('>option', dd).remove(); a bit more?

@Harry Pham: $.getJSON is documented here: api.jquery.com/jQuery.getJSON The URL is just /json/options. Also see the text (don't only look at code). You can just choose whatever URL you want. The opts is indeed JSON string as returned by servlet. Also see the JSON link to learn more about it. If you know Javabeans good, then JSON should look familiar enough. The $('>option', dd).remove() removes all previous options from the dropdown, otherwise it would only be appended, appended, etc.. By the way, if you like answers, just upvote it. I see that you almost never voted.

I see it now, the first parameter of getJSON is the url. I am a complete idiot. About the vote thing, so sorry. I did not even realize that. I will look back at my old post and update the vote. Thank you very much. If I have more question, I will come back and ask u.

So I successfully pre-populate the first combo box with some values from the db. However 1 weird thing happpen: When I select on one of the value from dd1, $('#dd1').change(fillOptions('dd2')); never got invoked again. Inside fillOptions, I put an alert box. I only see the alert box, when I first load the page, but it wont pop out when I select anything in the first combo box. Any idea why?

@BalusC: Your JQuery example won't work, as your "this" inside the fillOptions function will point to the Window object. "this" will only point to an HTMLSelectElement inside the function you passed to the .change function. I had to pass "this" to the fillOptions ("fillOptions('dd2', this)") in order to retrieve the value at the other side ("function fillOptions(ddId, callingElement)" and then "$(callingElement).val()").

Populating cascading dropdown lists in JSP/Servlet - Stack Overflow

jsp servlets drop-down-menu cascading
Rectangle 27 1044

JSP is a Java view technology running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript, ect.). JSP supports taglibs, which are backed by pieces of Java code that let you control the page flow or output dynamically. A well-known taglib is JSTL. JSP also supports Expression Language, which can be used to access backend data (via attributes available in the page, request, session and application scopes), mostly in combination with taglibs.

When a JSP is requested for the first time or when the web app starts up, the servlet container will compile it into a class extending HttpServlet and use it during the web app's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the /work directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the web server over a network to the client side, which in turn displays it in the web browser.

Servlet is a Java application programming interface (API) running on the server machine, which intercepts requests made by the client and generates/sends a response. A well-known example is the HttpServlet which provides methods to hook on HTTP requests using the popular HTTP methods such as GET and POST. You can configure HttpServlets to listen to a certain HTTP URL pattern, which is configurable in web.xml, or more recently with Java EE 6, with @WebServlet annotation.

When a Servlet is first requested or during web app startup, the servlet container will create an instance of it and keep it in memory during the web app's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by HttpServletRequest and handle the response by HttpServletResponse. Both objects are available as method arguments inside any of the overridden methods of HttpServlet, such as doGet() and doPost().

JSF is a component based MVC framework which is built on top of the Servlet API and provides components via taglibs which can be used in JSP or any other Java based view technology such as Facelets. Facelets is much more suited to JSF than JSP. It namely provides great templating capabilities such as composite components, while JSP basically only offers the <jsp:include> for templating, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work in JSF) when you want to replace a repeated group of components with a single component. Since JSF 2.0, JSP has been deprecated as view technology in favor of Facelets.

As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a JavaBean class as Model. The JSF components are used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet uses the JSF component tree to do all the work.

<c:forEach>
<mytag:doesSomething/>
<jsp:attribute>

Since this is a hugely popular answer, I want to add a very important bit which is JSP tag files which allows for custom tag creation for page composition and layout without writing Java code. This feature is extremly useful and has been part of the standard for many years yet remains underutilized.

@johnny Facelets has been the preferred view technology since Java EE 6 was released in 2009 (docs.oracle.com/javaee/6/tutorial/doc/giepx.html). The minimum set of technologies to develop Java web apps isn't higher than most other languages, but there are many more options and competitors, which is confusing to newcomers. Web development in Ruby? The first choice is obvious.

java - What is the difference between JSF, Servlet and JSP? - Stack Ov...

java jsp jsf servlets java-ee
Rectangle 27 1041

JSP is a Java view technology running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript, ect.). JSP supports taglibs, which are backed by pieces of Java code that let you control the page flow or output dynamically. A well-known taglib is JSTL. JSP also supports Expression Language, which can be used to access backend data (via attributes available in the page, request, session and application scopes), mostly in combination with taglibs.

When a JSP is requested for the first time or when the web app starts up, the servlet container will compile it into a class extending HttpServlet and use it during the web app's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the /work directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the web server over a network to the client side, which in turn displays it in the web browser.

Servlet is a Java application programming interface (API) running on the server machine, which intercepts requests made by the client and generates/sends a response. A well-known example is the HttpServlet which provides methods to hook on HTTP requests using the popular HTTP methods such as GET and POST. You can configure HttpServlets to listen to a certain HTTP URL pattern, which is configurable in web.xml, or more recently with Java EE 6, with @WebServlet annotation.

When a Servlet is first requested or during web app startup, the servlet container will create an instance of it and keep it in memory during the web app's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by HttpServletRequest and handle the response by HttpServletResponse. Both objects are available as method arguments inside any of the overridden methods of HttpServlet, such as doGet() and doPost().

JSF is a component based MVC framework which is built on top of the Servlet API and provides components via taglibs which can be used in JSP or any other Java based view technology such as Facelets. Facelets is much more suited to JSF than JSP. It namely provides great templating capabilities such as composite components, while JSP basically only offers the <jsp:include> for templating, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work in JSF) when you want to replace a repeated group of components with a single component. Since JSF 2.0, JSP has been deprecated as view technology in favor of Facelets.

As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a JavaBean class as Model. The JSF components are used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet uses the JSF component tree to do all the work.

<c:forEach>
<mytag:doesSomething/>
<jsp:attribute>

Since this is a hugely popular answer, I want to add a very important bit which is JSP tag files which allows for custom tag creation for page composition and layout without writing Java code. This feature is extremly useful and has been part of the standard for many years yet remains underutilized.

@johnny Facelets has been the preferred view technology since Java EE 6 was released in 2009 (docs.oracle.com/javaee/6/tutorial/doc/giepx.html). The minimum set of technologies to develop Java web apps isn't higher than most other languages, but there are many more options and competitors, which is confusing to newcomers. Web development in Ruby? The first choice is obvious.

java - What is the difference between JSF, Servlet and JSP? - Stack Ov...

java jsp jsf servlets java-ee
Rectangle 27 0

Haven't tested this, something like this should work:

<%@ tag description="treeview" %>
<ul>
    <jsp:doBody />
</ul>
<%@ tag description="treenode" %>
<%@ attribute name="label" required="true" type="java.lang.String" %>
<%@ attribute name="path" required="true" type="java.lang.String" %>
<li>
    <a href="${path}">${label}</a>
    <jsp:doBody />
</li>
<lib:treeview>
    <lib:treenode label="root" path="#">
        <lib:treeview>
            <lib:treenode label="node" path="#">
            <lib:treenode label="node" path="#">
            <lib:treenode label="node" path="#">
        </lib:treeview>
    </lib:treenode>
</lib:treeview>
<ul>
    <li>
        <a href="#">root</a>
        <ul>
            <a href="#">node</a>
            <a href="#">node</a>
            <a href="#">node</a>
        </ul>
    </li>
</ul>

Java JSP custom tag for nested tree structure. - Stack Overflow

java jsp jsp-tags
Rectangle 27 0

There is good discussion about how to achieve it manually (using jsp recursion) and also a good list of third-party utilities that can easily do it for you.

java - Display tree structure on a jsp using Recursion and JSTL - Stac...

java jsp servlets jstl
Rectangle 27 0

Not out the box. You have to create it yourself or to head to a 3rd party taglib or framework.

java - creating a Directory tree structure on a JSP - Stack Overflow

java jsp
Rectangle 27 0

View is different from what you can get in server-side.

Step 1 Learn how to implement a javascript tree in your JSP

http://plugins.jquery.com/tag/tree/

Step 2 Then simply pass the tree variables from the server-side to construct the actual directory tree you're looking for.

java - How to display server directory as tree in jsp? - Stack Overflo...

java ajax jsp java-ee jstl
Rectangle 27 0

Fact: JSP runs at webserver, produces HTML/CSS/JS and sends it to webbrowser. JS runs at webbrowser and sees only the HTML DOM tree, not any line of Java/JSP. Rightclick page in webbrowser, choose View Souce and see yourself. Do you understand this? OK, then continue.

In the generated HTML source you should see some HTML <input type="text"> elements in place of Struts' <html:text> components. I don't do Struts, but a bit decent MVC framework will assign those HTML elements an id as well. If not done or when the ID value is randomly generated, you'd like to set a fixed ID yourself. According the TLD documentation, you need to set the styleId attribute: <html:text styleId="someFixedId">.

Finally, write a JS function which get executed on click of the checkbox and modifies the disabled attribute of those text elements accordingly. Andy E has already given some hints. Here is how the JSP should basically look like:

<html:text property="my_dto.number1" styleId="number1" />
<html:text property="my_dto.number2" styleId="number2" /> 
<input type="checkbox" id="isTrue" onclick="disableNumbers(this)" /> 

<script>
    function disableNumbers(checkbox) {
        var number1 = document.getElementById("number1");
        var number2 = document.getElementById("number2");
        number1.disabled = number2.disabled = checkbox.checked;
    }
</script>

I think onchange would be more suitable, onclick won't fire if you focus the checkbox and press the spacebar key. I can't remember if onchange fires before or after though, so a 0ms timeout might also be needed.

@Andy: it will :) Test yourself. Oh, there's one more disadvantage of onchange: it get only fired when checkbox loses focus.

huh, I couldn't find that documented anywhere... You're right about the change event firing when focus is lost (but it's not true of all browsers and it's only the case when the keyboard is used). I think you've proven the click event works better for this situation though, +1 :-)

@Andy: not only for this situation. Always use it whenever you want to hook on a change of checkbox / radio button. The onchange on those elements won't behave as you'd intuitively expect.

javascript disable textbox in jsp page - Stack Overflow

javascript jsp
Rectangle 27 0

Roll your own with jsp recursion

Controller.java
Node root = getTreeRootNode();
request.setAttribute("node", root);
main.jsp
<jsp:include page="node.jsp"/>
node.jsp
<c:forEach var="node" items="${node.children}">
    <!-- TODO: print the node here -->
    <c:set var="node" value="${node}" scope="request"/>
    <jsp:include page="node.jsp"/>
</c:forEach>

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Displaying tree on JSP page - Stack Overflow

java jsp recursion tree
Rectangle 27 0

vote up for the answer, what concerns your further issues, if your code is really as posted so the class being with the blank, you need to access it via xpath with the blank as well

driver.findElement(By.xpath("//span[@class='tree ' and contains(text(),'Categories')]")).click();

java - Click on jsp tree element - Stack Overflow

java selenium selenium-webdriver
Rectangle 27 0

You could use a javascript based graph rendering engine to render this. You could then attach urls to each node and make them navigable. Try http://bluff.jcoglan.com/api.html for graphs. You can lookup js graphing libraries and you will find many. It may also be a good time to get some based libraries and do it natively in HTML :)

java ee - Display binary tree using JSP - Stack Overflow

jsp java-ee
Rectangle 27 0

Assuming, there is just a single span tag in the webpage, with innerHTML/text as "Categories"

driver.findElement(By.xpath("//span[@class='tree ' and contains(text(),'Categories')]")).click();

I tried it, however, selenium does not find it on the page? Which version of selenium do you use?

My selenium version is 2.44.0. Please tell me two things. Are there multiple span elements with same innerHTML/Text as 'Categories' ? And, what exception are you getting when you run the above code ?

java - Click on jsp tree element - Stack Overflow

java selenium selenium-webdriver
Rectangle 27 0

I've used struts2-jquery-plugin in the past to draw dynamic trees.

java - How can i generate dynamic tree view in jsp using struts 1.3.10...

java javascript jsp struts2 struts-1
Rectangle 27 0

Facelets doesn't work that way. Unlike a JSP file, a Facelets file isn't compiled to a Java class. It's instead "compiled" to a XML tree, usually by a SAX parser (which is one of the fastest ways of parsing XML). The XML tree is in turn internally cached in server's memory by DefaultFaceletCache (in case of Mojarra) which can be customized by providing a custom FaceletCache.

java - Compiling Facelets - Stack Overflow

java jsf compiler-construction facelets
Rectangle 27 0

If you are willing to use a web application framework, you may also consider the Tree-component from Vaadin. See the Sampler for a Tree example, including source code.

java - creating a Directory tree structure on a JSP - Stack Overflow

java jsp
Rectangle 27 0

Thanks much for the help. I ended up just overriding document.write as such

document.write = function(){
    document.getElementById("MyDiv").innerHTML = arguments[0];
}

function getTreeStruct() {
new Ajax.Request('MainServlet', {
    method: 'POST',
    parameters: "action=getTreeStruct",
    onSuccess: function(transport) {

        d = new dTree('d');
        d.add(0, -1, 'Root Element');
        //contains data queried from database to be inserted into the tree.
        var responseArray = transport.responseText.split("|");
        //Add each element to the tree object
        iterate1DArray(function(x) {
            var tempArray = x.split(",");
            if(tempArray[1] != undefined
                    && !(tempArray[0] == 0 && tempArray[1] ==0)){
                d.add(tempArray[0], tempArray[1], tempArray[2]);
            }
        }, responseArray);

        document.write(d);

    }
});

}

function iterate1DArray(func, array) {
    for( var i = 0; i < array.length; i++){
        array[i] = func(array[i]);
    }
}

I did not include the code for the tree, but it can be found here. Just thought I would put this on here in case anyone else has this type of issue. Thanks again for all your help!

java - Loading a Dynamic Javascript Tree Structure into a JSP - Stack ...

java javascript jsp dynamic tree
Rectangle 27 0

If you want partial page updates, then there is no other way than using JavaScript/Ajax (okay, you can in theory do so with a client side application like a Java applet, but that's plain clumsy). JSP runs on the server side, generates a bunch of HTML and sends it to the client side. On the client side, there is no means of any Java/JSP code. All you can do is to grab JavaScript for a bit dynamics. JavaScript is able to send HTTP requests/responses asynchronously and access/manipulate the HTML DOM tree.

  • Learn the basic JavaScript concepts: JavaScript tutorial
  • Learn the Ajax concepts: Ajax tutorial
  • Learn the jQuery which makes Ajax/HTMLDOM very easy and crossbrowser compatible: jQuery

Now you can work through the examples provided in How to use Servlets and Ajax? to grasp the general concepts so that you can reapply it for your own use case. Here's a basic kickoff example:

<div id="serverTime"></div>

<script>
    setTimeout(function() {
        $.get("timeServlet", function(response) {
            $("#serverTime").text(response);
        });
    }, 1000);
</script>

with the following in servlet's doGet()

response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);

response.setContentType("text/plain");
response.getWriter().write(new Date()); // Use SimpleDateFormat if necessary.

How can I refresh the time in my browser is showing with JSP? - Stack ...

jsp
Rectangle 27 0

1.session.isNew() returns true ,i have used sesssion ,then why is it still a new session

Probably because the server container has just created a new session. Take a look at the request and response headers and at your browser's cookie cache. Is a session cookie being set? Does the session cookie keep changing?

2.i am not able to use else in the jsp,getting syntax error on token

Look at the Java code generated for the JSP and look for the syntax error there. The file will be some temporary directory in the web container directory tree.

3.there is a log out button on the output.jsp now i want that on clicking the log out button,the user should able to go out of session

You will need to do this in a servlet. The simple way would be to call invalidate on the Session object. This may or may not work, depending on how your login mechanism / session cookie management is implemented.

java - Facing Problem in making a login page using servlets and jsp - ...

java html jsp servlets