Hot questions for Using GlassFish in jsp

Question:

I'm looking for help to get all my layers in the stack to UTF-8 encoding.

I found this nice article:

http://www.javapractices.com/topic/TopicAction.do?Id=206

describing the 3 places I need to worry about encoding. Since my (1) Oracle database is currently set to UTF-8, that leaves the (2) browser and (3) server to worry about.

I also found this detailed article

http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html#JSPServletRequest

which I'm trying to follow below, but with some newbie questions about implementation.

To address the browser, I've made sure to include the following at the top of each JSP page:

<%@page pageEncoding="UTF-8"%> 

(For reference, see here).

To address the server, I made sure to include the following line in the Java servlet and JSP pages before issuing a request.getParameter() or request.getAttribute() statement:

request.setCharacterEncoding("UTF-8");

Since I'm using GlassFish 3.1.2, I understand it does not use UTF-8 by default, so I need to set it manually somehow.

I've seen a lot of websites talking about a file named glassfish-web.xml. Is this part of the normal glassfish install? I don't know where to find it. I've been using the web.xml file in my WEB-INF folder for my web application. Could someone help me figure out whether I need to modify this web.xml file, or do I need to locate or create a new file named glassfish-web.xml, to configure encoding for glassfish?

My web.xml file starts with:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app> 
...

For the JSP/servlet request, I include the following line in the web.xml file

<parameter-encoding default-charset="UTF-8"/>

Is this OK to put in the web.xml file? Or, does it need to go in some glassfish-web.xml file?

For the JSP/servlet response, I put the following in my web.xml file (see accepted answer here):

<jsp-config>
   <jsp-property-group>
       <url-pattern>*.jsp</url-pattern>
       <page-encoding>UTF-8</page-encoding>
   </jsp-property-group> 
</jsp-config>

I'm assuming these lines just insert between <web-app> and </web-app>. But, let me know if they should instead go inside some other descriptor (such as <glassfish-web-app> and </glassfish-web-app>)?

I also put the following in the JSP <head> section:

<meta http-equiv="content-type" content="text/html; charset=utf-8">

Useful references:

How to get rid of WARNING: PWC4011: Unable to set request character encoding to UTF-8

https://stackoverflow.com/tags/servlet-filters/info

https://wikis.oracle.com/display/GlassFish/FaqHttpRequestParameterEncoding


Answer:

The glassfish-web.xml is a file you can create in your WEB-INF folder. For Glassfish 3.x it has to look similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <jsp-config>
    </jsp-config>
    <parameter-encoding default-charset="UTF-8" />
</glassfish-web-app>

And you are right, the parameter-encoding setting has to be in this file and not in the web.xml :)

See also:

  • glassfish-web.xml vs sun-web.xml vs web.xml
  • Glassfish encoding

Question:

I have the same problem as this unanswered question from almost 2 years ago.

<%@ taglib uri="/WEB-INF/tlds/myLib" prefix="myLib" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

I have these two lines in my JSP. Originally I was only using the JSTL core library and everything worked well. As soon as I add a custom library, I get an exception like this:

java.lang.NullPointerException
at org.apache.jasper.compiler.TagLibraryInfoImpl.toString(TagLibraryInfoImpl.java:129)
at java.lang.String.valueOf(String.java:2979)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at java.util.concurrent.ConcurrentHashMap.toString(ConcurrentHashMap.java:1321)
at org.apache.taglibs.standard.tag.common.core.OutSupport.out(OutSupport.java:211)
at org.apache.taglibs.standard.tag.common.core.OutSupport.doStartTag(OutSupport.java:132)
at org.apache.jsp.FormTest_jsp._jspx_meth_c_out_3(FormTest_jsp.java:306)
at org.apache.jsp.FormTest_jsp._jspx_meth_c_forEach_1(FormTest_jsp.java:256)
at org.apache.jsp.FormTest_jsp._jspService(FormTest_jsp.java:83)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:875)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:575)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:546)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
at form.FormServlet.processRequest(FormServlet.java:60)
at form.FormServlet.doPost(FormServlet.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)

