Geha Geha - 6 months ago 27
Java Question

How to get servlet action (request parameters) from index.html

I have in index.html:

<li><a href="list?action=list">List</a></li>


and in servlet class

public class Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("List")){
// do something.....
}
}
}


web.xml

<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>ru.proj.top.web.Servlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/list</url-pattern>
</servlet-mapping>


action in servlet is null.

How can I send this parameter from
index.html
to servlet?

Answer

I wouldn't name a servlet "Servlet" for test purposes. May be, somewhere in the big world there exists a base class with the same name...

So I call it "SimpleServlet".

Then you have this web.xml (be aware of the fully qualified class name):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <servlet>
        <servlet-name>simpleServlet</servlet-name>
        <servlet-class>de.so.SimpleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>simpleServlet</servlet-name>
        <url-pattern>/list</url-pattern>
    </servlet-mapping>
</web-app>

Now, if you call http://localhost:8080/simpleServlet/list?action=demo , the variable action in doGet() will contain "demo"

Also, I suggest to check action for null before calling a method on it:

    String action = req.getParameter("action");
    if (action != null)
    {
        // do something
    }
    else
    {
        // do something else
    }