1. 创建容器,这里用的是tomcat
2. jsp头部引入所需的包、可以从maven官网中下载对应jar包
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*,java.util.*,com.alibaba.fastjson.JSON" pageEncoding="utf-8"%>
所需的jar包、可以从maven官网搜索下载
Maven官网地址:https://mvnrepository.com/
mysql-connector-java
fastjson
如:mysql-connector-java
下载后的jar包放到tomcat的lib目录或者WEB-INF的lib目录
3. 数据库配置、操作
查询使用-executeQuery(sql) 返回类型:ResultSet
增删改使用-executeUpdate(sql) 返回类型:int
Mysql常用语句:https://blog.csdn.net/qq812457115/article/details/125152133
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*,java.util.*,com.alibaba.fastjson.JSON" pageEncoding="utf-8"%>
<%
//驱动程序名
String driverName = "com.mysql.jdbc.Driver";
//数据库用户名
String userName = "root";
//密码
String userPasswd = "******";
//数据库名
String dbName = "test-jsp";
//表名
String tableName = "user";
//联结字符串
String url = "jdbc:mysql://localhost/" + dbName + "?user=" + userName + "&password=" + userPasswd;
//加载驱动
Class.forName(driverName).newInstance();
//建立连接
Connection conn = DriverManager.getConnection(url);
//创建Statement(负责执行sql语句)
Statement stmt = conn.createStatement();
String sql = "select * from " + tableName;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
out.println(rs.getString("name"))
}
//关闭连接
rs.close();
stmt.close();
conn.close();
%>
4. 接收传递的参数、输出参数
<%
// 获取name参数
String name = request.getParameter("name");
// 输出name参数
out.println(name);
/* 允许跨域的主机地址 */
response.setHeader("Access-Control-Allow-Origin", "*");
/* 允许跨域的请求方法GET, POST, HEAD 等 */
response.setHeader("Access-Control-Allow-Methods", "*");
/* 重新预检验跨域的缓存时间 (s) */
response.setHeader("Access-Control-Max-Age", "3600");
/* 允许跨域的请求头 */
response.setHeader("Access-Control-Allow-Headers", "*");
/* 是否携带cookie */
response.setHeader("Access-Control-Allow-Credentials", "true");
%>