If I remove either of the two taglib directives, everything works correctly.

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>mylib</short-name>
  <uri>/WEB-INF/tlds/myLib</uri>
  <tag>
    <name>beaner</name>
    <tagclass>form.BeanTagHandler</tagclass>
    <bodycontent>empty</bodycontent>
  </tag>
</taglib>

tld is very minimal to try to get this working.

Would appreciate it if anyone can offer some insight as to what the problem may be. Thanks.

EDIT: Found the source of the problem.

<table>
<tr>
<th>Attribute Name</th>
<th>Attribute Value</th></tr>
<c:forEach var="a" items="${applicationScope}">
<tr>
<td> <c:out value="${a.key}"/> </td>
<td> <c:out value="${a.value}" /> </td>
</tr>
</c:forEach>
</table>

The problematic part is the c:out for ${a.value}. The jsp works fine without it. For some reason it works fine when I don't import my custom tag library. Any ideas as to why trying to c:out the values of the applicationScope would cause problems?


Answer:

Alright I figured out the problem. There is an attribute called com.sun.jsp.taglibraryCache in applicationScope that is Class ConcurrentHashMap. It seems that importing another tag library causes the toString method of the class to give a NullPointerException. I fixed my problem by using c:catch to catch the exception.

Question:

I am using Glassfish 4.0 with Eclipse Luna 4.4.0 and have downloaded the latest struts2 libraries. I have added all the struts2 jars to the project, just to be sure. I have created a Dynamic Web Project. This is my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>Struts2Starter</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>org.demian.javabrains.action</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

This is my struts.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="basicstruts2" extends="struts-default">
        <action name="getTutorial" class="org.demian.javabrains.action.TutorialAction" method="execute">
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

This is my TutorialAction.java:

package org.demian.javabrains.action;

import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;

public class TutorialAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    public String execute() throws Exception {
        System.out.println("Hello from execute!");
        Date d = new Date();
        long milliseconds = d.getTime();
        if (milliseconds % 2 == 0)
            return SUCCESS;
        else
            return ERROR;
    }
}

The other 2 pages I created are simple .jsp pages: success.jsp and error.jsp, both in the home directory. If I input this url: http://localhost:8080/Struts2Starter/success.jsp, I get the success page so it means that Glassfish is working but if I input this url: http://localhost:8080/Struts2Starter/getTutorial.action I always get http error 404. I followed the instructions on this page: struts2 documentation. Can anyone please tell me what I'm doing wrong?

EDIT

I tried debugging the application with struts2-config-browser-plugin by inserting this link

<a href="<s:url action="index" namespace="config-browser" />">Launch the configuration browser</a>

into my success.jsp page like it says here:http://struts.apache.org/release/2.2.x/docs/debugging-struts.html . When I click on the link it gives another 404 error. I don't understand. It's like Struts2 isn't working at all. Here is the log when I start the server: https://dl.dropboxusercontent.com/u/27349592/glassfish_server_startup.txt

EDIT1

I installed Tomcat 8.0.11 and here's the error message I get when I start the server: https://dl.dropboxusercontent.com/u/27349592/tomcat8_server_startup.txt


Answer:

I finally managed to make it work! First thing I did was to remove all the jars I included and add only the ones I needed. Here are the jars that I included: https://dl.dropboxusercontent.com/u/27349592/2014-09-05%2022_36_58-Preferences%20%28Filtered%29.png

After this, I configured the libraries in the Properties -> Deployment Assembly of the project: https://dl.dropboxusercontent.com/u/27349592/2014-09-05%2022_37_29-Properties%20for%20Struts2Tutorial.png

My web.xml file is:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>Struts2Tutorial</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

My struts.xml file is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="basicstruts2" extends="struts-default">
        <action name="getTutorial" class="org.demian.javabrains.action.TutorialAction" method="execute">
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

