Hot questions for Using GlassFish in servlets

Question:

I am deploying a war file to glassfish and would like to know if it is possible to have a file that can have properties stored in them that can be accessed within my web methods. The catch is I would like to change the file as business requests change wihtout having to recompile. I could store it in the DB or have it as system properties on glassfish itself but would like to know if the file way is possible.

I have read these but all seems like you would have to recompile?:

Load properties file in Servlet/JSP

loading properties file in init() of servlet without using context-param tag in web.xml


Answer:

Sure you can. You can load the properties at startup and note the modification time for the file; then you can reload the properties again when the modification time has changed, i.e. when someone has edited it. The check and reload can be done using a background thread or on access, but take care to handle synchronization as all simultaneous requests will compete with each other.

I'd keep the file outside of Glassfish and point to it using a system property or context parameter, but you can also edit the properties file where Glassfish has extracted the WAR file.

Question:

I catch

org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac. A full JDK (not just JRE) is required

I've installed JDK and set JAVA_HOME. Also I've added this statement to senv.conf:

AS_JAVA="C:\Program Files (x86)\Java\jdk1.7.0_67"

But nothing changes. What do?


Answer:

@Tony, uninstall jdk1.70_67, and install jdk1.70_25 or jdk1.70_45 , there are problems with jdk1.70_60 and upwards.

Question:

I have updated one of my tables to include the column canttouchthis using the MySQL Workbench. From the MySQL Workbench there is no problem writing sql against the column canttouchthis. But, in my code I get the following error on any instance of said column, but the remained of the columns work just fine, such as groups.id

Unknown column 'groups.canttouchthis' in 'field list'

Even a simple select statement like the following doesn't work:

try {
    String sql = "SELECT  groups.canttouchthis FROM  groups";
    PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        data.addProperty("got_data", rs.getLong(groups.canttouchthis));
    }
} catch (SQLException ex) {
    StackTrace.print(ex);
}

I have tried reseting my Java Servlet Container server to no avail


Answer:

I realized that I was passing the wrong database connection to this point. Thanks for your vigilance, I would delete this question if I could.

Question:


Answer:

First Question -

All the imports of the Servlet-API can't be resolved. But why? I did create a Java-Enterprise-Application-Project and assigned the Webproject onlineshop-war to the App. And the Glassfish is assigned to the Java-Enterprise-Application-Project and on the Glassfish-Server is the Servlet-API recorded, isn't it?

I am using eclipse with combination of Java-8 and Tomcat 8.5 web container, by watching your question, I simply created a new dynamic web project in eclipse, later created two html files index.html and register.html along with Servlet class RegisterServlet in the same package you defined.

After doing all work, I simply first started and stopped my web container server, later make a Right click on the project name, Go to menu Run As > Run on Server > Choose an existing server, there I choose the Tomcat 8.5 Server at localhost > Remove all other projects from list Configured instead the current one and pressed the Finish.

Earlier I have selected I have selected the default browser by steps option Window(Menu)>Web Browser>Chrome.

No such web.xml configuration file is there in directory WebContent/WEB-INF/ inside my project.

Thus the Tomcat 8.5 server will start and show the index.html page in chrome new tab, there Optionshop page appeared and I chose the Registrieren link, then redirected to register.html, there I inserted email id and password later pressed Enter and the servlet mapping viewed me my email id and password in fresh page, that's it.

Second Question -

Why can't he find the Servlet after clicking on submit after typing in the EMail and the Password on the register-HTML? Has it something to do with question 1?

I changed the @WebServlet to /RegisterServlet and in register.html I replaced the form starting tag to

<form name="register" method="POST" action="RegisterServlet">

also in Servlet class the method doGet(HttpServletRequest request, HttpServletResponse response) was missing, so I create one and my Servlet class is as follows:

package de.java2enterprise.onlineshop;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public RegisterServlet() { }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        final String email = request.getParameter("email");
        final String password = request.getParameter("password");

        final PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<body>");
        out.println("<br> Ihre Eingaben");
        out.println("<br> EMail: " + email);
        out.println("<br> EMail: " + password);
        out.println("</body>");
        out.println("</html>");

        out.close();
    }
}

Hope this will help you, thanks.

Question:


Answer:

1. Setting up pom.xml:

In Netbeans IDE create a new maven project. Change the packaging to war in pom.xml.

<packaging>war</packaging>

Add this dependency to dependencies in pom.xml. This will add the necessary servlet classes to classpath.

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

Set up maven-war-plugin version. With version 3.0.0 or higher you don't have to create ServletRoot/WEB-INF/web.xml. If you skip this step, the project won't compile without configuring web.xml. I called "ServletRoot" this path: mavenproject/src/main/webapp A good explanation about package directory structure can be found here at 3.1: package structure

<build>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.0.0</version>
        </plugin>
    </plugins>
</build>

2. Put index.html Create index.html into mavenproject/src/main/webapp and copy this codesnippet there. Take note that the form tag's action attribute's value must match your servlet's WebServlet annotation's value. In this case it will be this:

