当前位置:网站首页>Implement browser servlet database interaction
Implement browser servlet database interaction
2022-07-18 07:44:00 【Rong, who has to learn every day】
Catalog
- 1、 Create a new project module
- 2、 add to web modular
- 3、 Import jar package
- 4、 Add module dependencies
- 5、 Deploy Tomcat
- 6、 To configure Web Containers
- 7、 Create client's html Request file
- 8、 newly build JDBC Connect to the operation database
- 9、 newly build Servlet Components
- 10、 To configure servlet mapping
- 11、 Check whether the data can be successfully added to the database
1、 Create a new project module
stay project So let's make a new one module
2、 add to web modular
Built in your module Right click to select add framework support
3、 Import jar package
In the project project Create a new directory in , Name it lib Folder .
We can also put lib Create a new folder directly in WEB-INF Next , Such a bad place is this lib It can only be the current moudle exclusive . If there is a second moudle New... We need to repeat again lib .
Connect what you want to use with the database jar Package import in , That is, copy and paste into lib Under the folder , Download here jar The package and database versions should be consistent ,java Connect mysql Download the driver package of

stay lib Folder right click Add as Library
4、 Add module dependencies
Click on File - Project Structure , Perform the following steps to configure 
First import Tomcat Dependence and Lib rely on , It includes JSP and Servlet Need to use some API, as well as JDBC A library that connects to a database 

5、 Deploy Tomcat
5.1 The first way
After adding dependencies above , here Problems It will show a problem , Click on Fix Just fix it 
5.2 The second way
To Artifacts Delete this module before adding it again , The steps are as follows :

Be careful not to choose the wrong one Archive( representative War package , Namely Web The package ), Although there's nothing wrong ,Tomcat Will automatically decompress it for you , But it's better to choose the one above 
After selecting, click OK , The project is deployed 
Don't forget to apply after completion , Click on Apply And then click OK That's all right. 
6、 To configure Web Containers
Be careful : Here is tomcat Server, No tomcatEE Server
The first use here is to import Tomcat application , Choose all here Tomcat Just install the directory 
Then jump to the deployment page , Add deployment
6.1 The first method of configuration
It's direct here Fix That's all right. 
6.2 The second method of configuration
In this way, if there are multiple items, you can add them selectively 
Then on this page , Change this file directory to a /, Set the jump later URL You can have one less layer of folders 
① Fill in web Container name , It's usually tomcat+ Version number
② After Launch It means Tomcat After loading, the browser selected in the back will open by default URL Corresponding resources
③ Set up your URL Resources to address , Upper general Application context Set as a / , If so, set the link here directly as http://localhost:8080/add.html that will do , If you have no settings , The link set here has one more level of directory http://localhost:8080/ Your directory name /add.html

Be careful :
- Here, if you haven't made any changes , If the URL is :
http://localhost:8080/ Your directory /, So it shows that we are visiting index.html(Tomcat At the end of the default welcome page ), But you didn't write this resource , Will report 404( Resource not found ) error . - We can go through <welcome-file-list> Tab to set the welcome page ( stay tomcat Of web.xml Set in , Or in your own project web.xml Set in )


