tags:

views:

60

answers:

2

I have a piece of Java code in a simple blogging servlet being used in Apache Tomcat. I have page being generated based on a form in the previous page, among this is a link to publish the post. I would like the user clicking that link to call a method later in the class. Is this possible and, if so, how?

+1  A: 

Links generate GET requests. So if you want to execute some Java code during a GET request, you need to create a Servlet which has the doGet() implemented and execute the desired code logic accordingly.

If necessary, you can pass request parameters using the usual query string way like href="myservlet?name1=value1&name2=value2" or -more SEO friendly- as part of the path like href="myservlet/value1/value2" which you can access using HttpServletRequest#getPathInfo().

After processing the request, the servlet needs to forward the request to a JSP to display the page. This can be done by request.getRequestDispatcher("page.jsp").forward(request, response).

The servlet class behind myservlet is obviously to be mapped on an url-pattern of /myservlet/*.

Hope this helps.

[Edit] as one of your later comments reveals, you'd like to pass request scoped data to the next request. This case, just pass them along to the next request as request parameters. If they are already available as request parameters, then just do:

href="myservlet?name1=${param.name1}&name2=${param.name2}"

Otherwise, if they're only available as model data, then do something like:

href="myservlet?name1=${data.name1}&name2=${data.name2}"

Inside the doGet() method you can reobtain them the usual way by HttpServletRequest#getParameter().

Good luck.

BalusC
+1  A: 

Yes. The link can point back to that servlet (or to any servlet), and when you process the request, call whatever method you like.

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException {

    ... whatever I want ...

    anyMethod(req, res);

    ... whatever I want again ...
}
Willie Wheeler
The problem that Im having is that the data i need comes from parameters on one page and is then just static text on the next. How can i persist the data from one page to the next. I know this is a noobish question. thanks
Igman
Thanks guys. I got it. You were both awesome.
Igman
Check out HttpSession. You can call getAttribute() and setAttribute() to store data across requests.
Willie Wheeler