Servlet
sun公司开发的动态web技术,把实现Servlet接口的java程序叫做Servlet。
1. 实现Servlet
-
构建一个非模板Maven项目
-
删掉src目录,以后学习就在这个项目里建Moudel;这个空工程就是Maven主工程。
-
导入依赖
-
创建子工程,这个工程使用webapp模板;
tips:父项目有models标签;子项目有parent标签;
-
Maven环境优化
<!--修改web.xml为最新版--> <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> </web-app> -
编写一个普通的Servlet程序类;
- 这个程序是HttpServlet的子类
- HttpServlet实现了Servlet接口;
public class simpleClass extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**字节输出响应流
个人理解:这个类实现了Servelet接口,而Servlet接口的目的就是服务器执行相关的流程步骤,即获得请求,输出数据流,下面的write就是打印输出流,输出给浏览器端?*/
PrintWriter writer = resp.getWriter();
writer.println("hello Servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
-
编写Servlet的映射
为什么需要映射?
老师解释:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给web服务器一个浏览器能够访问的路径。
个人理解:浏览器连接web服务器后,浏览器获得一个路径用来接受数据,这个路径就是Servlet映射。
-
配置tomcat
-
启动测试
-
如果需要请求动态网页,还需要使用mysql,此时使用JDBC,代码写在java程序中.
-
HttpServletResponse接口
- 文件存放在哪里?来自于Servlet规范中,在tomcat中存在于servlet-api中。
- 谁提供的?http服务器提供。
- 有什么用?负责将doGet/doPost方法执行结果写到响应体交给浏览器。
- 其修饰的对象可以理解为(响应对象)。
- 主要功能是什么?
- 将执行结果以二进制写入响应体
- 设置响应头中【content-type】属性值,从而使浏览器使用对应编译器来将数据编译成 text,jpg,mp4,order等等形式。
- 设置将响应头中【location】属性,从而使浏览器向指定服务器发送请求。
public class oneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Connect success");
resp.setContentType("text/HTML;charset=GBK");//设置响应头页面响应和字符集格式
PrintWriter writer = resp.getWriter();//输出流
resp.sendRedirect("http://baidu.com");//发起重定向,跳转到指定的页面
writer.print("你已成功连接我的网站<br/>Show The Page On Browser<br>我决定换行啦");
}
- HttpServletRequesr接口
- 文件存放在哪里?来自于Servlet规范中,在tomcat中存在于servlet-api中。
- 谁提供的?http服务器提供。
- 有什么用?负责在doGet/doPost方法执行时,读取http请求协议包中的信息。
- 其修饰的对象可以理解为(请求对象)。
- 主要功能是什么?
- 读取http请求协议包中的数据
- 读取保存在http请求协议包中请求头或者请求体中的参数数据
- 替代浏览器向http服务器申请文件调用

浙公网安备 33010602011771号