一、构建 MVC
1. 新建 Model 文件,名为 Counter.java 位于 com.*.model package 下;
2. 新建 dao 文件,
3. 新建 sqlmap文件,直接操作 DataBase
<sql id="column_list">id, name, count</sql>
<resultMap id = "Map1">...</resultMap>
<select id = "selectByKey" resultMap="Map1"/ resultType="Integer" parameterType="java.lang.Integer"/"map"/"com.*.model.Counter">
SELECT COUNT(DISTINCT name) FROM counter
WHERE true
<if test="name != null and name!=''" >
AND name = #{name,jdbcType=VARCHAR}
</if>
limit #{start, jdbcType=INTEGER}, #{number, jdbcType=INTEGER}
</select>
>> resultMap/ resultType: 规定返回类型,必须和 CounterMapper.java 对应的返回值类型一致;
>> parameterType: 用于规定 java 中传递过来的数据类型;
>> jdbcType: 规定 SQL 语句中 Database 中的数据类型;
二、structs 中的 Action - @Controller 用于标注控制层组件
1. structs.xml 中配置各个 action,对应执行的 Action 类和方法,以及 result 处理;
2. 新建 Action 类,用于 JSP 跳转到 Java 中执行对应的操作,如 CounterAction.java;
<bean id="counterAction" class="com.*.action.CounterAction" scope="prototype">
<property name="counterService" ref = "counterService" ></property>
</bean>
//scope:默认是单例模式,每次访问的都是同一个 Action 对象,因此数据不安全,struts2 要求每次访问都对应不同的 Action,设置 scope="prototype" 每次请求时,都创建一个 Action 对象;
3. CounterAction 中需要 JSP 文件传递的参数时(如 date),必须在 CounterAction
4. CounterAction 需要通过 service 访问
注: applicationContext.xml: <import resource="classpath: action.xml"> ( 配置文件,详见三.3 )
action.xml: 注册 bean 和 service 的文件)
三、新建 CounterService -- structs 通过 service 调用 MVC
@ Service -- 自动装载
public class CounterService {
@ Autowired private CounterMapper dao;
}
1. @Service -- 服务层组件,业务层
@Service 是 Spring 框架的一个注解,表示这是一个 bean,[ 在 action.xml 中配置 bean id="CounterService",不必再 Spring 中配置 bean,自动根据 bean 的类名进行实现化为首字母小写counterService ]
2. @Autowired
>> @Autowired: Spring 框架中的注入方式,表示把 DAO 实现类注入到 service 实现类中;
>> @Autowired 不需要设置 get/ set方法,Spring 会自动注入;
3. 注解
applicationContext.xml -
<context: annotation-config/>
<context:component-scan base-package="com.*"></context:component-scan>
<import resource = "classpath: action.xml" /> // Spring 配置文件中导入 structs 的配置文件