I am using servlet to get request from frontend. Am i able to make single servlet which could do multiple operation based on url pattern? Here will be my url mapping
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
<url-pattern>/HelloServletOne</url-pattern>
<url-pattern>/HelloServletTwo</url-pattern>
</servlet-mapping>
That means if i hit to the url as framed below it should invoke its own functionalities.
How can i achive this by extending servlet.?
Code/link examples are much appreciated.
Regarding your url-pattern you need to know what URL was called. Because a request can be made due to different http-methods (GET, POST etc.) you can use parts of the FrontController Pattern
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
private static final String SERLVET = "HelloServlet";
private static final String SERLVET_ONE = "HelloServletOne";
private static final String SERLVET_TWO = "HelloServletTwo";
@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);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
String path = req.getServletPath();
switch (path) {
case SERLVET:
// ... call your function1
break;
case SERLVET_ONE:
// ... call your function2
break;
case SERLVET_TWO:
// ... call your function3
break;
default:
break;
}
// do something else
}
}
The getServletPath method may only work for explicit url-patterns like you have given. For other information on the URL check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With