我正在创建一个web servlet,目前由php访问,使用: $ payload = file_get_contents('http://localhost:8080/HelloWorldServlet/index?name=Joe&age=24');
这将调用在我的tomcat服务器上运行的HelloWorldServlet Web应用程序 使用/ index的url模式。 为servlet调用doGet()。 doGet()方法将数据写入json,作为响应.. 我的问题是如何将json发送回php,只是为了显示它? 此外,php应用程序正在端口8888上运行。
以下是doGet的代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//GsonBuilder builder = new ();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
response.setContentType("application/json; charset=UTF-8");
String key = request.getParameter("name");
String value = request.getParameter("age");
String jsonString = gson.toJson(new Tuple(key, value)).toString();
request.setAttribute("data", jsonString);
//response.sendRedirect("localhost:8888/MYPHPAPPLICATION/testcall.php");
try {
getServletConfig().getServletContext().getRequestDispatcher(
"/display.jsp").forward(request,response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
另外,我创建了一个过滤器,用于在尝试转发到php页面时更改请求。 但它没有按预期工作。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
String requestURI = request.getRequestURI();
if (requestURI.contains("display.jsp"))
{
String toReplace = "localhost:8888/MYPHPAPPLICATION/testcall.php";
req.getRequestDispatcher(toReplace).forward(req, res);
} else
chain.doFilter(req, res);
}
这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HelloWorldServlet</display-name>
<servlet>
<description></description>
<servlet-name>HelloWorldServlet2</servlet-name>
<servlet-class>com.srccodes.example.HelloWorld</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet2</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>com.srccodes.example.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
答案 0 :(得分:3)
只需将其写入响应正文并立即返回。
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
String jsonString = gson.toJson(new Tuple(key, value)).toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonString);
}
您不需要JSP。它主要用作HTML输出的模板。