I am quite new to JSP, servlets, etc.
I am making a website for learning purposes. I would like it to have a classic layout - menu on the left, and content in central part. I came across problem: I want to make "dynamic menu". It would load some data from database (countries). I can do it on single page by creating a servlet that returns those countries for me.
#WebServlet("/countries")
public class LeagueCountriesServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp);
}
void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
LeaguesDAO dao =
(LeaguesDAO)req.getServletContext().getAttribute("leaguesDAO");
List<String> list = dao.getAllCountries();
req.setAttribute("countrylist", list);
RequestDispatcher view = req.getRequestDispatcher("menulist.jsp");
view.forward(req, resp);
}
}
However, in fact it works only if I access "/countries". I would like to make it appear on many pages.
I tried to solve it with including it in other JSPs
<jsp:include page="/countries" />
But this causes that website is being "cut" after that included part.
What is the proper way to handle "layouts" like that?
I could generate response for this menu in every servlet, but it doesn't sound like a proper method.
I believe that i should divide template into two parts: pre-content holding header, menu, etc, and post-content holding footer etc, and include them in .jsp's used to display content-data coming from servlets. But how to avoid problems with dynamically generated menus?
<jsp:include page="before-content.jsp" />
(here some code to display specified web page)
<jsp:include page="after-content.jsp" />
Thanks for help!
You should change path in #WebServlet("/countries") not in JSPs, web server (Tomcat/Jetty/etc) are dispatches http requests looking into servlet mapping. Afterwards your servlet points which jsp should be used to generate desired html page.
Have a look at Apache Tiles, implementing the Composite View Pattern or Sitemesh, which uses the Decorator Pattern.
In Tiles you can define some templates for the header, footer and menu part and reuse them for every page.
Related
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.
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.
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
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
}
I have a servlet which is in the same web application as the JSF servlet.
How do I replace (rather than redirect) the servlet response with the JSF response?
Not sure I fully understand your question - but if you want to include the output from a JSF page in your servlet response, something like:
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// Do stuff
req.getRequestDispatcher("/blah.jsf").forward(req, res);
// Do other stuff
}
Should do the trick
I recommend using urlrewritefilter.
Simple
<rule>
<from>^/my/servlet/uri</from>
<to>/jsfpage.jsf</to>
</rule>
should be enough.