从JSP发送数据到Servlet时出错

时间:2014-02-06 09:31:09

标签: java jsp servlets

我正在使用Dynamic Web Project。 这是我的JSP代码。我正在尝试将Hello发送给servlet

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
  pageEncoding="ISO-   
  8859-1"%>
  <!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>
   <jsp:include page="/servlet/ServletCode" flush="true" >
   <jsp:param name="username" value="Hello" />
   </jsp:include>
   </body>
   </html>

这是我的Servlet文件。

package pack.exp;

public class ServletCode extends HttpServlet 
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{
    String output= request.getParameter("username");
    System.out.println(output);
     PrintWriter pw = response.getWriter();
     pw.println("Hello " + output);
}
}

在我的JSP文件中,我在此行上收到此编译时错误。

在预期的路径/ JSpServletCode / WebContent / servlet / ServletCode中找不到片段“/ servlet / ServletCode”

请帮帮我。

2 个答案:

答案 0 :(得分:1)

我认为您必须在web.xml中映射您的servlet,并在页面中提供您必须提供的servlet-url。像下面这样的东西可以工作。

<jsp:include page="/ServletCode" flush="true" > 

 <servlet>
         <servlet-name>Servlet1</servlet-name>
         <servlet-path>pack.exp.ServletCode</servlet-path>
    </servlet>
    <servlet-mapping>
         <servlet-name>Servlet1</servlet-name>
         <url-pattern>/ServletCode</url-pattern>
    </servlet-mapping>

<强>更新

这对我有用

<强> SERVLET

 @WebServlet("/ServletCode")
  public class ServletCode extends HttpServlet {
  private static final long serialVersionUID = 1L;

    public ServletCode() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String output= request.getParameter("username");
            System.out.println(output);
             PrintWriter pw = response.getWriter();
             pw.println("Hello " + output);
        }
}

<强> JSP

<body>
    <jsp:include page="/ServletCode" flush="true">
        <jsp:param name="username" value="Hello" />
    </jsp:include>
</body>

答案 1 :(得分:0)

这是模型servlet页面:

<servlet>
    <servlet-name>registerServlet</servlet-name>
    <servlet-class>com.example.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>registerServlet</servlet-name>
    <url-pattern>/register</url-pattern>
</servlet-mapping>

您必须更改此格式的表单:

<form action="register" method="post">

这是Post方法:

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter("uname");
 PrintWriter pw = response.getWriter();
     pw.println("Hello " + output);
System.out.println(output); 
       // ...
    }