I am absolutely new in Servlet technology and this is absolutely basic question, but I am all confused by the tutorials that are all too complicated for me.
I have a new servlet HelloWorldServlet. In web.xml, I have this
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>cz.hello.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
HelloWorldServlet.scala (I prefer scala to java) looks like this
package cz.hello
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class HelloWorldServlet extends HttpServlet {
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
resp.setContentType("text/plain")
resp.getWriter.println("Hello, world")
}
}
So far so good, servlet is loaded using Jetty, I am happy, I can see “hello world” on http://localhost:8080/HelloWorldServlet.
Now, I want the servlet to be able to react to GET requests to, say, http://localhost:8080/HelloWorldServlet/hello and http://localhost:8080/HelloWorldServlet/goodbye and to both of them differently. For example like (pseudocode)
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
resp.setContentType("text/plain")
if (req.isAddress("/hello") {
resp.getWriter.println("Hello, world")
} else {
resp.getWriter.println("Goodbye, world")
}
}
How can acchieve that?
First of all, if you want to react to POST requests, you should implement the
doPostmethod, instead of thedoGet.Second, I would advise you to think about handling each URL in a different servlet, unless your code will be as simple as the example you provided.
Chances are your code will get more complex when developing real-world applications, so it would be much cleaner if you separate the responsibilities into two servlets. If you agree with this approach, it is just a matter of creating another
<servlet>and another<servlet-mapping>object in yourweb.xml, like follows:This way, requests to
/hellowill be handled byHelloWorldServlet, and requests to/goodbyewill be handled byGoodbyeWorldServlet. Now it is just a matter of defining whether GET or POST makes more sense for you and implementing the corresponding methods(doGetordoPost, or both) at your servlets.Your idea (comparing the contents of the URL inside the servlet) also works, but is not a good design, since you might end up with a huge if/then/else chain, which sounds like a bad idea in this case.