文化企业网站模板,重庆网络安全公司,牛商网营销型网站建设,陕西营销型手机网站目录 1.准备工作
1.数据库源#xff08;这里以Mysql为例#xff09;
2.映射实体类
3.模拟三层架构#xff08;Dao、Service、Controller#xff09;
Dao接口
Dao实现
Service实现#xff08;这里省略Service接口#xff09;
Controller层#xff08;或叫Servlet层…目录 1.准备工作
1.数据库源这里以Mysql为例
2.映射实体类
3.模拟三层架构Dao、Service、Controller
Dao接口
Dao实现
Service实现这里省略Service接口
Controller层或叫Servlet层
web.xml中注册该Servket 1.准备工作
1.数据库源这里以Mysql为例
!-- 数据库依赖--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.47/version/dependency
因为是Servlet项目所以要用到JDBC去连接后台数据库此处还不熟悉的可借鉴我前几篇有关JDBC的文章
这里直接给出工具类JdbcUtil2
public class JdbcUtil2 {private static String url;private static String username;private static String password;private static String driver;static {InputStream is JdbcUtil2.class.getClassLoader().getResourceAsStream(db.properties);Properties pro new Properties();try {pro.load(is);} catch (IOException e) {throw new RuntimeException(e);}url pro.getProperty(url);username pro.getProperty(username);password pro.getProperty(password);driver pro.getProperty(driver);}public static Connection getConnection() throws SQLException, ClassNotFoundException {Class.forName(driver); // 显示加载驱动return (Connection) DriverManager.getConnection(url,username,password); // 拿到连接}public static Statement getStatement(Connection connection) throws SQLException {Statement statement connection.createStatement();return statement;}public static ResultSet getResultSet(Statement statement) throws SQLException {ResultSet resultSet statement.executeQuery(select * from book);return resultSet;}public static void close(Connection connection,Statement statement,ResultSet resultSet) throws SQLException {if(resultSet!null){resultSet.close();resultSet null;}if(statement!null){statement.close();statement null;}if(connection!null){connection.close();connection null;}}public static void main(String[] args) throws SQLException, ClassNotFoundException {Connection connection JdbcUtil2.getConnection();Statement statement JdbcUtil2.getStatement(connection);ResultSet resultSet JdbcUtil2.getResultSet(statement);while(resultSet.next()){int id resultSet.getInt(id);String name resultSet.getString(name);double price resultSet.getDouble(price);System.out.println(idid,namename,priceprice);}JdbcUtil2.close(connection,statement,resultSet);}2.映射实体类
这里我对应的数据库表是Book所以创建实体类Book 这是简单的表设计大家可直接模拟一个或自行创建一个表只要实体类对应上即可
public class Book {private int id;private String name;private double price;public Book(int id, String name, double price) {this.id id;this.name name;this.price price;}public Book() {}public int getId() {return id;}public void setId(int id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public double getPrice() {return price;}public void setPrice(double price) {this.price price;}Overridepublic String toString() {return Book{ id id , name name \ , price price };}
}3.模拟三层架构Dao、Service、Controller
Dao接口
public interface BookDao {// 书本列表public ListBook bookList() throws SQLException, ClassNotFoundException;}Dao实现
public class BookDaoImpl implements BookDao {// 书本列表Overridepublic ListBook bookList() throws SQLException, ClassNotFoundException {ListBook books new ArrayListBook();Connection connection JdbcUtil2.getConnection();// 注意这里的JdbcUtil2是自己封装好的JDBC工具类Statement statement JdbcUtil2.getStatement(connection);// 此处为了简便不考虑sql注入因此直接用statement而非prestatementResultSet resultSet JdbcUtil2.getResultSet(statement);// 获取结果集while(resultSet.next()){// 循环拿到每本书的信息并存在每个新创建的book对象中Book book new Book();book.setId(resultSet.getInt(id));book.setName(resultSet.getString(name));book.setPrice(resultSet.getDouble(price));books.add(book);// 添加每本书本信息在集合}return books; // 返回该集合}}
Service实现这里省略Service接口
public class BookService {public ListBook getAllbooks() throws SQLException, ClassNotFoundException {BookDao bookDao new BookDaoImpl();return bookDao.bookList();}Controller层或叫Servlet层
public class BookServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ListBook books new ArrayListBook();BookService bookService new BookService();try {books bookService.getAllbooks();// 调用Service层拿到books集合Gson gson new GsonBuilder().create();// 转换为jsonString json gson.toJson(books);// 设置响应类型指定为jsonresp.setContentType(application/json);// 指定字符集resp.setCharacterEncoding(UTF-8);// 返回数据resp.getWriter().write(json);} catch (SQLException e) {throw new RuntimeException(e);} catch (ClassNotFoundException e) {throw new RuntimeException(e);}}Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}}web.xml中注册该Servket
?xml version1.0 encodingUTF-8?
web-app xmlnshttp://xmlns.jcp.org/xml/ns/javaeexmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsdversion4.0!--设置首页--welcome-file-listwelcome-fileContent.jsp/welcome-file/welcome-file-list servletservlet-nameBookServket/servlet-nameservlet-classzhan.controller.BookServlet/servlet-class/servletservlet-mappingservlet-nameBookServket/servlet-nameurl-pattern/BookServlet/url-pattern/servlet-mapping/web-app编写Content.jsphtmljsajax
% page contentTypetext/html;charsetUTF-8 languagejava %
html
headtitle首页/title
/head
bodyh3列表展示/h3button idlistButton书本信息列表/buttondiv idbookList/div%--该div用于列表展示--%/body%--引入jquery用于调用ajax--%
script srchttps://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js/scriptscript$(function (){$(#listButton).click(function (){$.ajax({url: http://localhost:8080/BookServlet,type: GET,success: function (response){ // 一般来说response对响应体内容的封装我们可以从中获取值var bookList $(#bookList);bookList.empty(); // 清空列表response.forEach(function(book) {bookList.append(id:book.id,name:book.name,pricebook.pricebr);// 在response响应中遍历获取到的列表以book为单位不断填充在bookList这个div中 });},error: function (xhr, status, error) {alert(服务器异常);}});});});
/script