I'd like to test my servlet by printing the results to the console. System.out.println does not seen to work for a servlet. Does anyone know how I can achieve this? Main purpose is for debugging at a later stage.
public class GetAllStaff extends HttpServlet {
private static final long serialVersionUID = 1L;
static StaffDAO dao = new StaffDAO();
static ArrayList<Staff> sList = null;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
sList = dao.getAllStaff();
for (int i = 0; i < sList.size(); i++)
{
}
}
You could use
ServletContext context = getServletContext( );
context.log("This is a log item");
The logs are not printed in Eclipse console but can be found at logs folder of servlet container (say Apache Tomcat)
Reference: http://www.tutorialspoint.com/servlets/servlets-debugging.htm
You may want to print everything on a browser with the following code?
PrintWriter out = res.getWriter();
out.println("Some information on the browser...");
P.S I tried System.out.println("something"); in my IDE (Intellij), the result showed up in the console.
Related
I have a ServiceHandler class and I want to essentially read in a file. In my init() function:
private String languageDataSet = null; // This variable is shared by all HTTP requests for the servlet
private static long jobNumber = 0; // The number of the task in the async queue
private File f;
public void init() throws ServletException {
ServletContext ctx = getServletContext(); // Get a handle on the application context
languageDataSet = ctx.getInitParameter("LANGUAGE_DATA_SET"); // Reads the value from the <context-param> in web.xml
// You can start to build the subject database at this point. The init() method is only ever called once during the life cycle of a servlet
f = new File(languageDataSet);
}
In a doGet function, I want to display some info on this file:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
out.print("Language Dataset is located at " + languageDataSet + " and is <b><u>" + f.length() + "</u></b> bytes in size");
}
In my web.xml file, I have the context-param as so:
<context-param>
<param-name>LANGUAGE_DATA_SET</param-name>
<param-value>wili-2018-Edited.txt</param-value>
</context-param>
I get the following output:
Language Dataset is located at wili-2018-Edited.txt and is 0 bytes in size
It can't seem to find the file as I have verified there is text in the file, therefore it shouldn't be displaying as 0. Any idea why the file seemingly can't be found? (The file is in the same directory as the web.xml file).
I'm having trouble with my semantic web application coding. The error says java.lang.ClassNotFoundException: org.apache.jena.ontology.OntModelSpec. I'm using Eclipse JEE Luna, Apache Tomcat 7, JDK 7u79, and Apache Jena 3.6.0. The class should be included in Jena jar files right? But why can't the class be found? Thank you so much for your help :)
Coding excerpt:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> dataList = new ArrayList<String>();
Model modeltmp = null;
OntModel mpidb = null;
System.out.println("DONE1");
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
mpidb = ModelFactory.createOntologyModel(spec,modeltmp);
InputStream in = FileManager.get().open("C:/Users/USER/workspace/FYP/Ontologies/MangrovePlantImageDatabase.owl");
mpidb.read(in,"http://www.mangroveplantimagedatabase.com/ontologies/mangroveplantimagedatabase.owl");
System.out.println("DONE3");
}
I am using Tess4j API for performing OCR and have created a dynamic web project in eclipse. If I create a new java class directly under the Java resources folder, the code is working fine.
public static void main(String[] args){
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try{
String result = instance.doOCR(image);
System.out.println(result);
}catch(TesseractException e){
System.err.println(e.getMessage());
}
}
However I am getting an exception when I am calling the same code from my Servlets doPost method.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Validate valObj = new Validate();
valObj.validate();
}
public void validate() {
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(image);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
I have included all the required jars under lib folder of WEB-INF. Have also added the jars in the projects build path. Could anyone please let me know what I am doing wrong.
Exception :
java.lang.IllegalStateException: Input not set
23:33:45.002 [http-bio-8080-exec-5] ERROR net.sourceforge.tess4j.Tesseract - Input not set
java.lang.IllegalStateException: Input not set
I think your current directory is different when you are calling from servlet. the current directory is you tomcat bin folder. so when you are calling like this:
File image = new File("Scan0008.jpg");
your scan0008.jpg must be put in bin folder of tomcat or you must use absolute path of your file.
I am a complete new t servlet can someone plz tell me what is wrong with my code;i am trying to name input from user in a textbox and then display welcome :"text entered by user in textbox"
here is my code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class myprogramme extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
res.setContentType("text/html");
PrintWritter out=res.getWritter();
String name=req.getParameter("txtname");
out.println("<b>< font size=8 color="red">" +"welcome:"+ </font> "</b>"+name);
}
}
name of the textbox is txtname which i am storing in name variable
To answer your specific question, you need to escape your String literal (the double quotes surrounding red) and you didn't quote the font close tag (but you could collapse it to a single HTML String) like -
out.println("<b><font size=8 color=\"red\">Welcome:</font></b>" + name);
That being said, this is not a good way to write Java Servlet today. Because it uses presentation in the Servlet.
Edit It's getWriter(), change this
PrintWritter out=res.getWritter();
to
PrintWriter out=res.getWriter();
True, it is not the best way to do it, but I would suggest you to do like below for you to learn it easily:
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("txtname");
StringBuilder sb = null;
try {
sb = new StringBuilder();
sb.append("<b>< font size='8' color='red'>");
sb.append(" Welcome : " + name + " </font></b>");
out.println(sb.toString())
} catch (Exception e) {
e.printStackTrace();
}
}
I haven't test it, hope you can get an idea..
The state:
I have a Struts 1.3 based webapp that deploys just fine to Tomcat (war or exploded).
I combine the webapp with a class to run embedded jetty 7.x. This all goes into a single jar file.
I use maven-assembly-plugin to package all dependencies exploded into the single jar. I looked inside the jar file and all is as you would expect. Standard web app layout except all dependent classes are in a standard package layout. WEB-INF/web.xml right where you would expect it.
Jetty launches fine and runs my first startup servlet that does some database initialization. My JspConfiguration uses the path "WEB-INF/web.xml" to get the web.xml (note missing leading slash).
The problem
When the Struts action servlet initializes, it specifically makes the following call:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/web.xml");
which results in:
javax.servlet.ServletException: The /WEB-INF/web.xml was not found.
at org.apache.struts.action.ActionServlet.initServlet(ActionServlet.java:1781)
at org.apache.struts.action.ActionServlet.init(ActionServlet.java:349)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:432)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
The question:
I imagine it's due to struts using the leading slash when requesting the resource.
Should I package differently?
Should I have code that captures that request and tweaks the URI to remove the leading slash? How?
I'd rather not tweak the struts code if possible....
If you decide to help, thanks!
The info:
Here is the class I'm using to fire up jetty along with the two dependent classes.
public class JettyRunner {
public static void main(String[] args) throws Exception {
if (args == null) {
args = new String[0];
}
// Construct the new arguments for jetty-runner
boolean transientState = false;
int port = 8070;
Server server = new Server(port);
WebAppContext webapp = new WebAppContext(".", "");
webapp.setConfigurations(new Configuration[]{new JspConfiguration()});
ClassPathResourceHandler resourceHandler = new ClassPathResourceHandler();
resourceHandler.setContextPath("");
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.addHandler(resourceHandler);
contexts.addHandler(webapp);
server.setHandler(contexts);
//server.setHandler(webapp);
URL jettyXmlURL = new JettyRunner().getClass().getClassLoader().getResource("jetty.xml");
XmlConfiguration configuration = new XmlConfiguration(jettyXmlURL); //or use new XmlConfiguration(new FileInputStream("myJetty.xml"));
//XmlConfiguration configuration = new XmlConfiguration(new FileInputStream("jetty.xml"));
configuration.configure(server);
server.start();
server.join();
}
}
public class JspConfiguration extends WebXmlConfiguration {
#Override
public Resource findWebXml(WebAppContext webAppContext) throws IOException, MalformedURLException {
URL path = getClass().getClassLoader().getResource("WEB-INF/web.xml");
return Resource.newResource(path);
}
}
public class ClassPathResourceHandler extends ContextHandler {
Logger log = Logger.getLogger(startupServlet.class.getName());
private ResourceHandler realResourceHandler = null;
public ClassPathResourceHandler() {
realResourceHandler = new ResourceHandlerImplementation();
}
#Override
public void doHandle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
realResourceHandler.handle(s, request, httpServletRequest, httpServletResponse);
}
private class ResourceHandlerImplementation extends ResourceHandler {
#Override
protected Resource getResource(HttpServletRequest httpServletRequest) throws MalformedURLException {
String requestedFile = httpServletRequest.getRequestURI();
log.debug("getResource(): " + requestedFile);
URL path = getClass().getResource(requestedFile);
try {
Resource resource = Resource.newResource(path);
if (resource != null && resource.exists() && !resource.isDirectory()) {
return resource;
}
else {
return null;
}
}
catch (IOException e) {
return null;
}
}
}
}
Struts was designed to run as a Web application and not as a standalone application. In your JettyRunner class, you have a main method to fire up Jetty. That won't work with Struts. You would have to create a web application if you want to use Struts 1.x.
I was able to resolve this for my struts 1.3 app using WebAppContext's setWar() method. My version of a basic jetty runner looks like:
public class JettyRunner {
private static final Logger logger = Logger.getLogger(JettyRunner.class);
public static void main(String[] args) throws Exception {
WebAppContext context = new WebAppContext();
context.setWar(System.getProperty("user.dir") + "/src/main/webapp/");
context.setContextPath("/");
logger.debug(context.dump());
Server server = new Server(8080);
server.setHandler(context);
server.start();
server.join();
}
}