I have the following servlet:
#WebServlet("/publication/topic/*")
public class ViewTopicPublicationsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String[] pathInfo = request.getPathInfo().split("/");
System.out.println(Arrays.toString(pathInfo));
...
}
}
And for example if I have such url:
http://localhost:8080/bulletinboard/publication/topic/SALE
I want to omit empty string. So pathInfo resulted in [SALE] instead of [,SALE]
How this may be achieved ?
You can omit the first character since it's always a slash:
request.getPathInfo().substring(1).split("/")
Related
I have a servlet class which has a method "process", over ridden from HttpServlet
#override
protected void process(HttpServletRequest request, HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;
String inXml = null;
//some more code..
}
It is reading whatever is coming into the servlet.
How can I rewrite this as rest controller in spring??
Just code it as:
#RestController
public ReturnType process(HttpServletRequest request, HttpServletResponse response {
//...
}
and check this part of the Spring MVC documentation as well:
#RequestMapping handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values.
Note, that:
whatever you return from your Rest-Controller turns into HTTP Response Body;
you can define #RestController on the class level.
I am new java programmer. So I do understand the process of running servlet through mapping etc in the web.xml and I also can launch the servlet through annotation, my question is when I use the annotation, and run the project on the server, why do I have to write the serlvet name in the URL after project name for it to launch.
Is there any way without using web.xml file at all, giving an annotation and then when I run project on server that it would automatically launch and run the servlet? Instead of my writing the servlet name and hitting enter for it to launch.
#WebServlet(urlPatterns = {"/GetDate"})
public class GetDate extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Date date =new Date();
resp.setContentType("text/html");//this says we will send back html type
//get a pen to write back
PrintWriter pen=resp.getWriter();
//write back
pen.write(date.toString());
}
}
I would like the above simple servlet to just launch automatically as soon as I select run on server from eclipse.
You can specify load on startup in annotation, then the servlet's init() method is invoked when the web server starts
#WebServlet(urlPatterns = {"/GetDate"}, loadOnStartup=1)
public class GetDate extends HttpServlet{
#Override
public void init() throws ServletException {
// do some init stuff
}
It's all in the #WebServlet notation. If you change your code to be:
#WebServlet(urlPatterns = {"/"})
public class GetDate extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Date date =new Date();
resp.setContentType("text/html");//this says we will send back html type
//get a pen to write back
PrintWriter pen=resp.getWriter();
//write back
pen.write(date.toString());
}
}
Then the servlet is served at the / URL (after your webapplication name)
Be careful doing this. Traditionally you serve HTML resources from the / location. If you take this over with your servlet then you can't serve HTML. Additionally if you have more than one servlet then which one gets the / path - where do the rest go? It can be a bit self documenting to have the URL match the servlet. Note that there is no need to keep it the same name as the servlet - call it /myBigLongURLMapping if you like - the name is up to you.
Instead of #WebServlet(urlPatterns = {"/GetDate"}) write like this #WebServlet("/GetDate")
#WebServlet("/GetDate")
public class GetDate extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Date date =new Date();
resp.setContentType("text/html");//this says we will send back html type
//get a pen to write back
PrintWriter pen=resp.getWriter();
//write back
pen.write(date.toString());
}
}
I have a question with Spring MVC RequestMapping annotation. need your help.
I have created one IPSLcontroller and i want that IPSLcontroller to handle all request url.i have created two method in this controller.
1)handleLogoutRequest :- this method should invoke on below url.
2)handleRequest :- this method should invoke on all request url otherthan logout.
http://localhost:9086/webapp/login
or
http://localhost:9086/webapp/add
or
http://localhost:9086/webapp/remove
here is my sample code. but it's not working as expected.
#Controller
public class IPSLController {
#RequestMapping(value={"/logout/*"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"/*"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
You should use a general Prefix for every controller you use, so you can differ between them better. Also you donĀ“t need any "/" for calls like this.
#Controller
#RequestMapping("ispl")
public class IPSLController {
#RequestMapping(value={"logout"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"hello"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
If you now want to call them over a ServletRequest or with a restService or something similar you should declare them like this
#GET
#Path("ispl/logout")
public void Method (HttpServletResponse ...)
Well it is working the way it should. You have a mapping for /* and for /logout/*. So when you post to /logout it invokes the method for /*. I suspect that if you post to /logout/something it would invoke your logout handler.
If you want it to work, you cannot have a wildcard mapping for the second method. At least use /something/* so that spring can make a correct decision on mappings.
I tried to set default servlet by this way:
#WebServlet({"/abc", "","/"})
public class GreetingServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
getServletContext().getRequestDispatcher("/asd/ind.html").forward(request,response);
}
#Override
public String getServletInfo() {
return "The Hello servlet says hello.";
}
}
The file /asd/ind.html is exist, when I remove "/" like :
#WebServlet({"/abc", ""})
the redirection works fine when I hit:
contextpath/abc
contextpath/
contextpath
But with "/" like
#WebServlet({"/abc", "","/"})
It turns out
javax.servlet.ServletException: AS-WEB-CORE-00089
When I hit any URL at all, even the previous ones that did work.
Could anyone please give me an explanation? the "/" should make the servlet default which means any unmapped URL should redirected to GreetingServlet.
The problem happened because the default servlet maps the URI to the static path if it's not mapped to any servlet, but what I did is redefining the default servlet, so when I redirect to /asd/ind.html and this URI is not mapped to any servlet the default serlvet is called and in this case the default one is GreetingServlet, this causes infinite loop.
i want to ask you about mvc. How it works. So, this is simple example(I don't use any frameworks)
in Controller(Servlet):
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String page = null;
AbstractCommand action;
action = ActionFactory.getAction(request);// get command from factory
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
for action we create a common interface(Strategy pattern):
public interface AbstractAction {
public String execute(HttpServletRequest request, HttpServletResponse response);
}
Simple Action(Example):
public class HelloAction implements AbstractAction {
#Override
public String execute(HttpServletRequest request,
HttpServletResponse response) {
//....(some actions to modify request)
String page = "/main.jsp";
return page;
}
}
And now, our factory:
public class ActionFactory {
private enum Actions{
HELLO;
}
public static AbstractAction getAction(HttpServletRequest request){
String action = request.getParameter("action");//take parameter from jsp
Actions actionEnum = Actions.valueOf(action.toUpperCase());
switch (actionEnum) {
case HELLO:
return new HelloAction();
}
}
}
We came to the place where I am in confused. Servlet is initialized only once, and only one for all requests. Just forwards requests to the actions where we modify request or response. But, we create NEW instance of the class for every request. Here can occur memory overflow!? Or not?
Can we make these actions static(static method, one for all request)? If two requests come at the same time what will happen to them?
What do you think about this, please share your experience.
P.S. sorry for bad english.
How about Singleton pattern to get the instance of the Action class ?
Just add some abstact getInstance() method in AbstractAction.
Make every implementation provide its own instance.
In every implementation class, use Singleton pattern so that only one instance exists.
Make sure no action class stores any data related to a specific request.
As i understood the jsp, the whole thing is stateless, if u access the servlet by http request, the servlet will be created in a new instance.
After leaving the servlet by .forward(), it will be released by garbage collection.
2,3,...,n requests = 2,3,...,n servlets.
by forwarding to a jsp, the only way to access the servlet from jsp is a new http request = new servlet. ( will move to the doPost method)