Servlet
- Servlet (Servlet Applet)服务器小程序,主要功能用于生成动态Web内容
- Servlet是J2EE最重要的组成部分,也是我们学习的重点
Servlet开发步骤
- 创建Servlet类,继承HttpServlet
- 重写service方法,编写程序代码
- 配置web.xml,绑定URL
创建Servlet类,继承HttpServlet
IDEA项目中选择:new -> Servlet
如果没有new Servlet的情况,请参考以下内容:
附录:IDEA配置Web相关问题解决方案 ```java package com.ouchaochao;
import javax.servlet.; import javax.servlet.http.; import javax.servlet.annotation.*; import java.io.IOException; import java.io.PrintWriter;
@WebServlet(name = “hello”, value = “/hello”) public class helloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<a name="HvvNC"></a>
### 重写service方法,编写程序代码
```java
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); // 向浏览器输出数据流
out.println("<a href='https://www.baidu.com'>Baidu</a>");
}
配置web.xml,绑定URL
在web.xml中使用鼠标右键选择Generate,生成Servlet(快捷键Alt+Insert)
选择写好的Servlet,点击确定即可
在代码中填入
<?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">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.ouchaochao.helloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
配置Tomcat
运行
文末
恭喜你,到目前这一步为止,你已成功入门Servlet,请继续加油!