使用java EE 即 servlet 搭建一个简单的web后台,返回json数据
java代码:
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 VueServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
String resJSON = "[{id:1, name:‘奔驰’},{id:2, name:‘宝马’}]";
out.print(resJSON);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
使用HTTPServlet类需要导入 javax.servlet.jar jar包,若是使用MyEclipse创建的web项目会有选择java EE version选项,选择之后会自动导入java ee library 会包含 javax.servlet.jar jar包。若其他创建方式没有自动导入 javax.servlet.jar jar包,可以在Tomcat 的lib目录下找到,并导入,或在网上下载。
创建好servlet之后需要在web.xml文件中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Vue</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- servlet配置的名称,可任意命名 -->
<servlet-name>vueServlet</servlet-name>
<!-- 需要配置的servlet的全限定类名 -->
<servlet-class>com.hyt.servlet.VueServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- 需要与上面配置的servlet名称一致 -->
<servlet-name>vueServlet</servlet-name>
<!-- 触发servlet的URL后缀 -->
<url-pattern>/vueServlet</url-pattern>
</servlet-mapping>
</web-app>
部署到Tomcat之后,在浏览器输入正确的URL则可以正常访问