总结
- 配置文件(保证正确性,包名要正确)
- dao创建
- 创建接口,加@Repository
- 创建增删改查方法,加注解,写sql语句,#{ 属性 } 属性访问
- service创建, 接口 , 方法一般与dao一致
- serviceImpl创建,类 ,引入service接口,
- 加入@service注解,
- 加入@Autowired注解,
- 实现每个方法的dao处理
- controller创建,使用@Controller注解,
- 加入@Autowired 指定service接口,
- 创建方法,指定@RequestMapping("index"),执行方法
过程
- 浏览器发出请求
- 接受请求
- 启动Spring容器,web.xml 请求地址能够被Spring收到
- controller必须在Spring容器(依赖在容器内,service)
- controller-service-dao-连接注入(每个必须在容器)
- 启动Spring容器,web.xml 请求地址能够被Spring收到
- 2个扫描(包扫描,MapperScannerConfigurer扫描)
- @RequestMapping 地址(多层地址,地址不能冲突)
- 方法参数冲突(int,integer 必有项区别)
- 代码处理错误(null为空,index索引)-sql错误
- 返回的视图名称(路径对应)
- jsp视图处理正确
常见异常
404 mapping路径/视图名称/没进入Spring处理
500 数据库异常###
500控制器处理 根据异常信息
启动Spring错误,依赖容器初始化错误
web服务启动错误,jar不全,web.xml设置有问题 删除webserver重置
web.xml 配置静态资源(后缀名)
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
applicationContext.xml (路径)
<!-- 处理静态资源 -->
<mvc:default-servlet-handler/>
<mvc:resources location="/layui/" mapping="/layui/**"></mvc:resources>
容器部件
- @Controller 控制器(注入服务)
- @Service 服务(注入dao)
- @Repository dao(实现dao访问)
- @Component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
MVC
- model、pojo、entity
- view
- controller
- 基本处理
@Controller
public class testController {
@RequestMapping("aaa")
public String index() {
System.out.println("aaaa");
return "index";
}
-
- @RequestMapping
@Controller 多级目录
@RequestMapping("Book")
public class testController {
}
@RequestMapping("index")
public String index() {
}
-
- 方法参数
- 请求参数
- 方法参数
public String index(String txt)
public String index(Type t) 调用settters
-
-
- 系统参数
-
向页面模板传值(request 值)
public String index(Type t,ModelMap m)
m.put("info", new Type(2,"dddff"));
public String index(HttpServletRequest req)
public String index(HttpSession s)
-
- 方法数据库处理
- @Autowired 在容器中根据类型自动注入
- 方法数据库处理
@Autowired 在容器中根据类型自动获取对象
Type_Dao dao;
@RequestMapping("index")
public @ResponseBody List<Type> index() {
return dao.select();
}
-
- 方法返回
- String 视图名称
- 方法返回
return "edit";
-
-
- String url转发
-
return "redirect:index.jsp";
-
-
- 对象
-
public @ResponseBody Type index() { return new Type(2,"dddff"); }
Mybatis
- 定义接口
@Repository
public interface Type_Dao {
@Select("select * from type")
public List<Type> select();
@Insert("insert into type (name) values(#{name})")
public void insert(Type t);
- 两个扫描(包名要一致)
- 将接口动态生成类,加入数据连接
- 加入spring容器
1.将接口动态生成类,加入数据连接 (包名一致)
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
2.加入spring容器
<context:component-scan base-package="dao"></context:component-scan>
- 定义使用
- 动态注入 @Autowired 容器中查找同类型对象,直接赋值
- 查询使用
动态注入
@Autowired 在容器中查找类型一致的对象 ,赋值到下面变量
Type_Dao dao;
查询使用
@RequestMapping("index")
public @ResponseBody List<Type> index() {
return dao.select();
}