I still don't know exactly what was the problem but I guess that it may be because of the dependencies in the struts2 libraries.

Question:

I am trying to use JSTL in a page. I included it with no error or warning, but when I run the page on a glassfish server only simple html is showing and none of JSTL tags or code related to it is performed or displayed. How do i fix this?

Page related code:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
    <c:set var="errMsg" value="Sample Error Message" />
    <c:if test="${errMsg != null}">
        <span style="color: red;"> <c:out value="${errMsg}"></c:out>
        </span>
    </c:if>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SampleApp</groupId>
    <artifactId>SampleApp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Sample Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.9-rc</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>SampleApp</finalName>
    </build>
</project>

Answer:

It's EL which is being ignored.

You need to add this to your jsp declaration :

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>

This isELIgnored="false" will enable EL Language and you will see your message.

Question:


Answer:

The login.jsp is placed in WebContent/WEB-INF folder of my project.

Could you please put login.jsp in WebContent folder of your project in eclipse then clean the project and try the URL: http://localhost:53809/web-college-administration/login.jsp again?

Question:

This is my first attempt at HTML interaction with Java. I Understand that I need to use a Java servlet and an HTML index. I am doing this over a local GlassFish 4 server.

What I would like is a simple user input to my Java EE (Eclipse v4.5 (Mars)) project. I am not positive how to do this. I have watched tutorials and read multiple guides, but none explicitly explain the interaction. (This is why I know I need a servlet.)

So here is my setup thus far, and I have no clue where to go from here.

Java servelet

package servletPackage1;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetUserInputServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException{
        String userInput = req.getParameter("UserInput");

    }
}

Again I am not positive that this is even set up correctly, but how do I get the input from my index file?

Here is my index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DSS</title>
</head>
<body>
<form action="DATASEARCH/GetUserInputServlet" method="get">
  Search for details:<br>
  <input type="text" name="text/plain" value="Enter search criteria">
  <br>

  <br><br>
  <input type="submit" class="btn-success btn-md" style="margin-right:5px" id="T1" value="Submit">
</form>

</html>

I have found out that I need to have my deployment descriptor (web.xml file). I have created one, but I am still receiving a 404 upon submission. The XML is below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>DATASEARCH</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>Index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

This will be connected to a much larger project (which is finished and works perfectly) to search across a database. I only need to get the user input across a web application. NEW TO HTML also.

For an answer I am looking for:

  1. What is wrong with what I have done? (I am getting a 404 error when I click my submit button)

  2. How do I get the input into a Java variable casted as a string?

For now I will only be using ONE servlet as I only need access to a single user input from a single page. I do not understand this servlet mapping as well as I should, but I can not find information on how to map. Any help would be appreciated.


Answer:

You need to add servlet mapping in your deployment descriptor (web.xml)

    <servlet-mapping>
        <servlet-name>GetUserInputServlet</servlet-name>
        <url-pattern>GetUserInputServlet</url-pattern>
   </servlet-mapping>

This means that whenever you go to URL GetUserInputServlet, the control will be transferred to servlet named GetUserInputServlet.

Question:

I am getting a NullPointerException in this code:

update.jsp:

<%@ page language="java" import="com.solly.CaliforniaWaterDataVisualizationJSPCode" %>
<title>Updating database</title>
<a href="index.html">Return to home page</a>
<br>
Updating database...<br>
<pre>
<%
CaliforniaWaterDataVisualizationJSPCode.update(request, out);
%>
</pre>

CaliforniaWaterDataVisualizationJSPCode.java:

package com.solly;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import com.solly.parser.PSVParser;

