手把手带你走进javaweb
从环境安装到代码实操,从小白到入门的实操讲解
一. java运行环境jdk的安装
不造重复的轮子原则,具体看牛客网的安装基础教程:
jdk安装及基础:https://www.nowcoder.com/tutorial/10001/244d6df8a4ea40748ec0e5eaa7f3c3da
二.javaweb的开发工具准备
tomcat: 官网下载解压即可:https://tomcat.apache.org/
IDEA: https://blog.csdn.net/lxqasn/article/details/106563851
Maven:https://blog.csdn.net/weixin_43811057/article/details/108235117
避免每次在idea新建maven项目时都需要选择maven(默认是idea自带的maven),需要配置一下idea的设置
三.第一个javaweb程序
开发工具都准备好了,下面开始写第一个javaweb程序:
1.启动idea
2.新建一个webapp的maven项目
其实,新建项目后,就可以启动一个web项目了,系统默认生成了一个index.jsp,访问
http://localhost:8080/就可以跳到这个页面了
3.编写servlet基本程序代码
3.1 替换web.xml的头部web-app
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">
</web-app>
3.2 pom.xml导入相关的servlet的jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.king</groupId>
<artifactId>javaweb01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.3 新建一个类,继承HttpServlet并重写(Ctrl+o)doPost和doGet方法
public class ServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setHeader("Content-Type","text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.write("我是响应内容test");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3.4 web配置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"
metadata-complete="false">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.king.ServletTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
</web-app>
3.5 运行项目,效果如图: