This question already has answers here:
#WebServlet fails in Netbeans 11.0 with java.lang.RuntimeException: com.example.NewServlet.<init>(NewServlet.java:1)
(2 answers)
Closed 1 year ago.
I have created a simple web application in Netbeans 11 on JDK1.8 and running Glassfish 5.1.0 with just one servlet that redirects to a simple JSP page.
On building and running the application I get the above error when I access http://localhost:8080/MyNews/news. Stacktrace here
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
Loading application [MyNews] at [/MyNews]|#]
Loading application MyNews done in 161 ms|#]
GlassFish Server Open Source Edition 5.1.0 (default-private) startup time : Felix (3,830ms), startup services(6,567ms), total(10,397ms)|#]
visiting unvisited references|#]
Grizzly Framework 2.4.4 started in: 62ms - bound to [/0.0.0.0:7676]|#]
Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl#77ee25f1 as OSGi service registration: org.apache.felix.framework.ServiceRegistrationImpl#6dd93a21.|#]
Created HTTP listener http-listener-2 on host/port 0.0.0.0:8181|#]
JMXStartupService has started JMXConnector on JMXService URL service:jmx:rmi://DESKTOP-QQAVGAD:8686/jndi/rmi://DESKTOP-QQAVGAD:8686/jmxrmi|#]
Grizzly Framework 2.4.4 started in: 13ms - bound to [/0.0.0.0:8181]|#]
Created HTTP listener http-listener-1 on host/port 0.0.0.0:8080|#]
Grizzly Framework 2.4.4 started in: 12ms - bound to [/0.0.0.0:8080]|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
visiting unvisited references|#]
Loading application [MyNews] at [/MyNews]|#]
MyNews was successfully deployed in 404 milliseconds.|#]
Initializing Mojarra 2.3.9 for context ''|#]
Loading application [__admingui] at [/]|#]
Loading application __admingui done in 2,712 ms|#]
Context path from ServletContext: differs from path from bundle: /|#]
WebModule[/MyNews] ServletContext.log():Marking servlet ViewNews as unavailable|#]
StandardWrapperValve[ViewNews]: Allocate exception for servlet ViewNews
java.lang.RuntimeException:
at view.ViewNews.<init>(ViewNews.java:1)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:320)
at com.sun.enterprise.web.WebContainer.createServletInstance(WebContainer.java:725)
at com.sun.enterprise.web.WebModule.createServletInstance(WebModule.java:1955)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1262)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:1069)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:119)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:611)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:550)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:75)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:114)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:199)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
|#]
Here is the servlet
package view;
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;
/**
*
* #author korla
*/
#WebServlet(name = "ViewNews", urlPatterns = {"/news"})
public class ViewNews extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("news.jsp");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here is the JSP
<%--
Document : news
Created on : 03-May-2020, 4:54:15 PM
Author : korla
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Libraries added:
javax.servlet.jsp-2.2.0.jar
javax.servlet-api-4.0.1.jar
I got the same error when running a full-fledged application which i recently rebuilt on JDK-11 with Tomcat9.0 (without the above jars since tomcat comes with them). Shifted that application to JDK-8 and Glassfish (added these jars) as well and still getting the same error.
Try to install nb-javac plugin for netbeans:
https://blogs.apache.org/netbeans/entry/what-s-nb-javac-in
In my case it solved the isue
Related
I'm trying to learn using servlets and JSPs. I wanted to test out how it worked through NetBeans (using Glassfish Server). I created a web project (Java Ant for Web) and added a servlet. I didn't modify it heavily as I was only testing. I deployed it and the index.jsp worked but when I try accessing the servlet through the mapping, I am getting a HTTP 500 error.
exception jakarta.servlet.ServletException: Error instantiating servlet class test.MyDateServlet
root cause java.lang.ExceptionInInitializerError
root cause java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale en_US
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>MyDateServlet</servlet-name>
<servlet-class>test.MyDateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyDateServlet</servlet-name>
<url-pattern>/MyDateServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
MyDateServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author FE
*/
public class MyDateServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet MyDateServlet (Servlet version) </title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Today's date is: " + request.getContextPath() + "</h1>");
out.println(new java.util.Date());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is a really simple code with minimal revisions but I'm not too sure why I'm getting the error. My java is updated, and I'm currently using Java EE 7 API in my library.
You’ve mixed major versions of the Servlet technology.
A few years ago Oracle donated its Java EE specifications and technologies to the Eclipse Foundation. These were rebranded Jakarta EE.
As part of the transition, the package names changed from javax.* to jakarta.*. I see both of these in your Question, so I know you have a major mixup in your versions of API and libraries. Choose one or the other, but not both.
You need to get your API, libraries/dependencies, and deployment container all in alignment. Either you need to use older versions with javax. naming, or newer versions using `jakarta.* naming. If you are starting out on a fresh product, I would recommend the latter.
Search to learn more about this transition. It has been covered many many times in many many places including in the industry press, YouTube, and the Jakarta.EE web site.
While I’m not 100% certain this transition mismatch is the cause of your troubles, I would bet money on it.
I am in the process of migrating an application from Symfony 2.8 to Symfony 3.4
The services are now private and therefore instead of making a direct call to the services from the container, we must use dependency injection as a workaround.
So this is the following script and i'd like to check the existence and after that call profiler service using dependency injection :
<?php
namespace DEL\Bundle\ApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class EstimatePDFController
*
* #package DEL\Bundle\ApiBundle\Controller
*/
class EstimateController extends Controller
{
/**
*
* #param Request $request Request object.
*
* #return Response A Response instance
*/
public function sendAction(Request $request)
{
// disable debug env outputs
if ($this->container->has('profiler')) {
$this->container->get('profiler')->disable();
}
return new Response('OK');
}
}
As far as I know, this is not possible using autowiring. But the documentation provides an alternative:
add the profiler to your controller as a property
add a setter like setProfiler(Profiler $profiler) that sets the property
add a conditional setter to your service definition:
calls:
- [setProfiler, ['#?profiler']]
check whether $this->profiler is null or not in your sendAction method
Checking the existence means the Profiler exists before using it right? So you can autowire the Profiler with a default value and if it is not null, it exists. Something like this:
/**
* #param Request $request Request object.
* #param Profiler $profiler The Profiler if the service exists
*
* #return Response A Response instance
*/
public function sendAction(Request $request, Profiler $profiler = null): Response
{
// disable debug env outputs
if ($profiler !== null) {
$profiler->disable();
}
return new Response('OK');
}
This is the default behaviour by the way. It tries to resolve the argument, but if it fails, it skips it. And if you have no default value, then PHP fails.
I am in the process of migrating an application from Symfony 2.8 to Symfony 3.4
The services are now private and therefore instead of making a direct call to the services from the container, we must use dependency injection as a workaround.
For parameters, is $this->getParameter() is an anti pattern ? If yes, how can we get them in controller and of course we must always respecting the good practices ?
For information, there is a solution in Symfony 4.1, using the bind in services.yml
This the following script and this the environment as an example :
class CmsController extends Controller
{
/**
* #param Request $request
*
* #return Response
*/
public function importExportAction(Request $request): Response
{
$adminPool = $this->get('sonata.admin.pool');
$env = $this->getParameter('environment');
return new Response('OK');
}
}
Controllers are now seen as services.
You can look at this anwser, to know how configure services with parameters.
It seems pretty strange that AnimationTimer has not a method to know if it is running or not.... And i am facing this problem, cause sometimes it is starting and sometimes not.
A solution is creating a volatile variable inside the handle() method and every time it is running inside the handle to make it true and every time it enters stop()) method to make it false.So i have to #Override both methods.
The Question:
Why the AnimationTimer has not a method to determine if it is running?
Is it a bad design it is missing for some reason?
Relative questions:
Is AnimationTimer running in its own thread?
How can I know if an AnimationTimer is running?
It is indeed very strange that this method is missing but with the exception of you and me nobody seems to care. I have reported this issue
more than 4 years ago and nothing has happened since then although the fix seems to be trivial.
JDK-8092345
From now it has the method isRunning() until bro's from Oracle add it🐠.
By looking here although it is not present in Java 9 http://download.java.net/java/jdk9/jfxdocs/javafx/animation/AnimationTimer.html.
AnimationTimer code:
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.javafx.tk.Toolkit;
import com.sun.scenario.animation.AbstractMasterTimer;
import com.sun.scenario.animation.shared.TimerReceiver;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* The class {#code AnimationTimer} allows to create a timer, that is called in
* each frame while it is active.
*
* An extending class has to override the method {#link #handle(long)} which
* will be called in every frame.
*
* The methods {#link AnimationTimer#start()} and {#link #stop()} allow to start
* and stop the timer.
*
*
* #since JavaFX 2.0
*/
public abstract class AnimationTimer {
private class AnimationTimerReceiver implements TimerReceiver {
#Override public void handle(final long now) {
if (accessCtrlCtx == null) {
throw new IllegalStateException("Error: AccessControlContext not captured");
}
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
AnimationTimer.this.handle(now);
return null;
}, accessCtrlCtx);
}
}
private final AbstractMasterTimer timer;
private final AnimationTimerReceiver timerReceiver = new AnimationTimerReceiver();
private boolean active;
// Access control context, captured in start()
private AccessControlContext accessCtrlCtx = null;
/**
* Creates a new timer.
*/
public AnimationTimer() {
timer = Toolkit.getToolkit().getMasterTimer();
}
// For testing only
AnimationTimer(AbstractMasterTimer timer) {
this.timer = timer;
}
/**
* This method needs to be overridden by extending classes. It is going to
* be called in every frame while the {#code AnimationTimer} is active.
*
* #param now
* The timestamp of the current frame given in nanoseconds. This
* value will be the same for all {#code AnimationTimers} called
* during one frame.
*/
public abstract void handle(long now);
/**
* Starts the {#code AnimationTimers}. Once it is started, the
* {#link #handle(long)} method of this {#code AnimationTimers} will be
* called in every frame.
*
* The {#code AnimationTimers} can be stopped by calling {#link #stop()}.
*/
public void start() {
if (!active) {
// Capture the Access Control Context to be used during the animation pulse
accessCtrlCtx = AccessController.getContext();
timer.addAnimationTimer(timerReceiver);
active = true;
}
}
/**
* Stops the {#code AnimationTimers}. It can be activated again by calling
* {#link #start()}.
*/
public void stop() {
if (active) {
timer.removeAnimationTimer(timerReceiver);
active = false;
}
}
/**Determines if the AnimationTimer is Running
* #return True if it is running
*/
public boolean isRunning() {
return active;
}
}
I'm attempting to design a RESTful interface in Symfony which will be called through AJAX requests. I've been having a problem where my POST method route is being matched to the built-in redirect controller instead of the one I created below:
/**
* #Route("/todos")
*/
class TodoController extends Controller
{
/**
* #Route("/", name="todos")
* #Method("GET")
*/
public function indexAction()
{
// Get action here
}
/**
* #Route("/{id}", name="todo_delete")
* #Method("DELETE")
*/
public function deleteAction($id)
{
// Delete action here
}
/**
* #Route("/", name="todo_create")
* #Method({"POST"})
*/
public function createAction()
{
return new Response("Hello!");
}
}
My indexAction and deleteAction work fine, but my createAction did not. When I looked at the logs this is what I saw:
[2011-10-24 19:27:14] request.INFO: Matched route "todo_create" (parameters: "_controller": "Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction", "path": "/todos/", "permanent": "true", "scheme": "null", "httpPort": "80", "httpsPort": "443", "_route": "todo_create") [] []
It looks like my route is not even being associated with the TodoController I created. Any idea what is causing this?
---> #Method({"POST"})
Shouldn't that be
#Method("POST")
?
I figured it out. It turns out my client side code was calling "http://todos.localhost/todos" where the routes were expecting "http://todos.localhost/todos/" (which has a trailing /). I removed the slash in my POST request route as follows
/**
* #Route("", name="todo_create")
* #Method({"POST"})
*/
and everything works fine.
It seems like Symfony realized that the slash was missing, added it to the request url, and performed an internal redirect on using the new url. When Symfony performed the redirect, however, it wasn't maintaining the request method (POST in this case). Instead it was calling my GET controller.