功能:在页面点击“显示信息”,然后将书籍的信息显示出来,如下图
加群一起探讨java,QQ群号:591193911
下面是我的例子的项目结构图
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>springmvc-mybaits-book</display-name>
<!-- 配置springMVC的核心控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:resource/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置编码为utf-8,防止出现乱码 -->
<filter>
<filter-name>charsetEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charsetEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
BookIndex.java
package com.springbook.controller;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.entity.BookEntity;
import com.springmvc.service.mybaitsDatabase;
/**
*
* @author Administrator
* @return 将数据集合设置给index页面
*/
@Controller
public class BookIndex {
@RequestMapping(value = "/hello")
public ModelAndView getDeptAll() {
ArrayList<BookEntity> booklist = new mybaitsDatabase().getlist();
// 创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
// 进行对对象 赋值 键值对的形式
modelAndView.addObject("booklist", booklist);
// 进行写入要跳转的视图名index.jsp
modelAndView.setViewName("index");
return modelAndView;
}
}
BookDao.java
package com.springbook.dao;
import java.util.List;
import com.springmvc.entity.BookEntity;;
public interface BookDao {
/**
* 获取单条数据
*
* @param id
* @return
*/
public BookEntity get(String title);
/**
* 获取单条数据
*
* @param entity
* @return
*/
public BookEntity get(BookEntity entity);
/**
* 查询数据列表
*
* @param entity
* @return
*/
public List<BookEntity> findList(BookEntity entity);
/**
* 查询数据列表
*
* @param entity
* @return
*/
public List<BookEntity> findAllList(BookEntity entity);
/**
* 查询数据列表
*
* @see public List<UserEntity> findAllList(UserEntity entity)
* @return
*/
// @Deprecated(弃用的注解)
public List<BookEntity> findAllList();
/**
* 插入数据
*
* @param entity
* @return
*/
public int insert(BookEntity entity);
/**
* 更新数据
*
* @param entity
* @return
*/
public int update(BookEntity entity);
/**
* 删除数据
*
* @see public int delete(T entity)
* @return
*/
public int delete(String title);
/**
* 删除数据
*
* @return
*/
public int delete(BookEntity entity);
}
BookEntity.java
package com.springmvc.entity;
import java.util.UUID;
public class BookEntity {
private String title; //书籍的标题
private String author; //书籍的作者
private String price; //书籍的价格
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
/**
* 插入之前执行方法,需要手动调用 */
public void preInsert(){
// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
setTitle(uuid());
}
/**
* 封装JDK自带的UUID, 通过Random数字生成, 中间用-分割.
*/
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
mybaitsDatabase.java
package com.springmvc.service;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.springbook.dao.BookDao;
import com.springmvc.entity.BookEntity;
public class mybaitsDatabase {
private static BookDao userDao;
private static Reader reader;
private static SqlSessionFactory sessionFactory;
private static SqlSession session = null;
/**
*
* @return 数据库查询出来的的数据,供其他类调用数据
*/
public ArrayList<BookEntity> getlist() {
Initialize("mybatis_config.xml");
List<BookEntity> bookList = userDao.findAllList();
return (ArrayList<BookEntity>) bookList;
}
private static void Initialize(String configFile) {
try {
reader = Resources.getResourceAsReader(configFile);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
session = sessionFactory.openSession();
userDao = session.getMapper(BookDao.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd">
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<!-- 配置扫描 -->
<context:component-scan base-package="com.springbook.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 配置根视图 -->
<mvc:view-controller path="/" view-name="index" />
<!-- 激活基于注解的配置 @RequestMapping, @ExceptionHandler,数据绑定 ,@NumberFormat ,
@DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等 -->
<mvc:annotation-driven />
<!-- 静态资源配置 -->
<!-- <mvc:resources location="/assets/" mapping="/assets/**"></mvc:resources> -->
<!-- 视图层配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
BookMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springbook.dao.BookDao">
<sql id="userColumns">
a.title AS "title",
a.author AS "author",
a.price AS "price"
</sql>
<sql id="userJoins">
</sql>
<select id="get" resultType="Book">
SELECT
<include refid="userColumns" />
FROM book a
<include refid="userJoins" />
WHERE a.title = #{title}
</select>
<select id="findList" resultType="Book">
SELECT
<include refid="userColumns" />
FROM book a
<include refid="userJoins" />
<where>
a.del_flag = #{DEL_FLAG_NORMAL}
</where>
</select>
<select id="findAllList" resultType="Book">
SELECT
<include refid="userColumns" />
FROM book a
<include refid="userJoins" />
</select>
<insert id="insert">
INSERT INTO book(
title,
author,
price
) VALUES (
#{title},
#{author},
#{price}
)
</insert>
<update id="update">
UPDATE book SET
author = #{author},
age = #{price}
WHERE title = #{title}
</update>
<update id="delete">
DELETE FROM book
WHERE title = #{title}
</update>
</mapper>
mybatis_config.xml(注意写好你的url),我的mysql版本较高,驱动加了cj
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<!-- 这里给实体类取别名,方便在mapper配置文件中使用 -->
<typeAlias alias="Book" type="com.springmvc.entity.BookEntity" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.1.3:3306/debook?useSSL=false&useUnicode=true&characterEncoding=UTF8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 这里添加的是执行CRUD操作的接口对应的配置文件(xml文件) -->
<mappers>
<mapper resource="resource/BookMapper.xml" />
</mappers>
</configuration>
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>首页</title>
</head>
<body>
<center>
<form action="hello" method="post">
<table border="1" width="700px">
<tr>
<td>书名</td>
<td>作者</td>
<td>价格</td>
<td><input type="submit" value="显示信息"></td>
</tr>
<c:forEach var="book" items="${booklist }">
<tr>
<td>${book.title }</td>
<td>${book.author }</td>
<td>${book.price }</td>
</tr>
</c:forEach>
</table>
</form>
</center>
</body>
</html>
mysql数据sql
CREATE TABLE `book` (
`title` varchar(50) NOT NULL,
`author` varchar(50) DEFAULT NULL,
`price` varchar(80) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我的表添加的数据
运行项目后自动默认打开index.jsp,如果不自动打开,可以输入http://localhost:8080/springmvc-mybatis-book
注意:我的项目名的mybatis拼错了
点击“显示信息后的结构图”
源码下载:源码 提取码:adfg