@WebServlet("/postexample")

index.html:

<html>
    <body>
        <form action = "postexample" method = "POST">
            First Name: <input type = "text" name = "first_name">
            <br />
            Last Name: <input type = "text" name = "last_name" />
            <input type = "submit" value = "Submit" />
        </form>
    </body>
</html>

3. Create a new class in your package. Don't use default package.

I named it POSTExample. Here is the code without package declaration:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

// Extend HttpServlet class
@WebServlet("/postexample")
public class POSTExample extends HttpServlet {

    // Method to handle GET method request.
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse         response)
    throws ServletException, IOException {

        // Set response content type
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        String title = "Using GET Method to Read Form Data";
        String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " +
            "transitional//en\">\n";

        out.println(docType +
            "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor = \"#f0f0f0\">\n" +
                    "<h1 align = \"center\">" + title + "</h1>\n" +
                    "<ul>\n" +
                        "  <li><b>First Name</b>: "
                        + request.getParameter("first_name") + "\n" +
                        "  <li><b>Last Name</b>: "
                        + request.getParameter("last_name") + "\n" +
                    "</ul>\n" +
                "</body>\n" +
            "</html>"
        );
    }
    // Method to handle POST method request.
    @Override
   public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        doGet(request, response);
    }
}

4. Build maven project In Netbeans IDE you have a button for it. Neteans can also deploy it automatically to glassfish, but I haven't tried that. So I will show you how to deploy it manually with glassfish manager. You can build it in commandline with.

mvn clean package

5. Deploy Open commandline and use this command. It will start glassfish server, and will log a lot.

asadmin start-domain --verbose 

Open a browser and enter this URI. I'm assuming you are using the default settings for glassfish. Default Ports, etc...

http://localhost:4848/

Under "Common Tasks" you can find "Applications". Click on it. Then click Deploy. It's above the listed apps if there are any. Now you must enter the location of your created war file. Or you can drag n' drop. It's location is mavenproject/target/yourwarfile.war

Before clicking OK in the glassfish manager, give a simple a text for "context root" like "myservlet". You must remember this. If you did everything well, you can run the example in your browser by using this link: http://localhost:8080/myservlet

In this case "myservlet" is the context root you set in glassfish manager.

Question:

I'm developing an Identity Provider using OpenSAML API.

I have created a java application to test OpenSAML API which was a success.

The problem is now I'm trying to use that java Application in Servlet using glassfish and I'm loosing my mind right now.

Hear me out: before you can start using OpenSAML you have to call it's bootstrap to initiate it's components, one of those components is org.apache.xml.security.Init

so i added xmlsec.jar into libraries but every time I run the WebApplication it keeps on getting an exception:

"java.lang.NoClassDefFoundError: Could not initialize class org.apache.xml.security.Init"

the confusing part is if I remove the xmlsec.jar from libs, it still knows the

import "org.apache.xml.security.Init" 

but when I delete that and try to rewrite the same:

import "org.apache.xml.security.Init"

now it fails because now org.apache doesn't have xml.security in it.

any idea guys?

PS: I'm using these: - NetBeans IDE - Glassfish 4.1.1 - Java EE 7 - JDK 1.8

glassfish output:

Warning:   StandardWrapperValve[LoginServlet]: Servlet.service() for servlet LoginServlet threw exception
java.lang.NoClassDefFoundError: Could not initialize class org.apache.xml.security.Init
at org.opensaml.DefaultBootstrap.initializeXMLSecurity(DefaultBootstrap.java:195)
at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:98)
at opensamltest1.SAMLHelper.printSAMLObject(SAMLHelper.java:180)
at LoginServlet.processRequest(LoginServlet.java:53)
at LoginServlet.doPost(LoginServlet.java:100)
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:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
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:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
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:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
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:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)

Answer:

This could be due to a conflict between classes provided by JVM or your Container host, and those in the WAR file. If the class is duplicated in both places it can play all sorts of havoc with your startup.

Question:

Stupid problem, but I can't solve it. Java server - glassfish 4. I have in WEB-INF tiles**.xml files. For example I have tiles.xml, tiles2.xml (I can have more in future) and I need to get them. I use the following code

Collection<ApplicationResource> webINFSet = 
applicationContext.getResources("/WEB-INF/tiles*.xml")

However it this code returns only one.

System.out.println("Size:"+webINFSet.size());//out Size:1

Where is my mistake?


Answer:

Looking at org.apache.tiles.request.servlet.ServletApplicationContext at GrepCode, which I assume is the implemenation you get, it seems as if the error (if there is any) is not on your side. The implementation looks like this:

public Collection<ApplicationResource> getResources(String path) {
  ArrayList<ApplicationResource> resources = new ArrayList<ApplicationResource>();
  resources.add(getResource(path));
  return resources;
}

Depending on what you need, you could try and look for the files on the classpath. There is, however, no standard way of searching for resources by name pattern, but you could have a look here: Get a list of resources from classpath directory