根据用户的选择,选择要执行的代码部分

时间:2016-06-18 14:17:25

标签: java html servlets

我目前正在开发Java Web动态项目,我的html页面中有一个菜单栏。当用户单击菜单上出现的其中一个可用选项时,我希望能够控制匹配的Servlet中的哪部分代码将被执行。

1 个答案:

答案 0 :(得分:1)

您的菜单项与链接相关联,类似于:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>simple Servlet</title>
</head>
<body>
<ul>
    <li><a href="action?action=doThat">that Action</a></li>
    <li><a href="action?action=doThis">this Action</a></li>
</ul>

</body>
</html>

部署描述符:

<?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>action</servlet-name>
        <servlet-class>de.so.ActionServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>/action</url-pattern>
    </servlet-mapping>
</web-app>

和servlet代码:

package de.so;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class ActionServlet extends HttpServlet
{

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException,
            IOException
    {
        String action = request.getParameter("action");
        Writer out=response.getWriter();

        if (action == null || action.isEmpty())
        {
            out.write("Action empty");
        }
        else if (action.equals("doThis"))
        {
            out.write("perform this Action");
        }
        else if (action.equals("doThat"))
        {
            out.write("perform that Action");
        }
    }
}