Tomcat简单的说就是一个运行JAVA的网络服务器,底层是Socket的一个程序,它也是JSP和Serlvet的一个容器。
TomCat配置
在index中编写网页
index.html(编写网页的显示内容)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello</h1>
<form action="index" method="post">
名称:<input type="text" name="fname"/><br>
价格:<input type="text" name="price"/><br>
数量:<input type="text" name="fcount"/><br>
备注:<input type="text" name="remark"/><br>
<input type="submit" value="添加">
</form>
</body>
</html>
domain中的文件对应数据库中的表,dao中的文件是对表的各种操作方法的封装 ,Service编写对表的各种操作
FruitService
package JavaWeb.Service;
import JavaWeb.dao.FruitDAO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/**
* @author whlie(true){learn}
*/
public class FruitService extends HttpServlet {
FruitDAO fruitDAO = new FruitDAO();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fname = req.getParameter("fname");
String price = req.getParameter("price");
String fcount = req.getParameter("fcount");
String remark = req.getParameter("remark");
String sql="insert into fruit VALUES(null,?,?,?,?)";
try {
int update = fruitDAO.update(sql, fname, Integer.parseInt(price),
Integer.parseInt(fcount), remark);
System.out.println(update>0?"成功":"失败");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
index相当于前端接收用户输入,FruitService将接收的数据存入数据库,这两者之间还需要一个映射关系
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">
<servlet>
<servlet-name>Fruit</servlet-name>
<servlet-class>JavaWeb.Service.FruitService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Fruit</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
1.用户发请求,action=Fruit
2.项目中,web.xml中找到url-pattern=/index
3.根据对应的Fruit找到servlet-name=Fruit
4.找和servlet-mapping中servlet-name一致的servlet,找到JavaWeb.Service.FruitService
5.用户发送的是post请求(me thod-=post),因此tomcat会执行FruitService中的doPost方法
补充关于Tomcat运行后找不到配置文件的问题
可能的情况1
可能情况2
配置文件位置问题,将配置文件放到JavaWeb也就是映射的文件下
或者之间使用绝对路径