public abstract class CaliforniaWaterDataVisualizationJSPCode {
    static public void update(HttpServletRequest request, JspWriter out) throws IOException, SQLException, ClassNotFoundException {
        try(Connection dbConnection = DriverManager.getConnection("jdbc:sqlite:California_Water_Data.db")) { 
            if(request.getParameter("caldata-surface-toxic") != null) {
                URL url = new URL("https://data.ca.gov/sites/default/files/Surface_Water_Toxicity_2001_2015.txt");
                URLConnection urlConnection = url.openConnection();
                try(InputStream inputStream = urlConnection.getInputStream()) {
                    byte[] data = new byte[urlConnection.getContentLength()];
                    inputStream.read(data);
                    String content = new String(data);
                    PSVParser.parseFile(content);
                }
            }
            out.println("Finished retrieving data from data.ca.gov's 2001 to 2015 surface water toxicity record<br>");
        } catch(Throwable e) {
            out.println("Error: <br>" + e + "<br><br>" + "Stack trace: <br>");
            for(StackTraceElement element : e.getStackTrace()) {
                out.println(element + "<br>");
            }
            out.println("<br>Cause: <br>" + e.getCause());
        }
    }
}

I am using Java EE 7 update 21. I am using SQLite JDBC 3.7.2's compiled and source JARs (sqlite-jdbc-3.7.2.jar and sqlite-jdbc-3.7.2-sources.jar) from java2s.com running on GlassFish 4.1.1 build 1. You can access my code on GitHub at github.com/dhDZsG9QfQK3VTiF5KOs/California_Water_Data_Visualization. I have created a GitHub issue about this at github.com/dhDZsG9QfQK3VTiF5KOs/California_Water_Data_Visualization/issues/1.

Stack trace:

org.sqlite.NestedDB$CausedSQLException.fillInStackTrace(NestedDB.java:649)
java.lang.Throwable.(Throwable.java:250)
java.lang.Exception.(Exception.java:54)
java.sql.SQLException.(SQLException.java:140)
org.sqlite.NestedDB$CausedSQLException.(NestedDB.java:626)
org.sqlite.NestedDB._open(NestedDB.java:63)
org.sqlite.DB.open(DB.java:86)
org.sqlite.Conn.open(Conn.java:140)
org.sqlite.Conn.(Conn.java:57)
org.sqlite.JDBC.createConnection(JDBC.java:77)
org.sqlite.JDBC.connect(JDBC.java:64)
java.sql.DriverManager.getConnection(DriverManager.java:579)
java.sql.DriverManager.getConnection(DriverManager.java:243)
com.solly.CaliforniaWaterDataVisualizationJSPCode.update(CaliforniaWaterDataVisualizationJSPCode.java:18)
org.apache.jsp.update_jsp._jspService(update_jsp.java:53)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:323)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:321)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:536)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:356)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:214)
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1676)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
java.lang.Thread.run(Thread.java:722)

Answer:

I solved it by adding DriverManager.registerDriver(new JDBC()); before the try block. What inspired me was the new error message (after restarting the server): "java.sql.SQLException: No suitable driver found for jdbc:sqlite:California_Water_Data.db".

Question:

Let me preface this by saying this: I am an absolute beginner regarding JSP. I'm still trying to understand the fundamentals while also get my work done in a timely manner without asking the instructor for help (thanks to them never returning emails when me and some other classmates have reached out regarding the work and things such as missing information or links).

I have been tasked to make a program in JSP that generates random addition problems. The user is able to input the answer they think is write and, after submitting them, will be told by the program which they've got right and wrong. I've written a program thus far that, while it runs, it doesn't actually display anything in the browser. It just constantly says "waiting for localhost'. Here is what I've made thus far:

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <%@ page import = "java.util.*"%>

 <>
<!DOCTYPE html>
<html>
    <head>
        <title>Addition Quiz</title>
    </head>
    <body>
        <%
            int a, b, answer;

            Random rand = new Random();
             a = rand.nextInt(1000); 
             b = rand.nextInt(1000);

             %>

             <form>
             <%= a %> + <%= b %> =
             <input type="number" value="answer" name="answer"><br><br>
             <input type="submit" value="Submit">
             </form>

             <%

                 request.getParameter("answer");

                 answer = a + b;

                 if (answer==a+b) {

                     out.print("Correct");

                 } else if (answer!=(a+b)) {

                     out.print("Incorrect");
                 }
