Error 503 in J2EE Preview at local host - servlets

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.

Related

Failed to meta-introspect annotation interface org.springframework.web.bind.annotation

error message
21:13:46,666 DEBUG AnnotationUtils:1889 - Failed to meta-introspect annotation interface org.springframework.web.bind.annotation.RequestBody: java.lang.NullPointerException
com.alibaba.dubbo.rpc.RpcException: No provider available from registry 172.16.33.23:2181 for service com.itheima.service.CheckItemService on consumer 172.16.33.29 use dubbo version 2.6.0, may be providers disabled or not registered ?
at com.alibaba.dubbo.registry.integration.RegistryDirectory.doList(RegistryDirectory.java:572)
I have checked my Dubbo annotation package and controller's import but find that is right.
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/checkitem")
public class CheckItemController {
#Reference
private CheckItemService checkItemService;
#RequestMapping("/add")
public Result add(#RequestBody CheckItem checkItem){
try{
checkItemService.add(checkItem);
}catch (Exception e){
e.printStackTrace();
return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
}
return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
}
Also, my zookeeper started.
[root#localhost bin]# ./zkServer.sh start
JMX enabled by default
Using config: /usr/local/zookeeper-3.4.6/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
And the front end request successful.
it seems that have no problems
[zk: 127.0.0.1:2181(CONNECTED) 1] ls /dubbo/com.itheima.service.CheckItemService
[consumers, configurators, routers, providers]
anyone who can give a direction?
I can almost understand where the mistake is,but I don't know what to do.
RegisteryDirectoty.class

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.

servlet has to be reloaded everyday

I have created a servlet to access a database and giving response to a BB application...it was running fine during development...but after loading it on a tomcat server 6.0 after goining live the servlet has to be reloaded every morning on the tomcat server....after that it works fine during the whole day..but the next morning when i request something it gives a blank page as response and my server admin tells the servlet has to be reloaded ...
other application hosted on the server are working fine and do not need a restart...
what might be the problem....
adding the code ..if it helps
package com.ams.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.cms.dbaccess.DataAccess;
import com.cms.utils.ApplicationConstants;
import com.cms.utils.ApplicationHelper;
import java.sql.ResultSet;
public class BBRequestProcessorServlet extends HttpServlet {
/**
*
*/String userString;
private static final long serialVersionUID = 1L;
String jsonString = "";
ResultSet rs = null;
Connection connection = null;
Statement statement=null;
public enum db_name
{
//Test
resource_management_db,osms_inventory_db;
}
public void init(ServletConfig config)throws ServletException
{
super.init(config);
System.out.println("Inside init");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try{
connection = DataAccess.connectToDatabase("xxx", connection);
statement = DataAccess.createStatement(connection);
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = statement.executeQuery("query is here");
}
catch(SQLException e)
{
e.printStackTrace();
}
String db =request.getParameter("db");
System.out.println("DATABASE NAME :"+ db);
if(db.equalsIgnoreCase("xxx")){
//Call to populate JSONArray with the fetch ResultSet data
jsonString = ApplicationHelper.populateJSONArray(rs);
}
response.setContentType(ApplicationConstants.JSON_CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
System.out.println("json object sent");
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the only errors i could find was
Jul 20, 2012 9:57:24 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/usr/local/tomcat/apache-tomcat-6.0.20/webapps/MobileServlet /WEB-INF/lib/servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
The culprit is most likely the way how you handle external DB resources like the Connection. This problem can happen when you keep a DB Connection open all the time without closing it. When a DB Connection is been opened for a too long time, then the DB will timeout and reclaim it. This is most likely what was happening overnight.
You should redesign your DataAccess and BBRequestProcessorServlet that way so that you are nowhere keeping hold of Connection, Statement and ResultSet as an instance variable, or worse, a static variable of the class. The Connection should be created in the very same scope as where you're executing the SQL query/queries and it should be closed in the finally block of the very same try block as where you've created it.
By the way your jsonString should absolutely also not be declared as an instance variable of the servlet, it's not threadsafe this way.
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
How do servlets work? Instantiation, sessions, shared variables and multithreading
As to the error which you're seeing in the log, you should definitely remove the offending JAR. See also How do I import the javax.servlet API in my Eclipse project?
I am guessing and will be more clear after seeing your logs.
Its seems like you have putted your servlet-api.jar in the WEB-INF lib but its already in tomcat's lib.

#WebServlet annotation and error 404 [duplicate]

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.

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