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

一直用ssm在開發項目,以前都是直接copy別人的項目,今天趁着項目剛剛交付,本身搭建一下ssm環境,作個記錄html

1、建立項目、引入jar包,由於版本不同,就不貼出這部分的內容了。我的平時的習慣是,先將核心jar包引入,在測試是若是有須要添加的,在額外加入,一堆jar包也不太好記。java

2、首先項目中配置springmysql

 一、項目web.xml中配置web

<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>

二、構建項目結構以下圖(代碼見下方):spring

2.1實體類Usersql

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

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

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進行注入spring-mvc

@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和事物的配置,裏邊有詳細的配置註釋,這裏再也不贅述mybatis

<?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環境整合成功。

3、整合springmvc或者struts(這裏介紹springmvc)

一、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框架整合成功!

相關文章
相關標籤/搜索