个人源码:码云源码
新建一个maven项目
按照教材上的过程即可
搭建web项目框架
转为java web项目
将maven项目调整为web项目结构
需要三步即可实现:
- 在main目录下,添加webapp目录
- 在webapp目录下添加WEB-INF目录
- 在WEB-INF目录下,添加web.xml文件即可
然后就会提示,点击Configure->OK即可
然后在web.xml中添加代码
<?xml version="1.0" encoding="UTF-8" ?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
</web-app>
添加java web的maven依赖
由于web项目是需要打war包的,所以在pom里设置packaging为war(默认为jar)
<packaging>war</packaging>
添加servlet、JSP、JSTL依赖
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--JSP-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--JSTL-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
Maven依赖的三坐标(groupId、artifactId、version必须提供)
如果依赖只参与编译不需要打包,就可以scope为provided
tomcat自带servlet以及JSP对应jar包
编写一个简单的web应用
编写servlet类
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = dateFormat.format(new Date());
request.setAttribute("currentTime",currentTime);
request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
}
}
说明:
1. 继承HttpServlet,让它成为servlet类
2. 覆盖父类的doGet方法,用于接收GET请求
3. 在doGet方法中数据,将其放到HttpServletRequest对象然后转发到/WEB-INF/jsp/hello.jsp
4. 使用WebServlet注解并配置请求路径,对外发布Servlet服务
运行web应用
配置tomcat
-
首先在工具栏找到
edit configurations
,弹出Run/Debug
对话框 -
单机左上角的
+
号,选择Tomcat Servlet
->local
选项 -
输入tomcat的name,
取消勾选after launch
-
Application server下的Configure按钮,配置选择一个tomcat(自己安装的)
-
切换到deployment选项卡,单击右边的+号,选择Artifact选项,弹出select artifact to deploy对话框
-
选择…:war exploded
-
回到Run/Debug对话框下的Application context中输入/chapter1
即令URL为
http://localhost:8192/chapter1/
的形式 -
然后On frame deactivation选择Update resources
可以使用debug的方式运行Tomcat,这样代码中做出的修改可进行自动部署(热部署)只需要使用CTRL+F9键手工编译即可
使用Tomcat的Maven插件
在pom.xml中:
<!--Tomcat-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/${project.artifactId}</path>
</configuration>
</plugin>
不要打错了<path>
里的路径,任何一个符号错了就不可以,这里引用的值就是项目的artifactId,此项目的artifactId就是chapter1。
<path>
的作用是当前web项目的url
访问入口,即 http://localhost:8080/chapter1/
若设置为<path>/</path>
则访问url
为 http://localhost:8080/
然后添加一个maven的configuration
在common line输入tomcat7:run,点击OK然后RUN或者DEBUG 热部署了就可以访问了
部署完成之间输入url + @WebServlet
的值
如:http://localhost:8080/chapter1/hello