servelet 实现Post接口访问
先上代码:
package com.jovtec.galaxy.mailbox; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import com.jovtec.galaxy.object.SysObject; import com.jovtec.galaxy.util.DateHelper; public class MailboxAction extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * 覆盖Get方法 */ @SuppressWarnings("unchecked") public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); // 返回JSON数据 JSONObject resultObject = new JSONObject(); // 获取post提交的回复案件的信息 String postResult = reqMailbox(request); //实现逻辑... response.getOutputStream().write(resultObject.toString().getBytes("UTF-8")); } /** * 获取请求头内容 * * @param request * @return * @throws IOException */ private String reqMailbox(HttpServletRequest request) throws IOException { // 读取请求内容 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } // 将资料解码 return sb.toString(); } /** * 跳转到Get方法 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
1.首先,先继承HttpServlet,获取post请求的参数。
2.需要在web.xml里面做相应的配置,配置如下:
<servlet>
<servlet-name>MailboxAction</servlet-name>
<servlet-class>com.jovtec.galaxy.mailbox.MailboxAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MailboxAction</servlet-name>
<url-pattern>/mailbox/MailboxAction</url-pattern>
</servlet-mapping>
访问接口的路径,就是项目路径+/mailbox/MailboxAction
完~