#WebServlet annotation and error 404 [duplicate] - servlets

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
First of all: I use GlassFish 3.1 + Eclipse Java EE indigo.
I want to testing cache solutions with javaee so I made a dummy app. I have a big generated database and I list, search, modify, etc some data. To do that I wrote some basic servlet and I call with GET parameters. e.g.: /app/list?page=product&pageSize=100
The ListServlet is annotated with
#WebServlet({ "/ListServlet", "/list" })
and it works like a charm, I can use both urls.
So I need some additional servlet (for search, modify). I created them and annotated the same way.
But when I type the url http://localhost/app/modify or /app/search?id=1 I get error 404.
I tried to write a very dummy helloservlet which is print a hello world message but it didn't work: error 404. I restarted the glassfish server and the computer but not helped.
What's the problem? Did I miss something?
EDIT:
the servlets are the same package uses the same imports...

Are you sure your url patterns are correct? Try something like this:
#WebServlet( name="ListServlet", displayName="ListServlet", urlPatterns = {"/list","/modify", "/search"}, loadOnStartup=1)
If you want all the patterns go into the same servlet. If not, you would have to have a different servlets for each pattern, and those servlets should be named differently I guess.
Anyway, for this kind of behaviour I would recommend using for example Restlet routing.
EDITED:
I tested it. Here you have my servlets working like a charm:
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(asyncSupported = false, name = "HelloServlet1", urlPatterns = {"/hello1"})
public class TestServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<h2>Hello Servlet One </h2>");
out.close();
}
}
and the second one:
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(asyncSupported = false, name = "HelloServlet2", urlPatterns = {"/hello2"})
public class TestServlet2 extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<h2>Hello Servlet Two </h2>");
out.close();
}
}
I do call them like: http://localhost:8080/eetest/hello1 and http://localhost:8080/eetest/hello2 and they print 'Hello Servlet One' and 'Hello Servlet Two' respectivelly.
(tested on JBoss AS 7 - web profile)

I had this issue and the problem was a forgotten import statement in my servlet. Make sure your servlet is compiling correctly.

Related

How to fix remote ejb lookup in Websphere Liberty?

I am trying to access the ejb deployed on websphere liberty 18.0.0.3
The binding location is: java:global/ITSORemote/ITSORemoteEJB/HelloRemoteEJB!com.ibm.itso.ejbRemote.view.HelloRemoteEJBRemote
My ORB configuration in the server.xml is:
<orb nameService="corbaname::<ipaddress>:2809" iiopEndpointRef="defaultIiopEndpoint">
<iiopEndpoint host= id="defaultIiopEndpoint" iiopPort="2809">
</iiopEndpoint>
</orb>
I have also added ejbRemote-3.2 in feature manager
I have two scenarios:
1. Access ejb from a client code running on the same server - This works using the url java:global/ITSORemote/ITSORemoteEJB/HelloRemoteEJB!com.ibm.itso.ejbRemote.view.HelloRemoteEJBRemote
2. Access ejb from a client code running on the different server - This does not work using the url
corbaname::(ipaddress):2809#ejb/global/ITSORemote/ITSORemoteEJB/HelloRemoteEJB!com.ibm.itso.ejbRemote.view.HelloRemoteEJBRemote
I am using the following code for lookup:
package com.ibm.remoteaccess;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.itso.ejbRemote.view.HelloRemoteEJBRemote;
/**
* Servlet implementation class RemoteAccess
*/
#WebServlet("/RemoteAccess")
public class RemoteAccess extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
out.println("Hi");
Context ctx = new InitialContext();
Object ejbBusIntf = ctx.lookup("java:global/ITSORemote/ITSORemoteEJB/HelloRemoteEJB!com.ibm.itso.ejbRemote.view.HelloRemoteEJBRemote");
HelloRemoteEJBRemote bean = (HelloRemoteEJBRemote)PortableRemoteObject.narrow(ejbBusIntf, HelloRemoteEJBRemote.class);
out.println(bean.hello());
}
catch (NamingException e) { // Error getting the business interface
out.println(e);
}
}
}
There is no error thrown in the console also. What could be the problem?
There is a functional acceptance test (FAT) in open-liberty that looks up a remote EJB from one liberty server to an EJB on a second liberty server. The specific test can be found here:
https://github.com/OpenLiberty/open-liberty/blob/master/dev/com.ibm.ws.ejbcontainer.remote_fat/test-applications/RemoteClientWeb.war/src/com/ibm/ws/ejbcontainer/remote/client/web/RemoteTxAttrServlet.java
Each server process includes the ejbRemote-3.2 feature and an iiopEndpoint configuration (different ports since the test runs both serves on the same host).
https://github.com/OpenLiberty/open-liberty/blob/master/dev/com.ibm.ws.ejbcontainer.remote_fat/publish/servers/com.ibm.ws.ejbcontainer.remote.fat.RemoteServerClient/server.xml
If you are not seeing any errors, then perhaps the iiopEndpoint is not configured properly in the client side server (as the ORB will not start without it). For example, the default iiop port is 2809, and if both servers are on the same host, then they cannot both use that port. Setting both servers to the same port would result in the ORB not starting properly on one of the servers, and lookups would fail.
A lookup across servers would use corbaname, and the value you have specified appears to be correct.

