我在index.html中有:
<li><a href="list?action=list">List</a></li>
在servlet类中
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>
Servlet 中的操作为空。
如何将此参数从 index.html
发送到 servlet?
最佳答案
出于测试目的,我不会将 servlet 命名为“Servlet”。也许,在这个大世界的某个地方,存在一个同名的基类......
所以我称之为“SimpleServlet”。
然后你就有了这个web.xml
(注意完全限定的类名):
<?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>
现在,如果你打电话
http://localhost:8080/simpleServlet/list?action=demo
,
doGet()
中的变量 action
将包含“demo”
此外,我建议在调用方法之前检查 action
是否为 null:
String action = req.getParameter("action");
if (action != null)
{
// do something
}
else
{
// do something else
}
关于java - 如何从index.html获取servlet操作(请求参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713934/