<!--设置打包方式为 war 方式 --> <packaging>war</packaging> <!-- 设置 maven 的编译器版本是 1.8 --> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <!-- 添加 servlet 依赖 scope = provided表示这个依赖下的所有类只在开发、构建需要,运行时 Tomcat 内部已经有这套类了 --> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies>
查找标准的依赖写法:https://search.maven.org/artifact/javax.servlet/javax.servlet-api/3.1.0/jar
<?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_3_1.xsd" version="3.1"> </web-app>
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; import java.io.PrintWriter; /* 1. 继承 HttpServlet 抽象类 2. 通过 @WebServlet 注解,修饰类,填写资源路径,必须以 / 开头 3. 重写 doGet(...) 方法 */ @WebServlet("/first") public class FirstServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* 1. 设置响应头 Content-Type: */ resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); /* 2. 准备响应的正文部分 */ String s = "你好中国"; /* 3. 拿到写入正文的 writer */ PrintWriter writer = resp.getWriter(); /* 4. 写入正文 */ writer.println(s); } }
context path
编译(build)----》打包(Package)----》部署(deploy)
也可以使用 build artifact
使用专业版 IDEA 自带 Tomcat 插件启动
<form method="post" action="method"> <button>通过 post 访问</button> </form>
public class method extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("运行到这里"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); resp.getWriter().println("我是处理 method 的 POST 方法的"); } }
resp.setStatus(200)
。resp.setCharacterEncoding("utf-8");resp.setContentType("text/plain");
text/html、text/css、application/javascript、application/json。resp.getWriter().println();
package com.cc.servlet; 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; import java.io.PrintWriter; @WebServlet("/get-param") public class GetParam extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); String age = req.getParameter("age"); System.out.printf("name = %s, age = %s\n",name, age); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); writer.printf("name = %s, age = %s\n",name, age); } }
<form method="post" action="post-param"> <input type="text" name="name"> <input type="text" name="age"> <button>提交</button> </form>
@WebServlet("/post-param") public class PostParam extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); String age = req.getParameter("age"); System.out.printf("name = %s, age = %s\n", name, age); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); writer.printf("name = %s, age = %s\n",name, age); } }
req.setCharacterEncoding("utf-8");String name = req.getParameter("name");String[] names = req.getParameterValues("name");
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
package com.cc.servlet; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; 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; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @WebServlet("/user-list.txt") public class UserListServlet extends HttpServlet { //使用 text/plain 形式显示 // 通过添加打印信息, 观察中间过程的数据正确性 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { List<User> userList = queryFromDB(); System.out.println(userList); String responseBody = userListToString(userList); System.out.println(responseBody); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); writer.println(responseBody); } catch (SQLException exc) { // 由于 SQLException 不在方法签名可以抛的异常列表内,并且不能更改方法签名,否则就不是方法重写了 throw new ServletException(exc); } } private String userListToString(List<User> userList) { StringBuilder sb = new StringBuilder(); for (User user : userList) { sb.append(user.toString()); sb.append("\r\n"); } return sb.toString(); } private List<User> queryFromDB() throws SQLException { List<User> userList= new ArrayList<>(); MysqlDataSource db = new MysqlDataSource(); db.setServerName("127.0.0.1"); db.setPort(3306); db.setUser("root"); db.setPassword("123456"); db.setDatabaseName("db_12_28"); db.setUseSSL(false); db.setCharacterEncoding("utf8"); db.setServerTimezone("Asia/Shanghai"); try (Connection c = db.getConnection()) { String sql = "SELECT uid, name, age FROM users ORDER BY uid ASC"; try (PreparedStatement ps = c.prepareStatement(sql)) { System.out.println(ps); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { User user = new User( rs.getInt("uid"), rs.getString("name"), rs.getInt("age") ); userList.add(user); } } } } return userList; } }
User.java
package com.cc.servlet; public class User { public Integer uid; public String name; public Integer age; public User(Integer uid, String name, Integer age) { this.uid = uid; this.name = name; this.age = age; } @Override public String toString() { return "User{" + "uid=" + uid + ", name='" + name + '\'' + ", age=" + age + '}'; } }
package com.cc.servlet; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; 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; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @WebServlet("/user-list.html") public class UserListHtmlServlet extends HttpServlet { // 用 text/html 形式显示 // 通过添加打印信息, 观察中间过程的数据正确性 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { List<User> userList = queryFromDB(); System.out.println(userList); String responseBody = userListToString(userList); System.out.println(responseBody); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); writer.println(responseBody); } catch (SQLException exc) { // 由于 SQLException 不在方法签名可以抛的异常列表内,并且不能更改方法签名,否则就不是方法重写了 throw new ServletException(exc); } } // 以 table 形式展示 private String userListToString(List<User> userList) { StringBuilder sb = new StringBuilder("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>用户列表</title>\n" + " <link rel=\"stylesheet\" href=\"css/style.css\">\n" + "</head>\n" + "<body>\n"); sb.append("<table border=\"1\">\n"); for (User user : userList) { sb.append("<tr>\n"); sb.append("<td>").append(user.uid).append("</td>\n"); sb.append("<td>").append(user.name).append("</td>\n"); sb.append("<td>").append(user.age).append("</td>\n"); sb.append("</tr>\n"); } sb.append("</table>"); sb.append("</body>\n" + "</html>"); return sb.toString(); } private List<User> queryFromDB() throws SQLException { List<User> userList= new ArrayList<>(); MysqlDataSource db = new MysqlDataSource(); db.setServerName("127.0.0.1"); db.setPort(3306); db.setUser("root"); db.setPassword("123456"); db.setDatabaseName("db_12_28"); db.setUseSSL(false); db.setCharacterEncoding("utf8"); db.setServerTimezone("Asia/Shanghai"); try (Connection c = db.getConnection()) { String sql = "SELECT uid, name, age FROM users ORDER BY uid ASC"; try (PreparedStatement ps = c.prepareStatement(sql)) { System.out.println(ps); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { User user = new User( rs.getInt("uid"), rs.getString("name"), rs.getInt("age") ); userList.add(user); } } } } return userList; } }
使用结构化方式进行输出,结构化的方式有很多。结构化实际上是对象序列化的一种。
JSON是一种基于文本的轻量级的数据交换格式可以被任何编程语言读取和作为数据的格式传递。
JS 对象格式
{ “key1”:“value1”, “key2”:“value2” }
数组格式
[ “item1”,“item2” ]
使用 java 中的第三方库来完成:
导入依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency>
package com.cc.servlet; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; 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; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @WebServlet("/user-list.json") public class UserListJSONServlet extends HttpServlet { //使用 text/plain 形式显示 // 通过添加打印信息, 观察中间过程的数据正确性 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { List<User> userList = queryFromDB(); System.out.println(userList); String responseBody = userListToString(userList); System.out.println(responseBody); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); writer.println(responseBody); } catch (SQLException | JsonProcessingException exc) { // 由于 SQLException 不在方法签名可以抛的异常列表内,并且不能更改方法签名,否则就不是方法重写了 throw new ServletException(exc); } } private String userListToString(List<User> userList) throws JsonProcessingException { ObjectMapper om = new ObjectMapper(); return om.writerWithDefaultPrettyPrinter().writeValueAsString(userList); } private List<User> queryFromDB() throws SQLException { List<User> userList= new ArrayList<>(); MysqlDataSource db = new MysqlDataSource(); db.setServerName("127.0.0.1"); db.setPort(3306); db.setUser("root"); db.setPassword("123456"); db.setDatabaseName("db_12_28"); db.setUseSSL(false); db.setCharacterEncoding("utf8"); db.setServerTimezone("Asia/Shanghai"); try (Connection c = db.getConnection()) { String sql = "SELECT uid, name, age FROM users ORDER BY uid ASC"; try (PreparedStatement ps = c.prepareStatement(sql)) { System.out.println(ps); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { User user = new User( rs.getInt("uid"), rs.getString("name"), rs.getInt("age") ); userList.add(user); } } } } return userList; } }