Error 503 in J2EE Preview at local host

I'm simply trying to insert a row of data to a database using a serve-let in eclipse. I'm using the server J2EE Preview at local host. I even tried using apache tomcat v7.0. But every time 'HTTP ERROR 503' comes on the web page.
This is my code.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class trying extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
Statement myStmt = myConn.createStatement();
String sql = "insert into user values ('bandiiii', '123')";
myStmt.executeUpdate(sql);
System.out.print("done");
}catch( Exception exc) {
exc.printStackTrace();
}
}
}
Most Probably your application is down or the application is trying to hit a server that is not up and running.
Http Status code 503:
simply means that service is unavailable.
Troubleshooting:
Check if your server & Oracle servers are up and running on the specified ports.

AEM Servlet response writter removing links

In AEM, I'm trying to write a JSON object that contains a string object via a get servlet, like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObject.toString());
Response being of type SlingHttpServletResponse
When the servlet is accessed in a browser the is stripped with a warning coming out of the aem log:
03.08.2015 16:55:27.359 *WARN* [127.0.0.1 [1438617327343] GET /bin/integration.json HTTP/1.1] com.day.cq.rewriter.linkchecker.impl.LinkCheckerImpl Ignoring malformed URI: java.net.URISyntaxException: Illegal character in path at index 0: \
Link checker is bypassed for a lot of patterns including the link above.
For example the string object inside the json:
pageIntro:'this link doesn't work'
becomes:
pageIntro:'this link</a> doesn't work'
Any help would be much appreciated.
Cheers,
Alex
By doing a quick fiddle around AEM 6.0 , I am not able to reproduce this issue .
Following is what I did in the servlet. Attaching the snippet below. Is there anything else you are doing to achieve this ?
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#SlingServlet( label = "Stack Overflow - Sabya Test Servlet",
description = "Used for quick fiddle",
paths="/bin/sabya-servlet.json",
metatype = true
)
public class SabyaTestServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1335893917596088016L;
private static final Logger log = LoggerFactory
.getLogger(SabyaTestServlet.class);
#Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
log.trace("Sabya Test Servlet : doGet() starts .. ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("pageIntro", "this <a href='http://www.domain.com/my-section/page.html'>link</a> doesn't work");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObject.toString());
} catch (JSONException e) {
log.error("Something ridiculous has happened !! {}" , e);
}
log.trace("Sabya Test Servlet : doGet() ends .. ");
}
}
Request URL : http://localhost:4502/bin/sabya-servlet.json
Response :
{
pageIntro: "this <a href='http://www.domain.com/my-section/page.html'>link</a> doesn't work"
}
Note : I believe you are using org.apache.sling.commons.json.JSONObject .

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

I am using the below code to upload a file in to tomcat5.5 and it gives me the following exception
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
could you please help me to find it out?
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("Status : "+isMultipart);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("upload.jsp");
}
}
this is the jar i use commons-fileupload-1.2.2.jar
The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.
And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.
See also:
How to upload files to server using JSP/Servlet?
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
How do I import the javax.servlet API in my Eclipse project?
use maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
or download commons-io.1.3.2.jar to your lib folder
Solution
By default, Struts is using Apache “commons-io.jar” for its file upload process. To fix it, you have to include this library into your project dependency library folder.
Get Directly
Get “commons-io.jar” from official website – http://commons.apache.org/io/
Get From Maven
The prefer way is get the “commons-io.jar” from Maven repository
File : pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
just put all apache comons jar and file upload jar in lib folder of tomcat
If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.
You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt
Now, Next add this downloaded files into your project:
Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93

Processing an InputStream to OutputStream on the fly through a HttpServlet

I'm trying to process a large text file through a HttpServlet (tomcat).
As this file can be large and the process should be very fast, I don't want to upload the file on the server and I've used the method HttpRequest.getInputStream to process the input on the fly. For example, I want to transform the input to upper-case with the code below:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class EchoServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
OutputStream out=null;
InputStream in=req.getInputStream();
if(in==null) throw new IOException("input is null");
try
{
resp.setContentType("text/plain");
out=resp.getOutputStream();
int c;
while((c=in.read())!=-1)
{
out.write((char)Character.toUpperCase(c));
}
}
catch(IOException err)
{
//ignore
}
finally
{
if(out!=null) out.flush();
if(out!=null) out.close();
in.close();
}
}
}
I invoked my servlet with CURL:
curl -s -d #big.file.txt "http://localhost:8080/test/toupper"
1) processing the input on the fly through a servlet, is it a good/common practice ?
2) my code seems to remove the carriage return ('\n') . Why ?
Thanks
1) processing the input on the fly through a servlet, is it a good/common practice ?
Depends on the functional requirement. I would personally have used a servlet which accepts HTTP multipart/form-data requests instead of raw request bodies. This way it's reuseable on normal HTML forms.
2) my code seems to remove the carriage return ('\n') . Why ?
The given code example doesn't do that. Maybe you've oversimplified it and you was originally using BufferedReader#readLine() while not using PrintWriter#println(). The readLine() indeed eats CRLFs.
There are more issues/inefficiencies in the given code snippet as well, but I can't give a decent answer on that as you seem not to actually be running the code as you posted in the question.

Resources