创建一个web项目,添加一个HelloServlet类
1、导入两个maven依赖,因为类中继承了HttpServlet,所以要有对应的jar包
没有可以去maven仓库中下载
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<!-- <scope>provided</scope>--> <!-- scop这个标签表示作用域,把它删掉后什么地方都能使用 -->
</dependency>
2、填写HelloServlet类的内容
//有pom的javax.servlet依赖,才能使用HttpServlet
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//响应类型
response.setContentType("text/html");
//编码格式,不设置浏览器默认是charset=ISO-8859-1
response.setCharacterEncoding("utf-8");
//获取响应输出流
PrintWriter printWriter =response.getWriter();
printWriter.println("<html>");
printWriter.println("<hear>");
printWriter.println("<title>");
printWriter.println("你好");
printWriter.println("</title>");
printWriter.println("</hear>");
printWriter.println("<body>");
printWriter.println("Hello,World,你好");
printWriter.println("</body>");
printWriter.println("</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp); //这样不管是post请求还是get请求都是进入doGet方法了
}
}
3、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.xml中是配置我们核心web应用 -->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.wuzhy.servlet.HelloServlet</servlet-class><!-- 类路径 -->
</servlet>
<!-- 一个Servlet对应一个mapping映射 -->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
浏览器访问结果
结合动态web流程图思考
标签:web,printWriter,dome,response,简单,println,servlet,javax From: https://www.cnblogs.com/wuzhy/p/17375700.html