不使用spring-mybatis包
整合ssm完成对account表新增和查询的操作
spring核心、aspectj(aop)、spring-jdbc(jdbcTemplate)、spring-tx(事务)、
数据源:mysql、c3p0、mybatis mybatis-spring(spring整合mybatis)
junit、spring-tst、
servlet、jsp、jstl、
lombok、
spring-webmvc(springMvc依赖)
org.springframework
spring-context
5.0.5.RELEASE
org.aspectj
aspectjweaver
1.9.5
org.springframework
spring-jdbc
5.0.5.RELEASE
org.springframework
spring-tx
5.0.5.RELEASE
mysql
mysql-connector-java
5.1.8
com.mchange
c3p0
0.9.5.5
org.mybatis
mybatis
3.5.13
org.mybatis
mybatis-spring
2.0.5
junit
junit
4.12
test
org.springframework
spring-test
5.0.5.RELEASE
javax.servlet
javax.servlet-api
3.0.1
provided
javax.servlet.jsp
jsp-api
2.2
provided
jstl
jstl
1.2
org.projectlombok
lombok
1.18.12
org.springframework
spring-webmvc
5.0.5.RELEASE
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbc
jdbc.username=root
jdbc.password=root123
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
private int id;
private String name;
private double money;
}
public interface AccountMapper {
//保存账户数据
@Insert("insert into `account` values(#{id},#{name},#{money})")
public void save(Account account);
//查询账户数据
@Select("select * from `account`")
public List findAll();
}
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
CharacterEncodingFilter
/*
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
2
DispatcherServlet
/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AccountException extends Exception {
String message;
}
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof ClassCastException){
modelAndView.addObject("info","类转换异常");
}else if(e instanceof ArithmeticException){
modelAndView.addObject("info","除零算数异常");
}else if(e instanceof FileNotFoundException){
modelAndView.addObject("info","文件找不到异常");
}else if(e instanceof NullPointerException){
modelAndView.addObject("info","空指针异常");
}else if(e instanceof AccountException){
AccountException ae=(AccountException) e;
modelAndView.addObject("info","AccountService的报的异常"+ae.getMessage());
}
modelAndView.setViewName("error");
return modelAndView;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
error
异常页面~
${info}
@Service
public class AccountServiceImpl implements AccountService {
@Override
public void save(Account account) throws AccountException {
try {
//1.加载mybatis核心配置,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
mapper.save(account);
sqlSession.commit();
sqlSession.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
throw new AccountException(str);
}
}
@Override
public List findAll() throws AccountException {
try {
//1.加载mybatis核心配置,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
List accountList = mapper.findAll();
sqlSession.close();
return accountList;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
throw new AccountException(str);
}
}
}
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
//保存
@RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(Account account) throws AccountException {
accountService.save(account);
return "保存成功";
}
//查询
@RequestMapping("/findAll")
public ModelAndView findAll() throws AccountException {
List accountList = accountService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("index");
return modelAndView;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
save
添加账户信息表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
index
展示用户数据列表
账户id
账户名称
账户金额
${account.id}
${account.name}
${account.money}
运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp
和http://localhost:8080/SsmModule/account/findAll
如service层中的是实现类中的方法
public void save(Account account) throws AccountException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); ... }每当执行一次controller就会在service层创建一个sqlSessionFactory工厂
contextConfigLocation
classpath:applicationContext.xml
mybatisConfigLocation
mybatis-config.xml
@WebListener
public class MybatisLoadListener implements ServletContextListener {
@SneakyThrows
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
//获取web.xml中配置的application的全局初始化参数:
String mybatisConfigLocation = servletContext.getInitParameter("mybatisConfigLocation");//其值为applicationContext.xml
InputStream inputStream = Resources.getResourceAsStream(mybatisConfigLocation);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
servletContext.setAttribute("sqlSessionFactory",sqlSessionFactory);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
public class MybatisContextUtils {
public static SqlSessionFactory getSqlSessionFactory(ServletContext servletContext){
return (SqlSessionFactory)servletContext.getAttribute("sqlSessionFactory");
}
}
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
//保存
@RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(HttpServletRequest request,Account account) throws AccountException {
WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
ServletContext servletContext = ac1.getServletContext();
accountService.save(account,servletContext);
return "保存成功";
}
//查询
@RequestMapping("/findAll")
public ModelAndView findAll(HttpServletRequest request) throws AccountException {
WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
ServletContext servletContext = ac1.getServletContext();
List accountList = accountService.findAll(servletContext);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("index");
return modelAndView;
}
}
@Service
public class AccountServiceImpl implements AccountService {
@Override
public void save(Account account, ServletContext servletContext) throws AccountException {
try {
SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
mapper.save(account);
sqlSession.commit();
sqlSession.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
throw new AccountException(str);
}
}
@Override
public List findAll(ServletContext servletContext) throws AccountException {
try {
SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
List accountList = mapper.findAll();
sqlSession.close();
return accountList;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
throw new AccountException(str);
}
}
}
运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp
和http://localhost:8080/SsmModule/account/findAll
但是这种方式麻烦不说
service层每次还要加上一个servletContext的入参使得controller和service界限模糊不清
所以绝不推荐使用
将session工厂交给spring容器管理,从容器中获得执行操作的Mapper实例即可
将事务的控制(sqlSession.commit和sqlSession.close等)交给spring容器进行声明式事务控制
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public void save(Account account){
try {
accountMapper.save(account);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public List findAll(){
try {
List accountList = accountMapper.findAll();
return accountList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}