SSM環境搭建(接口編程方式)


一直用ssm在開發項目,之前都是直接copy別人的項目,今天趁着項目剛剛交付,自己搭建一下ssm環境,做個記錄

一、創建項目、引入jar包,因為版本不一樣,就不貼出這部分的內容了。個人平時的習慣是,先將核心jar包引入,在測試是如果有需要添加的,在額外加入,一堆jar包也不太好記。

二、首先項目中配置spring

 1、項目web.xml中配置

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 通過上下文參數指定spring配置文件的位置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

2、構建項目結構如下圖(代碼見下方):

2.1實體類User

public class User {
	private int id;
	private String name;
	private int age;
        //getters、setters
}

2.2   UserDao 對實體類的操作,其中的方法名稱和Mapper中對應的id一樣

public interface UserDao {

	public List<User> findAll();

	public User findById(int id);

	public void addUser(User u);

	public void deleteUser(int id);

	public void updateUser(User u);
}

2.3 UserMapper.xml,其中就是對應dao層的具體操作,包括其中的sql語句,類似與其中接口的實現,只不過這個實現是mybatis自己去實現的

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- Mapper中的namespace用於綁定Dao接口的,mybatis為映射文件定義了一個代理接口,以后全部通過這個接口來和映射文件交互,而不再是使用以前方法 -->
<mapper namespace="com.ssm.dao.UserDao">
	<!-- 查找 -->
	<select id="findAll" resultType="user">
		select * from user
	</select>

	<!-- 根據主鍵查找 -->
	<select id="findById" parameterType="int" resultType="user">
		select * from user where id = #{id}
	</select>

    <!-- useGeneratedKeys="true" keyProperty="id"  用戶獲取添加后的主鍵 -->
	<insert id="addUser" parameterType="user" useGeneratedKeys="true"
		keyProperty="id">
		insert into user values (#{id},#{name},#{age})
	</insert>

	<!-- 刪除 -->
	<delete id="deleteUser" parameterType="int">
		delete from user where id = #{id}
	</delete>

	<!-- 修改 -->
	<update id="updateUser" parameterType="user">
		update user
		set name =	#{name},age= #{age}
		where id = #{id}
	</update>
</mapper> 

2.4   userService,用戶的業務操作,注意這里userDao接口,mybatis MapperScannerConfigurer生成代理注入到Spring(spring文件中),所以我們沒有不需要為dao層添加注解@Repository進行注入

@Service
public class UserService {

	@Resource
	private UserDao userDao;

	public List<User> findAll() {
		return userDao.findAll();
	}

	public User findById(int qid) {
		return userDao.findById(qid);
	}

	public void addUser(User u) {
		userDao.addUser(u);
	}

	public void deleteUser(int id) {
		userDao.deleteUser(id);
	}

	public void updateUser(User u) {
		userDao.updateUser(u);
	}
}

2.5    applicationContext.xml文件中,主要是sqlSessionFactory和事物的配置,里邊有詳細的配置注釋,這里不再贅述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
						http://www.springframework.org/schema/mvc 
						http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd 
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

	<!-- 注解驅動 -->
	<mvc:annotation-driven />
	<!-- 組件掃描 -->
	<context:component-scan base-package="com.ssm"></context:component-scan>

	<!-- 定義數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="initialPoolSize" value="10" />
		<property name="maxPoolSize" value="50" />
		<property name="minPoolSize" value="10" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<property name="dataSource" ref="dataSource"></property>
		<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
	</bean>

	<!-- mybatis MapperScannerConfigurer 自動掃描 將Mapper接口生成代理注入到Spring -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ssm.dao" />
		
		<!--沒有必要去指定SqlSessionFactory或SqlSessionTemplate, 因為MapperScannerConfigurer將會創建 
			MapperFactoryBean,之后自動裝配。 但是,如果你使 用了一個以上的DataSource,那 么自動裝配可能會失效。 
			這種情況下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName 
			屬性來設置正確的 bean名稱來使用。 -->
		<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
	</bean>

	<!-- 事務管理器 -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置事物的傳播特性 (事物通知) -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" read-only="true" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:advisor pointcut="execution(* com.area.service.*.*(..))"
			advice-ref="txAdvice" />
	</aop:config>
</beans>

2.6  mybatis的配置文件,這個主要是對全局的配置進行一個設置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true" />
	</settings>
	<typeAliases>
		<typeAlias alias="user" type="com.ssm.pojo.User" />
	</typeAliases>

</configuration>

2.7   測試類:

public class TestSSM {

	private static ApplicationContext act;
	private static SqlSessionFactory sqlSessionFactory;
	private static SqlSession sqlSession;

	@BeforeClass
	public static void before() throws IOException {
		act = new ClassPathXmlApplicationContext("applicationContext.xml");
		sqlSessionFactory = (SqlSessionFactory) act
				.getBean("sqlSessionFactory");
		sqlSession = sqlSessionFactory.openSession();
	}

	@Test
	public void testFindAll() {
		UserService userService = (UserService) act.getBean("userService");
		List<User> list = userService.findAll();
		for (User u : list) {
			System.out.println(u.toString());
		}

	}
	
	@Test
	public void testFindById() {
		UserService userService = (UserService) act.getBean("userService");
		User u = userService.findById(3);
		System.out.println(u);
	}
	
	@Test
	public void testDeleteUser() {
		UserService userService = (UserService) act.getBean("userService");
		userService.deleteUser(3);;
	}
	
	@Test
	public void testAddUser() {
		UserService userService = (UserService) act.getBean("userService");
		User u = new User();
		u.setName("123");
		u.setAge(33);
		userService.addUser(u);
	}
	
	@Test
	public void testUpdateUser() {
		UserService userService = (UserService) act.getBean("userService");
		User u = new User();
		u.setName("123");
		u.setAge(33);
		u.setId(2);
		userService.updateUser(u);
	}

	@AfterClass
	public static void after() throws IOException {
		sqlSession.close();
	}

}

各個測試方法均測試通過,說明我們的spring + mybatis環境整合成功。

三、整合springmvc或者struts(這里介紹springmvc)

1、web.xml中配置springmvc

<servlet>
	<servlet-name>SpringMVC</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:springmvc.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>SpringMVC</servlet-name>
	<!-- 此處可以可以配置成*.do,對應struts的后綴習慣 -->
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

2. springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	
	
	<!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器 -->
	<context:component-scan base-package="com.area.controller" />
	<!--避免IE執行AJAX時,返回JSON出現下載文件 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />	<!-- JSON轉換器 -->
			</list>
		</property>
	</bean>
	<!-- 定義跳轉的文件的前后綴 ,視圖模式配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 這里的配置我的理解是自動給后面action的方法return的字符串加上前綴和后綴,變成一個 可用的url地址 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那么配置文件中也不必引入上傳組件包 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 默認編碼 -->
		<property name="defaultEncoding" value="utf-8" />
		<!-- 文件大小最大值 -->
		<property name="maxUploadSize" value="10485760000" />
		<!-- 內存中的最大值 -->
		<property name="maxInMemorySize" value="40960" />
	</bean>

</beans>

3.  編寫controller層

@Controller
public class UserController {
	@Resource
	private UserService userService;

	@RequestMapping("/test")
	public void test() {
		List<User> list = userService.findAll();
		for (User u : list) {
			System.out.println(u);
		}
	}

}

通過瀏覽器測試:

OK,一切正常!ssm框架整合成功!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM