Servlet
html中,form表单的 method = post | action = add
发送到服务器后根据 add 映射到相对应的服务器
需要在 web.xml 中配置服务器映射
- 用户发送请求,action = add,
- 项目中, web.xml 配置 servlet-name = AddServlet
- 服务器映射 servlet-mapping -> url-pattern = add 映射到 servlet-name = AddServlet
- servlet-class = com.atguigu.servlets.AddServlet 找到对应的类
- 在src目录下实现 com.atguigu.servlets.AddServlet 类即可
<?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>AddServlet</servlet-name>
<servlet-class>com.atguigu.servlets.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<!--
1.用户发送请求,action = add,
2.项目中, web.xml 配置 servlet-name = AddServlet
3.服务器映射 servlet-mapping -> url-pattern = add 映射到 servlet-name = AddServlet
4 servlet-class = com.atguigu.servlets.AddServlet 找到对应的类
-->
</web-app>
实现 com.atguigu.servlets.AddServlet 类
public class AddServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname = request.getParameter("fname");
String priceStr = request.getParameter("price");
Integer price = Integer.parseInt(priceStr);
String fcountStr = request.getParameter("fcount");
Integer fcount = Integer.parseInt(fcountStr);
String remark = request.getParameter("remark");
FruitDAO fruitDAO = new FruitDAOImpl();
boolean flag = fruitDAO.addFruit(new Fruit(0 , fname , price , fcount , remark));
System.out.println(flag ? "添加成功!" : "添加失败!");
}
}
遇到问题
-
404
- Tomcat部署时,Deployment中的Application context设置为 /
- Server中的URL设置为 http://localhost:8080/xxx.html
-
500
- ClassNotFoundException: com.mysql.cj.jdbc.Driver
- 需要在 Artifacts 中导入连接数据时用到的依赖(druid和mysql-connector-java)
- 在 Project Structure 的 Libraries 中添加需要的依赖
- 然后在 Artifacts 中会提示需要添加相同依赖到 WEB-INF 中,点击添加即可
-
中文添加到数据库中显示乱码
- 在服务器接收请求时设置字符集为UTF-8
- request.setCharacterEncoding("UTF-8");