%>

    </body>
</html>

What am I doing wrong here and, in your opinion, how should I go about it? I'm using NetBeans and GlassFish.

EDIT: Added to the program as per the suggestion of Swati. While it now outputs, the page will automatically say correct and whenever I submit a number to answer the equation the page just sorta refreshes to a new equation.


Answer:

As you submit it is reloading the page hence new random numbers are generating.Please find the below code. index.html

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>

<>
<!DOCTYPE html>
<html>
<head>
<title>Addition Quiz</title>
</head>
<body>
    <%
            int a, b, answer;

            Random rand = new Random();
             a = rand.nextInt(1000); 
             b = rand.nextInt(1000);

             %>

    <form action="result.jsp">
        <%= a %>
        +
        <%= b %>
        <% 
              request.setAttribute("a", a);
              request.setAttribute("b", b);
              %>
        = <input type="number" value="answer" name="answer"><br>
        <input type="hidden" name="a" value="<%=a%>">
        <input type="hidden" name="b" value="<%=b%>">
        <br><input type="submit" value="Submit">
    </form>


</body>
</html>

result.html

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h1>answer is::<%=Integer.parseInt(request.getParameter("answer")) %></h1>
    <h1>a+b is::<%=Integer.parseInt(request.getParameter("a"))+Integer.parseInt(request.getParameter("b")) %></h1>
    <h1>RESULT IS <%= (Integer.parseInt(request.getParameter("answer")) == (Integer.parseInt(request.getParameter("a"))+Integer.parseInt(request.getParameter("b"))) )?"Correct":"InCorrect"%></h1>
</body>
</html>

Question:

I'm trying to use Sitemesh 2.4.2 to decorate some JSPs with a navbar, and also to extract my CSS references into this decorator. However, I can't make it work: depending on how I set up the pattern in my decorators.xml, I'm either getting only the base JSP with no decorator, or the decorator (this is, the content of the <head> tag, and the <navbar> I'm adding at the beginning of my <body> tag) with no content from the base JSP. My application is using Glassfish 4 as the application server, hence using Jersey 2. Since I'm using JSPs, I'm using Jersey as a filter.

