Servlet
简介:Servlet就是sun公司开发动态web的一门技术
Sun在这些API中提供一个接口叫做:Servlet,有两个默认的实现类,HttpServlet
编写一个类,实现Servlet接口
把开发好的Java类部署到web服务器中
把实现了Servlet接口的Java程序叫做Servlet
HelloServlet
1.配置环境:
此电脑---->属性----->环境变量----->新建
JAVA_HOME,且找到它的路径
JRE_HOME,且找到它的路径
找到PATH---->编辑----->新建:%JAVA_HOME%\bin
然后一直按确认
例子:编写一个普通类ServletTest
package gdpiedu.cn;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/myServlet")
public class ServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("<table border ='1'>");
resp.getWriter().println("<tr><td>学号</td><td>姓名</td></tr>");
resp.getWriter().println("<tr><td>20210220527</td><td>测试</td></tr>");
resp.getWriter().println("</table>");
}
}
提示:若HttpServlet报错,就是没有sevrlet包,要先从外部导入,步骤如下
(注意:这个包是下载Tomcat自动附带的,若找不到,就是下载不完整,建议删除了再下一次)
2.配置Tomcat
在IDEA里面配置Tomcat
3.ServletContext
Web容器在启动的时候,他会为每一个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
例子:统计总共点击(不相同的)网页的数量
ServletContext_s1,如下;
package gdpiedu.cn;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/s1")
public class ServletContext_s1 extends HttpServlet {
@Override
public void init() throws ServletException {
ServletContext servletContext = getServletContext();
servletContext.setAttribute("count",1);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
int count = (int)servletContext.getAttribute("count");
resp.getWriter().write(""+count);
count++;
servletContext.setAttribute("count",count);
}
}
ServletContext_s2,如下:
package gdpiedu.cn;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/s2")
public class ServletContext_s2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext =this.getServletContext();
int count = (int)servletContext.getAttribute("count");
resp.getWriter().write(" "+count);
count++;
servletContext.setAttribute("count",count);
}
}