我正在尝试从jsp文件调用servlet,以执行业务逻辑并返回同一页面

时间:2018-09-18 11:08:22

标签: java eclipse maven jsp servlets

我的项目结构如下

enter image description here

这是我的jsp

<%@taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h2>Binary Search</h2>

<form action ="SearchServlet" method = "post">
<label>Enter size of the list</label>
<input type="text" name ="listSize"><br><br>

<label>Here is your Generated list...!!!</label><br><br>
<textarea rows="10" cols="50"><c:out value="${list}"/> </textarea><br><br>

<label>Enter number to search in the list</label>
<input type="text" name ="searchNumber"><br><br>

<button type="submit" name="button" value="generate">Generate List</button>
<button type="submit" name="button" value="search">Search Number</button>
<button type="reset" name="button" value="reset">Reset</button>

</form>


</body>
</html>

因此,当我单击“生成列表”按钮时,我希望它重定向到我的servlet并执行我的逻辑并返回arraylist以在文本区域中显示它。

这是我的servlet

public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public SearchServlet() {
    super();
    // TODO Auto-generated constructor stub
}

protected void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {
    GenerateList newList = new GenerateList();
    SearchList searchList = new SearchList();
    String button = request.getParameter("button");

    ArrayList<Integer> newGeneratedList = new ArrayList<Integer>();

    if ("generate".equals(button)) {
        newGeneratedList = newList.GeneratedList(Integer.parseInt(request.getParameter("listSize")));
        request.setAttribute("list",newGeneratedList);
        response.sendRedirect("index.jsp");

    } else if ("search".equals(button)) {

    }
    //doGet(request, response);
}

}

但是单击此按钮时我得到404 not found错误。我搜索了几个小时,找不到原因,而且我仍然是servlet的初学者。任何潜在客户/帮助都很好。

这也是我的web.xml     

<web-app>
 <display-name>Archetype Created Web Application</display-name>

<servlet>
 <servlet-name>SearchServlet</servlet-name>
 <display-name>SearchServlet</display-name>
 <description></description>
 <servlet-class>SearchServlet</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>BinarySearchServlet</servlet-name>
 <url-pattern>/binarySearchServlet</url-pattern>
</servlet-mapping>

1 个答案:

答案 0 :(得分:0)

您可以在Servlet中使用请求分派器代替sendRedirect。

尝试一下:

 RequestDispatcher rd=request.getRequestDispatcher(jspName);
 rd.forward(request, response);

在参数中,从调用此servlet的地方输入您的JSP名称。 转发功能将重定向到您所需的页面。