在平常开发项目中,总会遇到一些开发接口的工作,像http接口、webService接口等等,这些在工作中经常遇到。实现一个http接口可以通过servlet的方式,可以使用springmvc的注解去实现http接口服务,今天,主要讲一下通过servlet的方式实现http接口服务。
1:在web.xml中添加如下配置:
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>util.httpUtil.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/DemoServlet</url-pattern>
</servlet-mapping>
2:具体DemoServlet类的实现如下,重写doPost或者doGet方法,以下为重写doPost方法:
public class DemoServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedReader bufferedReader;
PrintWriter out;
String respString = "";
String reqString = "";
String inputStr = "";
try {
//1:接受入参,以下接受两种入参的方式二选一
bufferedReader = request.getReader();
bufferedReader = new BufferedReader( new InputStreamReader(req.getInputStream(), "UTF-8"));
StringBuilder requestStrBuilder = new StringBuilder();
while ((inputStr = bufferedReader.readLine()) != null) {
requestStrBuilder.append(inputStr);
}
reqString = requestStrBuilder.toString();
System.out.println("入参数据为:"+reqString);
//2:逻辑处理
respString = "200";
//3:返回数据
response.setContentType("text/plain;charset=UTF-8");
out = response.getWriter();
out.write(respString);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
PrintWriter out;
//1:接受入参
String id = request.getParameter("id");
String name = request.getParameter("nme");
System.out.println("入参id:"+id+",name:"+name);
//2:逻辑处理
String returnCode = "200";
//3:返回数据
response.setContentType("text/plain;charset=UTF-8");
out = response.getWriter();
out.write(returnCode);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上为通过servlet的方式实现,重写post和get方法,两个获取参数的方法不用。get请求是将参数直接拼在链接后面,所以不能用get请求能传递敏感的信息,安全性不好;post请求参数是隐藏的,用户不可见,所以post请求是相对比较安全的;get提交的数据大小有限制,post对提交数据大小没有限制。
servlet方式实现一个http接口代码如上,实现过程相对比较简单,主要就是在项目中实现具体的业务。