环境搭建
- 导入jar包
- spring、spring mvc
- mybatis、spring整合mybatis
- druid 连接池
- jsp jstl(标准标签库)
MyBatis配置类
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import javax.sql.DataSource;
import java.util.Properties;
public class MyBatisConfiguration {
// 配置session工厂
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{
//1 创建 factoryBean
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//2 设置数据
// 2.1 数据源
factoryBean.setDataSource(dataSource);
// 2.2 驼峰命名
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(configuration);
// 2.3 分页插件
Properties props = new Properties();
// 设置方言
props.setProperty("dialect", "mysql");
// 分页的同时进行count查询
props.setProperty("rowBoundsWithCount", "true");
// 分页合理化参数,pageNum<=0 时会查询第一页,pageNum>pages (超过总数时),会查询最后一页
props.setProperty("reasonable", "true");
// PageInterceptor pageInterceptor = new PageInterceptor();
// pageInterceptor.setProperties(props);
PageHelper pageHelper = new PageHelper();
pageHelper.setProperties(props);
factoryBean.setPlugins(new Interceptor[] {pageHelper});
//3 通过factorybean获得对应
return factoryBean.getObject();
}
/*
* 映射扫描器
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
//1 创建
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
//2设置包
mapperScanner.setBasePackage("mapper");
return mapperScanner;
}
}
Spring配置类
- 数据源配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=用户
jdbc.password=密码
- 配置类
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
public class SpringConfiguration {
/**
* 获得properties文件中内容,并注入对应变量
*/
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 配置数据源
*/
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
/**
* 事务管理器
*/
@Bean
public DataSourceTransactionManager txManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
Spring MVC配置类
@Configuration
@ComponentScan(basePackages=“controller”)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
public class MvcConfiguration implements WebMvcConfigurer {
/**
* 视图解析器
*/
@Bean
public InternalResourceViewResolver internalResourceViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//前缀 jsp文件夹
viewResolver.setPrefix("/WEB-INF/pages/");
//后缀 jsp扩展名
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
启动配置类
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//1 配置spring工厂
AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext();
// 注册所有的配置类
application.register(MyBatisConfiguration.class);
application.register(SpringConfiguration.class);
application.register(MvcConfiguration.class);
//2 post中文乱码
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8"));
encodingFilter.addMappingForUrlPatterns(null, true, "/*");
//3 核心控制器
ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application));
//mvcServlet.addMapping("*.action");
mvcServlet.addMapping("/");
mvcServlet.setLoadOnStartup(2); //tomcat启动时,执行servlet的初始化方法
}
实现
- 编写JavaBean(User)
- 提供字段 和 表类对应
- 添加MyBatis相关注解 @Id 等
@Entity(name="user")
public class User {
@Id
private String uid;
@Column(name="username")
private String userName;
private String password;
private String name;
private String email;
private String telephone;
private Date birthday;
private String sex;
private Integer state;
private String code;
// 省略getter和setter
}
- 编写Mapper(UserMapper)
- 整合通用Mapper
public interface UserMapper extends Mapper<User> {
}
- 编写service
- 需要管理事务
public interface UserService {
/*
* 查询所有
*/
public List<User> selectAll();
}
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
}
- 编写controller
- 处理请求路径
- 选择视图页面 list
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/selectAll")
public String selectAll(Model model) {
// 查询所有
List<User> list = userService.selectAll();
// 将查询结果存放request --> 模型
model.addAttribute("list", list);
// 设置视图名
return "list";
}
}
- list.jsp 页面展示数据(非重点)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1" width="800">
<tr>
<td>编号</td>
<td>登录名</td>
<td>昵称</td>
<td>email</td>
<td>电话</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.uid}</td>
<td>${user.userName}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.telephone}</td>
<td>
修改
删除
</td>
</tr>
</c:forEach>
</table>
</body>
</html>