This is my web.xml (I'm not entirely sure if I need this FORWARD dispatcher)

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <filter>
    <filter-name>SiteMeshFilter</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SiteMeshFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
  </filter-mapping>

  <filter>
    <filter-name>jersey</filter-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
    <init-param>
      <param-name>jersey.config.servlet.filter.forwardOn404</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.xxx.jersey2.config.CustomResourceConfig</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>jersey</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

My decorators.xml

<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/WEB-INF/decorators">
<decorator name="main" page="my_navbar.jsp">
  <!--<pattern>/jsp/*</pattern>-->
  <pattern>/*</pattern>
</decorator>
</decorators>

Here, if I change the pattern to <pattern>/jsp/*</pattern>, then the decorator wouldn't be included at all — I would get just the base JSP. By setting the pattern to <pattern>/*</pattern>, I'm getting only the decorator, this is, I'm getting only the content of my_navbar.jsp. Also, Sitemesh's tags on it, like <decorator:body />, won't be rendered at all, and they would appear in the resulting webpage source code that can be seen from the browser.

This is the JSP that's going to be decorated, my_navbar.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sandbox application</title>
    <link rel="stylesheet" href="../../js/jquery-1.12.4.min.js">
    <link rel="stylesheet" href="../../css/bootstrap.min.css">
    <link rel="stylesheet" href="../../js/bootstrap.min.js">
    <decorator:head />
</head>
<body>

<nav class="navbar navbar-light bg-faded">
    <ul class="nav navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="/sample-jersey2/">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="/sample-jersey2/movies/list/">Movies</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="/sample-jersey2/genres/list/">Genres</a>
        </li>
    </ul>
</nav>

<decorator:body />

</body>
</html>

And finally, one of the JSPs I'm trying to get decorated with my navbar and styles

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title></title>
</head>
<body>

<h2>Listing Movies</h2>
    <table class="table table-striped">
        <tr>
            <th>Name</th>
            <th>Starring</th>
            <th>Genre</th>
        </tr>
        <c:forEach var="item" items="${it.movies}">
            <tr>
                <td>${item.name}</td>
                <td>${item.starring}</td>
                <td>${item.genre}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Any ideas on this would be greatly appreciated. Regards


Answer:

I was missing this line in my my_navbar.jsp file:

<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator" %>

Now it works properly.

Question:

I have Netbeans 8.0.2 installed on Ubuntu 15.04 which includes the GlassFish 4.1 EE Container.

For some reason, after ensuring my resolv.conf and hosts files were set-up properly, accessing dynamic content, such as a servlet that pulls data from a SQL database, is terribly slow.

However, accessing static JSP pages returns in less than 1ms as it should.

Pinging the server on 127.0.0.1 or localhost returns in 0.038ms or less, which is to be expected, so I don't think the DNS resolving issues common with Linux and localhost are to blame here.

For kicks, I downloaded the GlassFish 4.1 server off their website and set-up NetBeans to deploy there, and I got the same results. In addition I also tried manually deploying my WAR files, and that also resulted in terribly slow response times from dynamic content / servlets.

What gets me is that with the exact same set-up and configurations, I do not have this issues on Windows.

So in summary:

  • Static content resolves and responds in less than 1ms.
  • Dynamic content through servlets is terribly slow, up to 5 minutes.

I did look and see if it was my code. And no, it is not. It runs perfectly fine on Windows and Windows Server. It even runs fine when the server is on CentOS and pointing outwards, i.e. you would browse to a URL and not through the localhost.


To clarify, this problem occurs even on servlets that do not access any external resources, such as a servlet that only adds a few lines of HTML, or forwards the request to a static JSP page.


Answer:

Well,

After some extensive digging and profiling, I found the solution:

I had a filter that would authenticate users, and set a cookie that changes for every request (prevents CSRF) but used a Java Utils SecureRandom to inject a secure random bit of info into a MD5 hashing algorithm along with some other goodies to spit out a decently secure, one-time use cookie.

Apparently, the version of CentOS my production server is using already includes the haveged daemon which keeps the /dev/random entropy topped up.

The issue is that SecureRandom on Linux requests the /dev/random and is blocking. When there isn't enough entropy, it can wait up to 25 seconds before returning.

Solution was to of course: install the haveged daemon. Problem solved.

Question:

I'm attempting to connect a Java web application to a ms access database. I get a java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver when running any page of the application that takes data from the database over the GlassFish server.

Within the same application I have a 'test app' that successfully takes all data from the database and prints to the console. I'm trying to run the same method from the underlying database class to retrieve the data from a .jsp.

I've checked that the JDK has the necessary class.

I'm using

Netbeans 8.0.2 (64 bit)

JDK 7.0.0_67 (64 bit)

MS Access 2010 (64 bit)

GlassFish server 4.1

Upgrading to JDK 8 is not an option, this app is for a University project that has to run on the Unis computers which use JDK 7.

Exception

Warning:   StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1783)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1633)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:259)
    at plymoutheventsaccess.DatabaseConnector.createConnection(DatabaseConnector.java:42)
    at org.apache.jsp.eventList_jsp._jspService(eventList_jsp.java:62)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

Any help much appreciated.

Tony


Answer:

I followed the suggested made by commenters on the question but none worked. In summary I tried:

  • Setting JAVA_HOME
  • Editing Glassfish BAT files
  • Changing where the Java syslink pointed
  • Including JDBC within the deployment package

To solve my issue I removed JDK 8 from my system completely. After this there was no further configuration needed, worked straight away.