1、注册Spring配置文件,在web应用启动时创建Spring容器(注册listener)。
contextConfigLocation
classpath:spring-*.xml
org.springframework.web.context.ContextLoaderListener
2、字符集过滤器
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
forceEncoding
true
CharacterEncodingFilter
/*
3、注册SpringMVC中央调度器
SpringMVCDispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
SpringMVCDispatcher
*.do
4、定义实体类,实现页面。
例如Student类,注册页面,欢迎页面
5、实现处理器,编写主业务逻辑,等待service注入。
public class RegisterHandler implements Controller {
private IStudentService studentService;//等待注入,设置setter
public void setStudentService(IStudentService studentService) {
this.studentService = studentService;
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
Integer age = Integer.valueOf(ageStr);
Student student = new Student(name, age);
studentService.registerStudent(student);
ModelAndView modelAndView = new ModelAndView("/welcome.jsp");
modelAndView.addObject("student",student);
return modelAndView;
}
}
6、编写service层接口,等待dao层注入
public interface IStudentService {
void registerStudent(Student student);
}
public class StudentServiceImpl implements IStudentService {
private IStudentDao studentDao;//等待注入,设置setter
public void setStudentDao(IStudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public void registerStudent(Student student) {
studentDao.insertStudent(student);
}
}
7、编写dao层接口,实现dao层(mapper映射)。最好把mapper映射放在dao包下,但是这样有个问题就是不会被编译。尝试放在resources文件夹下
public interface IStudentDao {
void insertStudent(Student student);
}
//IStudentDao.xml
/p>
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
insert into student(name,age) values(#{name},#{age})
8、数据库连接,数据源
//jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
jdbc.user=1234
jdbc.password=1234
//spring-db.xml
9、整合spring与mybatis
重点:sqlSessionFactoryBean、mapper扫描器
10、dao注入到service,service注入到handler
11、最后在pom里编译一下没放进resources目录的xml文件
src/main/java
**/*.xml
12、添加事务处理
原文:https://www.cnblogs.com/darknessplus/p/10292305.html