Results 1 to 13 of 13

Thread: [RESOLVED] Jstl / Mvc

  1. #1

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Resolved [RESOLVED] Jstl / Mvc

    I am required to write a small JSP application for an assignment as university. I am familiar with Java and have done a little reading on he JSP specification so here is what I plan to do:
    • All output will be produced using a set of JSTL pages and templates.
    • Input via the POST method will be handled by servlets - upon successfully carrying out the request, it will be despatched to a JSTL page where the result will be rendered (I would prefer to dispatch the request via an HHTTP redirect).
    • Although it looks as though JSTL's are compiled into servlets and an instance of each servlet is kept within memory, I will make the connection to the SQL database on a per request basis. If JDBC has a thread safe way of maintaining a connection within the servlet instance I'd love to know

    Are there any problems are bad practices I am using here or any refinements I can make to the way I am doing it?
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  2. #2
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Jstl / Mvc

    No problems. Looks like good practices. Two potential pitfalls, though.

    1) The client-side redirect through HttpServletResponse.sendRedirect() sends a Moved Permanently (301) reponse. This is bad practice for follow-up pages. What should really be sent is, for HTTP/1.1 clients, a 303 See Other response, while HTTP/1.0 clients should receive a 302 Found code. However, Servlets lack a convenient built-in way of doing that. (The spec writers probably expected internal forwards to be sufficient. They didn't consider the double-post problem of such an approach.)
    Here's a utility function to remedy that; use it instead of HttpServletResponse.sendRedirect().
    Code:
    public static void sendResultRedirect(HttpServletRequest req,
    	HttpServletResponse resp, String path)
    {
    	path = path.trim();
    	if(req.getProtocol().equals("HTTP/1.0")) {
    		resp.setStatus(HttpServletResponse.SC_FOUND);
    	} else {
    		resp.setStatus(HttpServletResponse.SC_SEE_OTHER);
    	}
    	StringBuilder builder = new StringBuilder();
    	if(path.startsWith("http:") || path.startsWith("https:")) {
    		// Path is totally absolute.
    		builder.append(path);
    	} else if(path.startsWith("//")) {
    		// Special feature: "//" means relative to context.
    		builder.append(req.getScheme()).append("://").
    			append(req.getServerName());
    		if(req.getServerPort() != 80) {
    			builder.append(":").append(req.getServerPort());
    		}
    		builder.append(req.getContextPath()).append(path.substring(1));
    	} else if(path.startsWith("/")) {
    		// Relative to server root.
    		builder.append(req.getScheme()).append("://").
    			append(req.getServerName());
    		if(req.getServerPort() != 80) {
    			builder.append(":").append(req.getServerPort());
    		}
    		builder.append(path);
    	} else {
    		// Relative to current location.
    		String current = req.getRequestURI();
    		builder.append(req.getScheme()).append("://").
    			append(req.getServerName());
    		if(req.getServerPort() != 80) {
    			builder.append(":").append(req.getServerPort());
    		}
    		builder.append(current.substring(0, current.lastIndexOf('/')+1)).
    			append(path);
    	}
    	resp.setHeader("Location", resp.encodeRedirectURL(builder.toString()));
    }
    The function works identically to sendRedirect(), except for the status codes and one special feature I built in: a path starting with "//" will be resolved relative to the current context. (sendRedirect() only knows absolute URLs with protocol being used directly, absolute URLs without protocol or server being resolved from the server root and relative URLs being resolved relative to the current request.)

    2) Connection per request is doable - after all, all PHP applications do it. But still it is more efficient to set up a database connection pool. If you've got access to your context configuration and you're using Tomcat as the servlet container, this works like this:
    a) Put the JDBC driver for your DB into Tomcat's common/lib directory.
    b) Put the Apache Jakarta Commons DBCP JAR and dependencies (Commons Pool, mostly) into the same directory.
    c) Modify the Context configuration for your web application. You can find this config
    - in Tomcat's server.xml, as a nested <Context> element of <Host> or
    - in the Catalina/<hostname>/<contextname>.xml file in Tomcat's configuration directory (where server.xml is - that would be ${CATALINA_HOME}/conf/) or
    - in the META-INF/context.xml (not WEB-INF) file in your web application directory.
    d) Add the following to the configuration:
    Code:
    <Resource name="jdbc/db" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="username" password="secret" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/dbname?autoReconnect=true"/>
    e) When you need one, retrieve a Connection:
    Code:
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    java.sql.Connection c = (java.sql.Connection)ctx.lookup("java:comp/env/jdbc/db");
    Don't forget to close it when you're done (do it in a finally block) or you'll exhaust the pool.

    One final thing: in my opinion, there's no such thing as a "JSTL page". There's just JSP pages. Whether they make use of JSTL or not is really irrelevant.
    As I said, my opinion.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  3. #3

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    Thanks for the detailed info I will have a look into the connection pooling.

    I am making use of JSTL so I can force myself not to include huge chunks of Java code within HTML pages. I am planning on accessing objects with useBean:

    <jsp:abuseBean name="cart" context="session" class="eshop.Cart" />

    One of the things that confuses me about this is you cannot access methods of the object only its setters and getters. Does this mean that all logic needs to be included within these?

    Say for example I have an authentication class, how would one create a ninstance of the class and check that the user has authenticated:
    Code:
    <c:if test="{! $auth.check}">
        <jsp:forward ..... />
    </c:if>
    Should I be approaching this problem from another direction?
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  4. #4
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Jstl / Mvc

    In short, <jsp:useBean> sucks for actually doing anything. The intention of it might have been to actually create the beans in Servlets and do all logic there, and then in JSP pages only retrieve the results.
    Or perhaps they really expected the getters to do logic. In which case, shame on them.

    Here's my advice: forget useBean. Use EL to retrieve properties, and use custom tags when you actually want to do something.

    Ah, custom tags. Now that's some good stuff.



    Checking authentication, on the other hand, is IMO a task for a filter. Using a filter here means that you don't have to put the check in every single page you create.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  5. #5

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    Filters?

    How do filters work and how would I use them?
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  6. #6

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    I think this tells me most of what I need to know:

    http://java.sun.com/products/servlet/Filters.html

    Looks awsome.
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  7. #7
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Jstl / Mvc

    You implement the javax.servlet.Filter interface with a class. Best to create an abstract DefaultFilter that contains no-ops for all three methods and derive from that - most filters only care about one or two.
    Note that the no-op implementation for doFilter is:
    Code:
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException
    {
      chain.doFilter(request, response);
    }
    In overriding this method, you can do anything you want with the request and response - change parameters, set attributes, even wrap up the whole objects with classes derived from ServletRequestWrapper (or HttpServletRequestWrapper) and the Response equivalent and completely falsify all information, or capture the entire response and do something to it (e.g. XSLT transformation if the response is XML). You can also choose not to call chain.doFilter() and thus prevent the original target from handling the request. (E.g. on authentication failure.)

    After you've written the class, you need to map it. That works pretty much the same way as servlets. Add this to the web.xml:
    Code:
    <filter>
      <filter-name>identifier</filter-name>
      <filter-class>fqcn implements Filter</filter-class>
      <init-param>
        <!-- parameter that is available in Filter.init() -->
      </init-param>
    </filter>
    
    <filter-mapping>
      <filter-name>identifier</filter-name>
      <url-pattern>/*</url-pattern><!-- Apply to all requests. -->
      <!-- Optional: -->
      <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    The dispatcher element specifies on which types of dispatching the filter should be invoked. The default is REQUEST, which means normal, direct requests to the resource. Additional values are FORWARD and INCLUDE, which apply to calls through the RequestDispatcher.forward() and RequestDispatcher.include() methods, respectively. You can use any combination of these three methods; put each you want to handle into its own dispatcher element.

    Things I've used filters for recently:
    1) Parsing a part of the request path and making it known as a request attribute.
    2) Retrieving info from a DB based on that part.
    3) Ensuring that an authentication token is passed in the request.
    4) Capturing the servlet context and making it available globally.
    5) Instantiating a bean that was used everywhere from cookie or session data.
    6) Changing the request URL information for requests dispatched through RequestDispatcher.include(). (This method does not change the URL to the called page - the called page knows that the request was originally to the outer page. I needed the inner page to believe it was directly called, though.)
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  8. #8

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    Quote Originally Posted by CornedBee
    Code:
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    java.sql.Connection c = (java.sql.Connection)ctx.lookup("java:comp/env/jdbc/db");
    When I attempt this after creating the data source in the context XML I get a casting error:
    Code:
    type Exception report
    
    message
    
    description The server encountered an internal error () that prevented it from fulfilling this request.
    
    exception
    
    java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource
    	com.codedv.sloughcollectiblecoins.CommonFilter.doFilter(CommonFilter.java:40)
    
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.20 logs.
    I have tried changing the type attribute in the resource element to java.sql.Connection. This prevents the exception but creates a java.naming.NamingException. Is there something I'm missing here. I want to get the connection inside a filter:
    Code:
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
        {
            try 
            {
             
                javax.naming.InitialContext context = new javax.naming.InitialContext();
    
                Connection con = (Connection) context.lookup("java:comp/env/jdbc/db");
                
                request.setAttribute("dbConnection", con);
                
            }
            catch(javax.naming.NamingException e)
            {
                response.getWriter().write(e.toString());
           
            }
            
            chain.doFilter(request, response);
    
        
        }
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  9. #9

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    Would there be an issue with returning the connection to the conenction pool if it is retrieved using a filter?
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  10. #10
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Jstl / Mvc

    Sorry, the result is not a Connection but a javax.sql.DataSource.

    Just be sure to always close() the connection.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  11. #11

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Jstl / Mvc

    Is the some kind of destroy function or destructor function I can use to dispose of the connection at the end of every request without having to make a call on every page?
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  12. #12
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Jstl / Mvc

    You dispose of the connection the moment you've done your DB queries. There is no per-request dispose function, and you'd only get into multithreading troubles anyway.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  13. #13

    Thread Starter
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: [RESOLVED] Jstl / Mvc

    Thanks for all the help. This is the somewhat incomplete application I created. Had I had more than 3 days to make it, it would look a lot better:

    http://jsp.codedv.com/SloughCollectableCoins/index.jspx
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width