Java 使链接转到 servlet 以重定向到另一个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22771347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:47:41  来源:igfitidea点击:

Making link go to servlet to redirect to another page

javajspjakarta-eeservlets

提问by user3457789

SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.

所以首先让我首先说我的 servlet 以一种我很好的形式加载选项列表。问题是当我像我想要的那样从 index.jsp 开始时,列表不会加载。所以基本上,我想单击 index.jsp 上的链接将我带到 servlet,然后根据单击的链接将我重定向到正确的页面。也许我已经看这个太久了,只需要新的眼睛,但我不明白为什么它不起作用。

I have included my Index.jsp and servlet

我已经包含了我的 Index.jsp 和 servlet

Index.jsp

索引.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.ArrayList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>



    <form method="get" action="customerServlet">


        <a href="customerServlet?addCustomer">Add Customer</a>
    <br/>
    <a href="customerServlet?addPet">Add Pet</a>
    </form>


</body>
</html>

Servlet

小服务程序

package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;




import javax.servlet.http.HttpSession;

import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;


@WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public CustomerServlet() {
        super();
    }


    private void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        HttpSession session = request.getSession();


        Phone phone = new Phone();
        States state = new States();


        Collection<Phone> phones = phone.getPhoneCollection();
        Collection<States> states = state.getStateCollection();

            session.setAttribute("phones", phones);
            session.setAttribute("states", states);
            request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
        //}

    }







    private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();



 private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
           throws IOException, ServletException {
    String url = "/customerManagement.jsp";
    processRequest(request, response);
        request.getRequestDispatcher(url).forward(request,response);
    }

 private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
         throws IOException, ServletException {
    String url = "/pets.jsp";
    request.getRequestDispatcher(url).forward(request,response);
  }




    private Customer getCustomer(int customerId) {
        for (Customer customer : customers) {
            if (customer.getCustomerId() == customerId) {
                return customer;
            }
        }
        return null;
    }



    private void sendEditCustomerForm(HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {

        String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);
    }



    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
         String uri = request.getRequestURI();
         if (uri.endsWith("/addCustomer")) {
             addCustomer(response, request);
         } else if (uri.endsWith("/addPet")) {
             addPet(response, request);
         }

    }


    public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
         processRequest(request, response);

        // update customer
        int customerId = 0;
        try {
            customerId = 
                    Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
        }
        Customer customer = getCustomer(customerId);
        if (customer != null) {
            customer.setFirstName(request.getParameter("firstName"));
            customer.setLastName(request.getParameter("lastName"));
            customer.setEmail(request.getParameter("email"));
            customer.setPhone(request.getParameter("phone"));
            customer.setAddress(request.getParameter("address"));
            customer.setCity(request.getParameter("city"));

            customer.setZip(request.getParameter("zip"));
        }

    }
}

采纳答案by developerwjk

It would be easier to use one parameter and check the value than to manually parse the URL:

使用一个参数并检查值比手动解析 URL 更容易:

<a href="customerServlet?action=addCustomer">Add Customer</a>
<br/><a href="customerServlet?action=addPet">Add Pet</a>

In your servlet:

在您的 servlet 中:

String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }

回答by Naoto Aguilar Morita

if you are using "forms", this could be the solution to send params to servlet.

如果您使用“表单”,这可能是将参数发送到 servlet 的解决方案。

 <form action="ServletName" method="POST">
     <input type="text" name="paramName">
     <input type="submit" value="Add">
    </form>

In Servlet:

在 Servlet 中:

String costumerName = request.getParameter("paramName");

If you just use a link like href, you should send the param like:

如果您只使用 href 之类的链接,则应发送如下参数:

<a href="ServletName?ID=12345">

In servlet, same.

在 servlet 中,相同。

String costumerName = request.getParameter("ID");