我如何从servlet调用类java类

时间:2014-05-09 11:53:25

标签: gwt

我有一个html页面,你好是我的servlet

 <html>
 <body>
 <form action="http://localhost:8080/nitin/jsnipop/hello" method="post">
   <input type="text" id="foo" name="foo">
 <input type="submit" value="Send" name="submit" id="submit">
</form>
 </body>
 </html>

我的servlet是

public class hello  extends HttpServlet{
/**
 * 
 */
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
    res.setContentType("text/html");
    PrintWriter pw=res.getWriter();
    String foo=req.getParameter("foo");   
    pw.println("Welcome "+foo);
}
}

现在我想在客户端发送foo字符串变量并将其设置为用户名 我的客户端类名是ser.java 请帮忙

1 个答案:

答案 0 :(得分:0)

注意:

  • 一旦将请求转发给其他人,请在响应流中写入任何内容。

以下行没有意义:

pw.println("Welcome "+foo);

因为现在响应是由转发的JSP / Servlet / HTML驱动的。

  • 客户端和服务器之间共享的类必须放在共享文件夹下。

要遵循的步骤:

  • 创建一个Model类的对象,该对象位于共享文件夹下,只是一个POJO类。
  • 在对象中设置属性,例如username等。
  • 将对象设置为request attribute
  • 将请求转发给其他人
  • 只需在转发的JSP / Servlet中阅读。

请查看下面的设置链接并获取请求属性


示例代码:

hello Servlet(服务器端)

// get the parameter from the request
String foo=req.getParameter("foo");

// create an object of Model class
Model model = new Model();

// Set the properties in the object
model.setUserName(foo);

// set the object as request attribute
req.setAttribute("model",model);

// forward the request to some one else
rd.forward(req, res); 

在转发的JSP中(使用Scriplets)

<!-- Simply read it here -->
<%com.x.y.shared.Model model = request.getAttribute("model");%>

模型类(共享文件夹)

public class Model implements IsSerializable, Serializable{
    private String userName;

    public Model(){} // no-arg constructor
    // getter & setter
}
相关问题