1、写法:
```
@WebServlet(urlPatterns = "/hello")
public class Servlet01 extends HttpServlet {
@Override
//请求,响应
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
System.out.println(req.getParameter("name"));
System.out.println(req.getParameter("password"));
System.out.println("hello,world");
System.out.println("你好,世界");
//向浏览器返回信息的方法
res.setContentType("byte/html;charset=utf-8");
res.getWriter().println("<html><body>hello,world</body></html>
//返回中文,写法格式固定
res.setContentType("text/html;charset=utf-8");
res.getWriter().println("<html><body>你好,世界</body></html>
2、生命周期
```
@WebServlet(urlPatterns = "/hello2")
//构造方法和初始化方法只执行一次,先构造
//再初始化,service请求几次,就执行几次
//销毁destory方法只执行一次
public class Servlet2 extends HttpServlet {
public Servlet2(){
System.out.println("我是构造方法");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("我是service方法");
}
@Override
public void init() throws ServletException {
System.out.println("我是初始化方法");
}
@Override
public void destroy() {
System.out.println("我是销毁方法");
}
}
```
3、操作数据库(查询显示)
```
@WebServlet(urlPatterns = "/hello4")
public class Servlet4 extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static final String U="jdbc:mysql://localhost:3306/ku1?serverTimezone=GMT%2B8&useSSL=false";
static String username="root";
static String password="9315";
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
try {
Connection conn=Utils.connection();
PreparedStatement stmt=conn.prepareStatement("select tid,tname from teacher");
ResultSet rs=stmt.executeQuery();
ArrayList<Teacher> list = new ArrayList<>();
//1、将查询结果放入list集合
while (rs.next()){
list.add(new Teacher(rs.getInt("tid"),rs.getString("tname")));
}
//2、将list集合放入req作用域
req.setAttribute("list",list);
rs.close();
stmt.close();
conn.close();
//3,执行跳转,控制权交给jsp
req.getRequestDispatcher("homework.jsp").forward(req,res);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
```
<%--
Created by IntelliJ IDEA.
User: 召凯
Date: 2018/9/14
Time: 18:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*,web.Teacher" %>
<%@ page import="web.Teacher" %>
<%@ taglib prefix="b2" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--<%
ArrayList<Teacher> list = new ArrayList<Teacher>();
list.add(new Teacher(6, "张强"));
list.add(new Teacher(7, "张亮"));
list.add(new Teacher(8, "李亮"));
pageContext.setAttribute("list", list);
%>--%>
<table>
<tbody>
<b2:forEach items="${list}" var="i">
<tr>
<td>${i.tid}</td>
<td>${i.tname}</td>
</tr>
</b2:forEach>
</tbody>
</table>
</body>
</html>
```