[英]calling a servlet from a java class
在測試簡單Java類中調用servlet時遇到問題。 我想將參數與Servlet一起傳遞,該方法將為POST。 如何實現?
在搜索答案時,我看到有人推薦了HTTPClient。 但是,只是想知道是否有避免這種情況的方法。
您要做的就是請求一個URL。 像平常一樣放置所有名稱,值對,並在其上打開流。
這里是示例代碼:
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中的字符串
Servlet容器負責初始化和調用Servlet。 您不能直接調用servlet類。
要發布請求,可以使用HttpClient。
或者您可以使用
使用以下代碼。使用此代碼,您還可以維護會話。
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);
}
%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.