【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
//测试类如下
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ClientTest {
//定义servlet路径,MyServlet是工程名字,自己可以修改
private static String path="http://localhost:8080/MyServlet/QueryServlet";
public static void main(String[] args) throws Exception {
URL url =new URL(path);
//接收servlet返会值,是字节
InputStream is=url.openStream();
//由于is是字节,所以我们要把它转换为String类型,否则遇到中文会出现乱码
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
//输出servlet返回值
System.out.println(sb);
}
}
//servlet类如下:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost");
//解决乱码问题,必须放在最前面
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//接收穿过来的值
//req.getAttribute(arg0);
PrintWriter out=resp.getWriter();
//content可以servlet访问方法返回的值
String content="我爱祖国天安门";
//返回值到客户端
out.write(content);
}
}
来源:oschina
链接:https://my.oschina.net/u/2293326/blog/752687