And remember apply - ok That's all right. 
7、 Create client's html Request file
stay web Right click... Under the folder new One HTML file , Notice the new one here html The document is and WEB-INF In the same directory , Don't put the new file in WEB-INF Directory 
The file after construction is shown in the following figure 
stay add.html Create a new form in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="add" method="post">
name :<input type="text" name="fname"/><br/>
Price :<input type="text" name="price"/><br/>
stock :<input type="text" name="fcount"/><br/>
remarks :<input type="text" name="remark"/><br/>
<input type="submit" value=" add to " />
</form>
</body>
</html>
Be careful :
- Null pointer or NumberFormatException . Because there is price and inventory ,
If the price is not available , As a result, you want to be right null Conduct Integer.parseInt() You're going to report a mistake . - The reason for the mistake is mostly because name=“price” There is a mistake here , It turns out that Servlet End or use request.getParameter(“price”) To get .( No spaces , It has to be exactly the same )
8、 newly build JDBC Connect to the operation database
In this one module Under the src Create a new package under the folder ,fruit Package placement is related to database connection interaction DAO Interface file 、 Implementation classes and fruit Fruits, etc , You can go to the official official account of shangsilicon Valley to reply JavaWeb To get relevant information , Just copy and paste it directly ,DAO The specific principle of implementation can be seen in my previous article ( Silicon Valley )JDBC Always review 
That's it when it's built :
8.1 Database operation
The default database here is enabled , And there are already fruit This form , If not , Click the following directory in the Shang Silicon Valley information to find fruitdb.sql Run it in the database , It will generate a fruitdb Database and fruit form , After this step, keep the database open 
8.2 Change user name and password
Pasted here BaseDAO The file is used directly in Java How to configure the four elements in the code , So we found BaseDAO file , Modify the user name and password to be your own user name and password ( If you don't modify this connection, you won't be able to connect to the database , After adding data in a while, the server will respond with 500 FALSE )
9、 newly build Servlet Components
We will be having atguigu Create a new servlets Folder , stay servlet Create a new folder AddServlet class , Inherit one HttpServlet class ( This class is in the Tomcat Inside servlet-api jar In the bag , So remember to import Tomcat rely on ), And because we add.html The method defined in is post, So we're going to rewrite it doPost Method ( If it is not rewritten, it will report 405 error ), At the same time through request Object to get the information sent by the user 
AddServlet The components are written as follows :
package atguigu.servlets;
import atguigu.fruit.dao.FruitDAO;
import atguigu.fruit.dao.impl.FruitDAOImpl;
import atguigu.fruit.pojo.Fruit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AddServlet extends HttpServlet {
// Respond to your http request , The client sends a... To the server http request , The server encapsulates it into a HttpServletRequest object
@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 ? " Add success !" : " Add failure !");
}
}
Be careful :
- 405 problem : The currently requested method does not support . such as , Our form method=post , that Servlet Must correspond to doPost, Otherwise the newspaper 405 error .
10、 To configure servlet mapping
How do we put add This action is similar to AddServlet What about the correspondence , Just click the Add button on my side , Send to server , The server knows which component I want to use to process this information
10.1 The first method
stay module Under the module of web In the catalog WEB-INF Found in folder web.xml file , Set... In it servlet and servlet-mapping Tag for connection mapping 
The document is modified as follows :
<?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>
</web-app>
Be careful :
- Among them url-pattern In order to / At the beginning , This can't be lost , Unknown cause .
xml File mapping process :
1. Request from user ,action=add
2. In the project ,web.xml Find url-pattern = /add -> The first 12 That's ok
3. Find the first 11 Yes servlet-name = AddServlet
4. Find a peace servlet-mapping in servlet-name coincident servlet , Find No 7 That's ok
5. Find the first 8 Yes servlet-class -> com.atguigu.servlets.AddServlet
6. The user sent post request (method=post) , therefore tomcat Will execute AddServlet Medium doPost Method
10.2 The second method
Use annotations , No need to modify web.xml file , Directly in your AddServlet Class using annotations
- @WebServlet(“/add”), This one in double quotation marks /add Just like your original url-pattern The contents in the label are consistent .
The code is as follows ( Only modify in the first line ):
@WebServlet("/add")
public class AddServlet extends HttpServlet {
// Respond to your http request , The client sends a... To the server http request , The server encapsulates it into a HttpServletRequest object
@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 ? " Add success !" : " Add failure !");
}
}
Be careful :
- Choose one of the two ways , Otherwise, an error will be reported
11、 Check whether the data can be successfully added to the database
Click on debug Carry out commissioning and operation 
Tomcat Successfully deployed and Web After the container is successfully configured, the interface

The resource interface to respond after successful operation :
The database interface :

After writing something inside, click the Add button , Let's see what happens , A successful addition is the return 200 Status code for ,
Now look at the database interface , Successful user database interaction .
At this time, the console prints and adds the word success ( There may be a garbled code problem here , stay servlet Code set settings in )
边栏推荐
- HTAP能力加速TPC-H执行前要怎么部署PolarDB for PostgreSQL?
- Detailed explanation of time complexity and space complexity
- 3-6月面经总结,200多页真题笔记和详解(含核心考点及6家大厂)
- Pytorch中torch.repeat_interleave()函数解析
- 如何制作sitemaps网站地图
- 模块二interfaces下头文件解析(2)
- (开源项目)abattoir unity游戏
- VSCode【因为在此系统上禁止运行脚本】
- mysql中出现Unit mysql.service could not be found 的解决方法
- JVM tuning command encyclopedia and common command tools and practical steps
猜你喜欢

防火墙HA配置

在创建生成WIFI二维码手机扫码链接

Penetration test process

Simple understanding of CAS and AQS

Pytorch中torch.repeat_interleave()函数解析

(Dell Lingyue 7572) after the laptop expands the display, the laptop has no sound

英特尔发布开源AI参考套件

LAN attack and network device security configuration

Amd ryzen 5 7600x 6 core and 4.4ghz'zen 4 'CPU appear in the running sub database

Eight guidelines for modbus-rs485 wiring
随机推荐
想到多线程并发就心虚?先来巩固下这些线程基础知识吧!
Using chardet to detect web page coding
数据治理生产线DataArts,让“人人都是分析师”
Provide/Inject
李沐动手学深度学习V2-目标检测数据集
2022 China mobile maker marathon Internet of things special competition kicks off
Writing PHP form data to MySQL code
LINQ implements dynamic orderby
2、趋势科技2017校招开发岗试题
OpenHarmony模块二下文件samgr_server解析(2)
Intel releases open source AI Reference Suite
Talk about how to write a programmer's resume (help modify your resume)
Openharmony module 2 file samgr_ Server parsing (5)
DevSecOps研发安全实践——设计篇
实现浏览器 - Servlet - 数据库交互操作
根据经纬度计算两点之间的距离
Numpy gets a row and a column of a two-dimensional array
如何制作sitemaps网站地图
mysql中 decimal(10,2)格式的通过stream 方式写到 kafka 变成 stri
C#小技巧 获取枚举所有枚举值