简体   繁体   English

使用字符串查询参数的servlet重定向失败

[英]Unsuccessful redirecting of servlet based using string query parameters

Situation: In the code below I'm attempting to learn how to use form parameters specifically redirecting Java servlets by propagating string query parameters. 情况:在下面的代码中,我试图学习如何使用表单参数,特别是通过传播字符串查询参数来重定向Java servlet。

Problem: I can't seem to figure out why I'm facing a problem with re-directing the user from the form ie index.html using the desired string query paramters to the correct page. 问题:我似乎无法弄清楚为什么我要使用所需的字符串查询参数将用户从index.html表单重定向到正确的页面时遇到问题。

Below are the steps I took before posting this up: 以下是我在发布之前采取的步骤:

  • I made sure the URL pattern for the @WebServlet annotation is correct ie in my case /CityManagerWebStarter/mainmenuresponder.do 我确保@WebServlet批注的URL模式正确,即在我的情况下/CityManagerWebStarter/mainmenuresponder.do

  • I made sure my content-root when looking at the URL is correct ie /CityManagerWebStarter and I can confirm this as when I launch the following URL http://localhost:8080/CityManagerWebStarter/ it displays the index.html page as expected. 我确保查看URL时我的内容根目录正确,即/ CityManagerWebStarter,并且可以确认为启动以下URL http:// localhost:8080 / CityManagerWebStarter /时的情况,它按预期显示了index.html页。

Below is my servlet code and following that is my index.html code and ListCities.html is an example of a page I'm attempting to re-direct the user to: 以下是我的servlet代码,其后是我的index.html代码,而ListCities.html是我尝试将用户重定向到的页面示例:

servlet code: servlet代码:

package company.citymanagerweb.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MainMenuResponder
 */
@WebServlet("/CityManagerWebStarter/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
    private static final long serialVersionUID = 1L;

     /**
     * @see HttpServlet#HttpServlet()
     */
    public MainMenuResponder() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String userChoiceSelect = request.getParameter("menuChoice");
        String[] userOptionsCBox = request.getParameterValues("adminoptions");

        StringBuilder params = new StringBuilder();
        String queryStringParams = params.toString();

        if(userOptionsCBox != null) {
            boolean isFirst = true;

            for(int i = 0; i < userOptionsCBox.length; i++) {

                // Build URL with string query parameters i.e. URL + ? + PARAM1 + AMAPERSAND + PARAM2
                // Arguments is value of the value attribute
                if(!isFirst) {
                    params.append("&");
                } else {
                    params.append("?");
                }

                if(userOptionsCBox[i].equalsIgnoreCase("useDB")) {
                    // append() argument is value of the value attribute belonging to the input attribute
                    params.append("useDB=1");
                } else if(userOptionsCBox[i].equalsIgnoreCase("sendEmail")) {
                    params.append("sendEmail=1");                   
                }

                isFirst = false;
            }

            queryStringParams = params.toString();
        }

        if(userChoiceSelect.equals("1")) {
            response.sendRedirect("ListCities.html" + queryStringParams);
        } else if(userChoiceSelect.equals("2")) {
            response.sendRedirect("AddCity.html" + queryStringParams);
        } else if(userChoiceSelect.equals("3")) {
            response.sendRedirect("DeleteCity.html" + queryStringParams);
        } else {
            response.sendRedirect("index.html");
        }

    }

}

index.html: index.html:

<html>
    <head>
        <title>Welcome to the City Manager</title>
    </head>
</html>
<body>
    <form id="form1" method="post" 
            action="/CityManagerWeb/mainmenuresponder.do">
        <table style="width:100%">
            <tr>
                <td style="width:100%" align="center">
                    <h1>Welcome to the World City Manager</h1>
                </td>
            </tr>
            <tr>
                <td>
                    <h3>What would you like to do today?</h3>
                </td>
            </tr>
            <tr>
                <td>
                    <select id="menuChoice" name="menuChoice">
                        <option id="1" value="1">
                            List Cities
                        </option>
                        <option id="2" value="2">
                            Add a new city
                        </option>
                        <option id="3" value="3">
                            Delete a city
                        </option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" name="adminoptions" id="optionDatabase" value="useDB" />Use Database<br>
                    <input type="checkbox" name="adminoptions" id="optionEmail" value="sendEmail" />Send Confirmation<br>
                </td>
            </tr>
            <tr>
                <td>
                    <input name="chooser" type="submit" value="Choose" />
                </td>
            </tr>
        </table>
    </form>
</body>

ListCities.html: ListCities.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Listing Cities</title>
</head>
<body>
    <table style="width:450px;">
        <tr>
            <td style="width:150px;"><b>COUNTRY</b></td>
            <td style="width:300px;"><b>CITY</b></td>
        </tr>
        <tr>
            <td>Russia</td>
            <td>Moscow</td>
        </tr>
        <tr>
            <td>England</td>
            <td>London</td>
        </tr>
        <tr>
            <td>United States</td>
            <td>Washington, D.C.</td>
        </tr>
    </table>
</body>
</html>

web.xml: web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>CityManagerWebStarter</display-name>
  <servlet>
    <servlet-name>citymanagerwebstarter</servlet-name>
    <servlet-class>company.citymanagerweb.servlets</servlet-class>
  </servlet>  
  <servlet-mapping>
    <servlet-name>citymanagerwebstarter</servlet-name>
    <url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
  </servlet-mapping>  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Thanks for any suggestions/help. 感谢您的任何建议/帮助。

If citymanagerwebstarter is the content root. 如果citymanagerwebstarter是内容根。 It should not be part of the url parttern in web.xml and @WebServlet annotation. 它不应该是web.xml@WebServlet批注中url一部分的一部分。

A fairly common problem I'm seeing these days is that people are using the latest IDE tooling that generates their web projects using the Servlet 3.0 specification ie the files generated use the new @WebServlet , @WebFilter etc. annotations way of doing things against the traditional deployment descriptor web.xml . 我最近看到的一个相当普遍的问题是,人们使用的是最新的IDE工具,该工具使用Servlet 3.0规范来生成其Web项目,即,生成的文件使用新的@ @WebServlet ,@ @WebFilter等。传统部署描述符web.xml But, they follow these old Servlet 2.x tutorials online and end up configuring the same servlet twice; 但是,他们在线上遵循了这些旧的Servlet 2.x教程,最终两次配置了相同的servlet。 once with the annotations and once again in the web.xml . 一次带有注释,再次出现在web.xml This would lead to your server responding in undefined ways and must be avoided. 这将导致您的服务器以不确定的方式响应,因此必须避免。

So, you can safely get rid of the following from your web.xml : 因此,您可以放心地从web.xml删除以下内容:

<servlet>
    <servlet-name>citymanagerwebstarter</servlet-name>
    <servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>  
<servlet-mapping>
    <servlet-name>citymanagerwebstarter</servlet-name>
    <url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>

The next issue is that your web application's context root is never a part of your servlet or filter's url-pattern . 下一个问题是,Web应用程序的上下文根永远不会成为servlet或过滤器的url-pattern So, your annotation should be like 因此,您的注释应该像

@WebServlet("/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {

Lastly, though it works as is, your form 's action attribute shouldn't hard code the context root like that. 最后,尽管它按原样工作,但您的formaction属性不应这样硬编码上下文根 I suggest you use a relative URL there as well. 我建议您也使用一个相对URL。

<form id="form1" method="post" action="mainmenuresponder.do">

Notice, that unlike the servlets, you can't put a leading / in the action here. 请注意,这不像servlets时,你不能把领先/action这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM