从java类调用servlet

时间:2013-12-04 06:17:09

标签: java servlets

我在一个简单的java类中调用servlet以进行测试时遇到了问题。我想传递一个参数和servlet,方法将是POST。如何实现?

在搜索答案时,我看到有人推荐了HTTPClient。但只是想知道是否有办法避免这种情况。

3 个答案:

答案 0 :(得分:0)

您所要做的就是申请一个网址。按照通常的方式放置所有名称,值对,然后在其上打开一个流。

这里是示例代码:

import java.io.*; 
import javax.servlet.http.*; 
import javax.servlet.*;

public class SpecialServlet extends HttpServlet 
{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{ 
    PrintWriter out = res.getWriter(); 
    out.println ("Hello " + req.getParameter("name") + ", this is SpecialServlet!"); 
    out.close(); 
}
} 

java程序:

import java.net.*; 
import java.io.*; 

public class CmdLineApplication
{
public static void main (String args[])
{
String line;
try
{
URL url = new URL( "http://127.0.0.1/servlet/special?name=CmdLineApplication" );
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
System.out.println( line );
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

将servlet .class文件放在servlet引擎的WEB-INF/classes目录中。以通常的方式在命令行上运行另一个类:

java CmdLineApplication

您应该看到来自servlet的字符串

答案 1 :(得分:0)

servlet容器负责初始化和调用servlet。你不能直接调用servlet类。

要发布请求,您可以使用HttpClient。

Apache HTTPClient

或者您可以使用

URLConnection

答案 2 :(得分:0)

使用以下代码。使用此代码,您也可以维护会话。

package webapp;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;


public class HttpClientSingleton {
    public static HttpClientSingleton mSingleton = null;

    public static HttpClient mHttpClient = null;

    //constructor
    private HttpClientSingleton(){
    mHttpClient = new DefaultHttpClient();
    }

    public static HttpClientSingleton getInstance(){
    if( mSingleton == null ){
        mSingleton = new HttpClientSingleton();
    }
    return mSingleton;
    }



}

jsp file:

<%
try{
    int i=0;
String sid = "ED6379C8FDDB801EB970BBDE55E5732D"; 
HttpClientSingleton h1 = HttpClientSingleton.getInstance();
HttpClient client= h1.mHttpClient;


HttpPost responses = new HttpPost("http://localhost:8080/docinbangalore/Billing_address_display?sid="+sid+"");
try {

    HttpResponse respons = client.execute(responses);
    BufferedReader rd = new BufferedReader(new InputStreamReader(respons.getEntity().getContent()));
    String line = "";
    out.println(line = rd.readLine());
    while ((line = rd.readLine()) != null) {
     out.println(line);

    }
  } catch (IOException e) {
    e.printStackTrace();
  }}
catch(Exception e)
{
    out.println(e);
}

%>