Printing Request debug information on a Java Servlet - java

I find it extremely useful when doing Django/Python web development to fully inspect a HTTP request like this:
logger = logging.getLogger(__name__)
def index(request):
logger.info(request)
Is there something similar for a Java Servlet?
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// debugInfo should print something similar to what you get in DJANGO
debugInfo(request);
}

Since I got no answers, I wrote a little helper class to help me with this issue. Hope someone else finds it interesting and useful.

Related

Same header.jsp for different web application

I have a running web application with a functional header with js and css of it's own. Now I m trying to use the same header with all the features in my another application.
Instead of duplicating the code, I need to have some kind of a controller or servlet that can provide me this JSP in proper functional format.
Currently I have tried this approach mentioned below code in a servlet :
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CharArrayWriterResponse customResponse = new CharArrayWriterResponse(resp);
req.getRequestDispatcher("/WEB-INF/jsp/layout/header_new.jsp").forward(req, customResponse);
resp.getWriter().print(customResponse.getOutput());
}
I m getting the response as html but stil not able to use it in another application using tag.
Any suggestions would be helpful.

How to add a FIleHandler to a HttpServlet ( java.util.logging)

I have implemented a HttpServlet that uses java.util.logging for leaving Log.
Now I want that the Servlet leaves the Log inside a txt file.
I know the FileHandlers implements this functionality.
Doubts:
Where I have to put the code that adds the FileHanlder to the Logger? by "where", I mean in which part of the code. I think that in the service() method is not correct at all.
#Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// HERE???
}
I want that the FileHandler is instanced only one time , so I have no locks problem with the txt file. How can I do that? Do you have any samples of code/recommendations?
Please forgive my bad explanation, but I am lost, and very noob in Java.

How can i implement java Rest with out Jersy

Hello i am trying to develop a rest api .it have no need for performance issue or such complex design just two api . how can i develop it with out jersy using jetty server ??
Isn't there any way we can make a RESTful web service without using jersey or for that matter any other light weight libs ?
is there any Reasons for not directly write Servlets for creating a REST API ??
Here is the code for skeleton servlet. If you have issues making it run, let me know and I'll post complete sample project.
public class TestServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String query = request.getQueryString();
writer.print("Hello. You said: " + query);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}
REST is basically a concept over applied the HTTP protocol. You can implement it with Servlets and JSP, even thought it will be much harder to understand in a more complex scenario, when a base resource invokes sub-resource, building a chain call.
I would recommend that you stick to the JAX-RS specification for java REST services. It is very lightweight and easy to understand.

Servlet should accept POST and GET

I try to implement a servlet which should be called either through POST or GET.
So I wrote something like this
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// .. do stuff
// forward to welcome page
this.getServletContext().getRequestDispatcher("/guestbook.jsp").forward(req, resp);
return;
}
But/or because of the forward at the end I get an IllegalStateException, which is only a warning but still. What should I do differently?
Thanks,
-lony
Edit: Wanted Stacktrace
2012-05-26 18:02:16.422:WARN::/wsc/guestbook
java.lang.IllegalStateException: Committed
at org.eclipse.jetty.server.Response.resetBuffer(Response.java:1056)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:216)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:115)
at de.tum.in.dss.GuestbookController.doGet(GuestbookController.java:135)
at de.tum.in.dss.GuestbookController.doPost(GuestbookController.java:37)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:538)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1352)
at de.tum.in.dss.XSSFilter.doFilter(XSSFilter.java:76)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1323)
at de.tum.in.dss.AccessFilter.doFilter(AccessFilter.java:55)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1323)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:476)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:517)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:225)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:937)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:871)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:247)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
at org.eclipse.jetty.server.Server.handle(Server.java:346)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:589)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:1065)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:823)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:220)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:411)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:535)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:529)
at java.lang.Thread.run(Thread.java:722)
Your concrete problem is not related by letting GET and POST both do the same thing. Your problem is caused by writing to the response in the servlet and thus implicitly committing it before performing the forward.
Do not touch response.getWriter() or resposne.getOutputStream() in the servlet and just let JSP do that job. If you need to prepare data which JSP needs to display, just set it as an attribute in the request, session or application scope, depending on the scope the data needs to hold in.
See also:
Our servlets wiki page
Doing the same job on GET and POST is by the way smelly. Are you sure you understand what exactly each of those methods are to be used for?
You can override directly the service() method, it's called for all request methods.
replace this.getServletContext() with req

Servlet : doGet and doPost [duplicate]

This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 6 years ago.
I have 2 parameters, User and Pass. I want to send them to a servlet.
If I use the doGet method of the servlet it would look like this :
"link?User="+TextFieldValue+"&pass"textFieldValue
user= UserName.getValue();
pass= password.getValue();
Resource newPictureResource = new ExternalResource("http://localhost:8888/PieChart?UserName="+name+"&Password="+pass);
Success.setSource(newPictureResource);
editContent.addComponent(Success);
send them to servlet :
String UserName = request.getParameter("UserName");
String Password = request.getParameter("Password");
It works (tested)
If the Username + pass are right then he get a "success" picture posted on the screen.
But nobody passes the parameters via URL.
My question: How do I send the parameters using doPost method of the servlet ?
info : im working with eclipse on a liferay portal with a Vaadin portlet.
You don't send parameters in doPost(..). You receive them there. HTTP has many methods, two of which are GET and POST. It is up to the client-side to choose which method to use. POST is most often used with html forms - <form method="POST".
Vaadin should be able to send POST requests as well - see this thread
Not sure how Vaadin interacts, but typically portlet requests are handled differently. Looking though The Book of Vaadin - Portal Integration sheds some insights on configuration and action processing.
If you're looking for a way to handle both request types without reusing logic, simply choose your method of submission by either post or get from your application interface:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Enter logic here
}

Categories

Resources