徒手搭建 SpringMVC / Spring3 / Mybatis3 集成開發環境
準備環境:spring-framework-3.2.6 + Mybatis-3.1.1 + mybatis-spring(集成包)
準備spring-framework-3.2.6.RELEASE\libs下所有的jar包導入工程。
另準備如下圖jar包:

例中使用的數據庫結構:[表名User]
首先需要讓容器知道如何啟動 Spring MVC 以及 Spring:
1、配置 Spring MVC 的 DispatcherServle 默認截取所有請求 "/" , 并設置讀取文件路徑及名稱(文件名自定義)
2、配置 Spring
首先把 包 的結構創建出來。

/WEB-INF/applicationContext-dao.xml dao 層 bean 的依賴注入,這里是XML配置,可以寫 Annotation
/WEB-INF/applicationContext-service.xml service 層 bean 的依賴注入。
新建 /WEB-INF/applicationContext-common.xml
新建 /WEB-INF/Configuration.xml
創建 User 類 在 com.ssm.domain 包下:
創建 User 類的 映射文件 。
配置 applicationContext-dao.xml
新建 dao 層中的 接口與實現類:
配置 applicationContext-service.xml
新建 service 曾 需要的 接口與實現類
配置 Spring MVC 核心配置文件:applicationContext-controller.xml
新建 com.ssm.web.contorller.LoginContorller
最后,在web.xml 中添加 Spring 的字符過濾器
準備spring-framework-3.2.6.RELEASE\libs下所有的jar包導入工程。
另準備如下圖jar包:
例中使用的數據庫結構:[表名User]
1、配置 Spring MVC 的 DispatcherServle 默認截取所有請求 "/" , 并設置讀取文件路徑及名稱(文件名自定義)
1 <!-- Spring MVC DispatcherServlet Init -->
2 <servlet>
3 <servlet-name>springMVC</servlet-name>
4 <servlet-class>
5 org.springframework.web.servlet.DispatcherServlet
6 </servlet-class>
7 <init-param>
8 <param-name>contextConfigLocation</param-name>
9 <param-value>
10 /WEB-INF/applicationContext-Controller.xml
11 </param-value>
12 </init-param>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>springMVC</servlet-name>
17 <url-pattern>/</url-pattern>
18 </servlet-mapping>
2 <servlet>
3 <servlet-name>springMVC</servlet-name>
4 <servlet-class>
5 org.springframework.web.servlet.DispatcherServlet
6 </servlet-class>
7 <init-param>
8 <param-name>contextConfigLocation</param-name>
9 <param-value>
10 /WEB-INF/applicationContext-Controller.xml
11 </param-value>
12 </init-param>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>springMVC</servlet-name>
17 <url-pattern>/</url-pattern>
18 </servlet-mapping>
2、配置 Spring
1 <!-- 讀取Spring 配置 -->
2 <context-param>
3 <param-name>contextConfigLocation</param-name>
4 <param-value>
5 /WEB-INF/applicationContext-common.xml,
6 /WEB-INF/applicationContext-dao.xml,
7 /WEB-INF/applicationContext-service.xml,
8 </param-value>
9 </context-param>
10 <listener>
11 <listener-class>
12 org.springframework.web.context.ContextLoaderListener
13 </listener-class>
14 </listener>
2 <context-param>
3 <param-name>contextConfigLocation</param-name>
4 <param-value>
5 /WEB-INF/applicationContext-common.xml,
6 /WEB-INF/applicationContext-dao.xml,
7 /WEB-INF/applicationContext-service.xml,
8 </param-value>
9 </context-param>
10 <listener>
11 <listener-class>
12 org.springframework.web.context.ContextLoaderListener
13 </listener-class>
14 </listener>
首先把 包 的結構創建出來。
/WEB-INF/applicationContext-Controller.xml Spring MVC 的核心配置
/WEB-INF/applicationContext-common.xml Spring 事務 與 MyBatis SqlSessionFactory的管理/WEB-INF/applicationContext-dao.xml dao 層 bean 的依賴注入,這里是XML配置,可以寫 Annotation
/WEB-INF/applicationContext-service.xml service 層 bean 的依賴注入。
新建 /WEB-INF/applicationContext-common.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xmlns:tx="http://www.springframework.org/schema/tx"
7 xsi:schemaLocation="http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/aop
10 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context-2.5.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
15
16 <!-- 代替 Mybatis 配置訪問數據庫連接 -->
17 <bean id="dataSource"
18 class="org.apache.commons.dbcp.BasicDataSource">
19 <property name="driverClassName"
20 value="com.mysql.jdbc.Driver">
21 </property>
22 <property name="url"
23 value="jdbc:mysql://localhost:3306/springmvc3mybatis3">
24 </property>
25 <property name="username" value="root"></property>
26 <property name="password" value="123456"></property>
27 </bean>
28
29 <!-- 配置mybatis固定的寫法 -->
30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
31 <property name="dataSource" ref="dataSource"/> <!-- 這里讀取Mybatis的核心配置文件 -->
32 <property name="configLocation" value="/WEB-INF/Configuration.xml"/>
33 </bean>
34 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
35 <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
36 </bean>
37
38 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
39 <property name="dataSource">
40 <ref bean="dataSource" />
41 </property>
42 </bean>
43
44 <tx:advice id="txAdvice" transaction-manager="transactionManager">
45 <tx:attributes>
46 <tx:method name="append*" propagation="REQUIRED"/>
47 <tx:method name="remove*" propagation="REQUIRED"/>
48 <tx:method name="modify*" propagation="REQUIRED"/>
49 <tx:method name="*" read-only="true"/>
50 </tx:attributes>
51 </tx:advice>
52
53 <aop:config>
54 <aop:pointcut id="all" expression="execution(* com.ssm.service.impl.*.*(..))"/>
55 <aop:advisor advice-ref="txAdvice" pointcut-ref="all"/>
56 </aop:config>
57
58 </beans>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xmlns:tx="http://www.springframework.org/schema/tx"
7 xsi:schemaLocation="http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/aop
10 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context-2.5.xsd
13 http://www.springframework.org/schema/tx
14 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
15
16 <!-- 代替 Mybatis 配置訪問數據庫連接 -->
17 <bean id="dataSource"
18 class="org.apache.commons.dbcp.BasicDataSource">
19 <property name="driverClassName"
20 value="com.mysql.jdbc.Driver">
21 </property>
22 <property name="url"
23 value="jdbc:mysql://localhost:3306/springmvc3mybatis3">
24 </property>
25 <property name="username" value="root"></property>
26 <property name="password" value="123456"></property>
27 </bean>
28
29 <!-- 配置mybatis固定的寫法 -->
30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
31 <property name="dataSource" ref="dataSource"/> <!-- 這里讀取Mybatis的核心配置文件 -->
32 <property name="configLocation" value="/WEB-INF/Configuration.xml"/>
33 </bean>
34 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
35 <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
36 </bean>
37
38 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
39 <property name="dataSource">
40 <ref bean="dataSource" />
41 </property>
42 </bean>
43
44 <tx:advice id="txAdvice" transaction-manager="transactionManager">
45 <tx:attributes>
46 <tx:method name="append*" propagation="REQUIRED"/>
47 <tx:method name="remove*" propagation="REQUIRED"/>
48 <tx:method name="modify*" propagation="REQUIRED"/>
49 <tx:method name="*" read-only="true"/>
50 </tx:attributes>
51 </tx:advice>
52
53 <aop:config>
54 <aop:pointcut id="all" expression="execution(* com.ssm.service.impl.*.*(..))"/>
55 <aop:advisor advice-ref="txAdvice" pointcut-ref="all"/>
56 </aop:config>
57
58 </beans>
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
4 <configuration>
5 <typeAliases> <!-- 需要 User 的實體類 -->
6 <typeAlias alias="User" type="com.ssm.domain.User"/>
7 </typeAliases>
8 <mappers> <!-- 需要 User 的 映射文件-->
9 <mapper resource="com/ssm/domain/User.xml"/>
10 </mappers>
11 </configuration>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
4 <configuration>
5 <typeAliases> <!-- 需要 User 的實體類 -->
6 <typeAlias alias="User" type="com.ssm.domain.User"/>
7 </typeAliases>
8 <mappers> <!-- 需要 User 的 映射文件-->
9 <mapper resource="com/ssm/domain/User.xml"/>
10 </mappers>
11 </configuration>
1 package com.ssm.domain;
2
3 public class User {
4 private int id ;
5 private String username ;
6 private String password ;
7
8 public String getUsername() {
9 return username;
10 }
11 public void setUsername(String username) {
12 this.username = username;
13 }
14 public String getPassword() {
15 return password;
16 }
17 public void setPassword(String password) {
18 this.password = password;
19 }
20 public int getId() {
21 return id;
22 }
23 public void setId(int id) {
24 this.id = id;
25 }
26 }
2
3 public class User {
4 private int id ;
5 private String username ;
6 private String password ;
7
8 public String getUsername() {
9 return username;
10 }
11 public void setUsername(String username) {
12 this.username = username;
13 }
14 public String getPassword() {
15 return password;
16 }
17 public void setPassword(String password) {
18 this.password = password;
19 }
20 public int getId() {
21 return id;
22 }
23 public void setId(int id) {
24 this.id = id;
25 }
26 }
創建 User 類的 映射文件 。
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
3 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
4 <mapper namespace="com.ssm.domain">
5
6 <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
7 <insert id="insert" parameterType="com.ssm.domain.User"
8 useGeneratedKeys="true" keyProperty="id">
9 <![CDATA[
10 INSERT INTO
11 user (
12 username,
13 password
14 ) VALUES (
15 #{username,jdbcType=VARCHAR},
16 #{password,jdbcType=VARCHAR}
17 )
18 ]]>
19 <!--
20 oracle: order="BEFORE" SELECT sequenceName.nextval AS ID FROM DUAL
21 DB2: order="BEFORE"" values nextval for sequenceName
22 <selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="userId">
23 SELECT sequenceName.nextval AS ID FROM DUAL
24 </selectKey>
25 -->
26 </insert>
27
28 <update id="update" parameterType="com.ssm.domain.User">
29 <![CDATA[
30 UPDATE user SET
31 username = #{username,jdbcType=VARCHAR},
32 password = #{password,jdbcType=VARCHAR}
33 WHERE
34 id = #{id,jdbcType=INTEGER}
35 ]]>
36 </update>
37
38 <delete id="delete" parameterType="com.ssm.domain.User">
39 delete from user where id = #{id}
40 </delete>
41
42 <select id="selectById" resultType="com.ssm.domain.User"
43 parameterType="Integer">
44 select * from user where id = #{id}
45 </select>
46
47 <select id="selectAll" resultType="com.ssm.domain.User">
48 select * from user;
49 </select>
50
51 <delete id="deleteByPrimaryKey" parameterType="Integer">
52 delete from user where id = #{id}
53 </delete>
54 </mapper>
2 <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
3 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
4 <mapper namespace="com.ssm.domain">
5
6 <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
7 <insert id="insert" parameterType="com.ssm.domain.User"
8 useGeneratedKeys="true" keyProperty="id">
9 <![CDATA[
10 INSERT INTO
11 user (
12 username,
13 password
14 ) VALUES (
15 #{username,jdbcType=VARCHAR},
16 #{password,jdbcType=VARCHAR}
17 )
18 ]]>
19 <!--
20 oracle: order="BEFORE" SELECT sequenceName.nextval AS ID FROM DUAL
21 DB2: order="BEFORE"" values nextval for sequenceName
22 <selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="userId">
23 SELECT sequenceName.nextval AS ID FROM DUAL
24 </selectKey>
25 -->
26 </insert>
27
28 <update id="update" parameterType="com.ssm.domain.User">
29 <![CDATA[
30 UPDATE user SET
31 username = #{username,jdbcType=VARCHAR},
32 password = #{password,jdbcType=VARCHAR}
33 WHERE
34 id = #{id,jdbcType=INTEGER}
35 ]]>
36 </update>
37
38 <delete id="delete" parameterType="com.ssm.domain.User">
39 delete from user where id = #{id}
40 </delete>
41
42 <select id="selectById" resultType="com.ssm.domain.User"
43 parameterType="Integer">
44 select * from user where id = #{id}
45 </select>
46
47 <select id="selectAll" resultType="com.ssm.domain.User">
48 select * from user;
49 </select>
50
51 <delete id="deleteByPrimaryKey" parameterType="Integer">
52 delete from user where id = #{id}
53 </delete>
54 </mapper>
配置 applicationContext-dao.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans
3 xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7 <bean id="userDaoRef" class="com.ssm.dao.mybatis.impl.UserMybatisDaoImpl">
8 <property name="sqlSession" ref="sqlSession"></property>
9 </bean>
10 </beans>
2 <beans
3 xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7 <bean id="userDaoRef" class="com.ssm.dao.mybatis.impl.UserMybatisDaoImpl">
8 <property name="sqlSession" ref="sqlSession"></property>
9 </bean>
10 </beans>
新建 dao 層中的 接口與實現類:
1 package com.ssm.dao;
2
3 public interface IBaseDao {
4
5 }
2
3 public interface IBaseDao {
4
5 }
1 package com.ssm.dao;
2
3 import java.util.List;
4
5 import com.ssm.domain.User;
6
7 public interface IUserDao extends IBaseDao {
8
9 public boolean insert(User user);
10
11 public boolean delete(int id);
12
13 public boolean update(User user);
14
15 public List<User> findAll();
16
17 public User findById(int id);
18 }
2
3 import java.util.List;
4
5 import com.ssm.domain.User;
6
7 public interface IUserDao extends IBaseDao {
8
9 public boolean insert(User user);
10
11 public boolean delete(int id);
12
13 public boolean update(User user);
14
15 public List<User> findAll();
16
17 public User findById(int id);
18 }
1 package com.ssm.dao.mybatis.impl;
2
3 import com.ssm.dao.IBaseDao;
4
5 public class BaseMybatisDaoImpl implements IBaseDao {
6
7 }
2
3 import com.ssm.dao.IBaseDao;
4
5 public class BaseMybatisDaoImpl implements IBaseDao {
6
7 }
1 package com.ssm.dao.mybatis.impl;
2
3 import java.util.List;
4
5 import org.mybatis.spring.SqlSessionTemplate;
6
7 import com.ssm.dao.IUserDao;
8 import com.ssm.domain.User;
9
10 public class UserMybatisDaoImpl implements IUserDao {
11 /*sql 語句*/
12 private static final String INSERT = "insert";
13
14 private static final String UPDATE = "update";
15
16 private static final String DELETE = "delete";
17
18 private static final String SELECTALL = "selectAll";
19
20 private static final String SELECTBYID = "selectById";
21
22 private SqlSessionTemplate sqlSession;
23
24 public SqlSessionTemplate getSqlSession() {
25 return sqlSession;
26 }
27
28 public void setSqlSession(SqlSessionTemplate sqlSession) {
29 this.sqlSession = sqlSession;
30 }
31
32 public boolean delete(int id)
33 {
34 // TODO Auto-generated method stub
35 String sql = this.getStatementId(User.class, DELETE);
36 sqlSession.delete(sql, id);
37 return true;
38 }
39
40 public List<User> findAll()
41 {
42 // TODO Auto-generated method stub
43 String sql = this.getStatementId(User.class, SELECTALL);
44 List<User> list = (List<User>)sqlSession.selectList(sql);
45 return list;
46 }
47
48 public User findById(int id)
49 {
50 // TODO Auto-generated method stub
51 String sql = this.getStatementId(User.class, SELECTBYID);
52 User stu = (User)sqlSession.selectOne(sql, id);
53 return stu;
54 }
55
56 public boolean insert(User stu)
57 {
58 // TODO Auto-generated method stub
59 String sql = this.getStatementId(User.class, INSERT);
60 this.sqlSession.insert(sql, stu);
61 return true;
62 }
63
64 public boolean update(User stu)
65 {
66 // TODO Auto-generated method stub
67 String sql = this.getStatementId(User.class, UPDATE);
68 this.sqlSession.update(sql, stu);
69 return true;
70 }
71
72 /**
73 * 映射sqlid
74 */
75 private String getStatementId(Class entityClass, String suffix)
76 {
77 String sqlStr = entityClass.getName() + "." + suffix;
78 System.out.println("getStatementId:" + sqlStr);
79 return sqlStr;
80 }
81 }
2
3 import java.util.List;
4
5 import org.mybatis.spring.SqlSessionTemplate;
6
7 import com.ssm.dao.IUserDao;
8 import com.ssm.domain.User;
9
10 public class UserMybatisDaoImpl implements IUserDao {
11 /*sql 語句*/
12 private static final String INSERT = "insert";
13
14 private static final String UPDATE = "update";
15
16 private static final String DELETE = "delete";
17
18 private static final String SELECTALL = "selectAll";
19
20 private static final String SELECTBYID = "selectById";
21
22 private SqlSessionTemplate sqlSession;
23
24 public SqlSessionTemplate getSqlSession() {
25 return sqlSession;
26 }
27
28 public void setSqlSession(SqlSessionTemplate sqlSession) {
29 this.sqlSession = sqlSession;
30 }
31
32 public boolean delete(int id)
33 {
34 // TODO Auto-generated method stub
35 String sql = this.getStatementId(User.class, DELETE);
36 sqlSession.delete(sql, id);
37 return true;
38 }
39
40 public List<User> findAll()
41 {
42 // TODO Auto-generated method stub
43 String sql = this.getStatementId(User.class, SELECTALL);
44 List<User> list = (List<User>)sqlSession.selectList(sql);
45 return list;
46 }
47
48 public User findById(int id)
49 {
50 // TODO Auto-generated method stub
51 String sql = this.getStatementId(User.class, SELECTBYID);
52 User stu = (User)sqlSession.selectOne(sql, id);
53 return stu;
54 }
55
56 public boolean insert(User stu)
57 {
58 // TODO Auto-generated method stub
59 String sql = this.getStatementId(User.class, INSERT);
60 this.sqlSession.insert(sql, stu);
61 return true;
62 }
63
64 public boolean update(User stu)
65 {
66 // TODO Auto-generated method stub
67 String sql = this.getStatementId(User.class, UPDATE);
68 this.sqlSession.update(sql, stu);
69 return true;
70 }
71
72 /**
73 * 映射sqlid
74 */
75 private String getStatementId(Class entityClass, String suffix)
76 {
77 String sqlStr = entityClass.getName() + "." + suffix;
78 System.out.println("getStatementId:" + sqlStr);
79 return sqlStr;
80 }
81 }
配置 applicationContext-service.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans
3 xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7
8 <bean id="userServiceImpl" class="com.ssm.service.impl.UserServiceImpl">
9 <property name="userDaoImpl" ref="userDaoRef"></property>
10 </bean>
11
12 </beans>
2 <beans
3 xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7
8 <bean id="userServiceImpl" class="com.ssm.service.impl.UserServiceImpl">
9 <property name="userDaoImpl" ref="userDaoRef"></property>
10 </bean>
11
12 </beans>
新建 service 曾 需要的 接口與實現類
1 package com.ssm.service;
2
3 import java.util.List;
4
5 import com.ssm.domain.User;
6
7 public interface IUserService {
8 public boolean insert(User user);
9
10 public boolean delete(int id);
11
12 public boolean update(User user);
13
14 public List<User> findAll();
15
16 public User findById(int id);
17 }
2
3 import java.util.List;
4
5 import com.ssm.domain.User;
6
7 public interface IUserService {
8 public boolean insert(User user);
9
10 public boolean delete(int id);
11
12 public boolean update(User user);
13
14 public List<User> findAll();
15
16 public User findById(int id);
17 }
1 package com.ssm.service.impl;
2
3 import java.util.List;
4
5 import com.ssm.dao.IUserDao;
6 import com.ssm.domain.User;
7 import com.ssm.service.IUserService;
8
9 public class UserServiceImpl implements IUserService {
10 private IUserDao userDaoImpl ;
11
12 public IUserDao getUserDaoImpl() {
13 return userDaoImpl;
14 }
15
16 public void setUserDaoImpl(IUserDao userDaoImpl) {
17 this.userDaoImpl = userDaoImpl;
18 }
19
20 public void setStuDao(IUserDao stuDao)
21 {
22 this.userDaoImpl = stuDao;
23 }
24
25 public boolean delete(int id)
26 {
27 // TODO Auto-generated method stub
28 return userDaoImpl.delete(id);
29 }
30
31 public List<User> findAll()
32 {
33 // TODO Auto-generated method stub
34 return userDaoImpl.findAll();
35 }
36
37 public User findById(int id)
38 {
39 // TODO Auto-generated method stub
40 return userDaoImpl.findById(id);
41 }
42
43 public boolean insert(User stu)
44 {
45 // TODO Auto-generated method stub
46 userDaoImpl.insert(stu);
47 return true;
48 }
49
50 public boolean update(User stu)
51 {
52 // TODO Auto-generated method stub
53 return userDaoImpl.update(stu);
54 }
55 }
2
3 import java.util.List;
4
5 import com.ssm.dao.IUserDao;
6 import com.ssm.domain.User;
7 import com.ssm.service.IUserService;
8
9 public class UserServiceImpl implements IUserService {
10 private IUserDao userDaoImpl ;
11
12 public IUserDao getUserDaoImpl() {
13 return userDaoImpl;
14 }
15
16 public void setUserDaoImpl(IUserDao userDaoImpl) {
17 this.userDaoImpl = userDaoImpl;
18 }
19
20 public void setStuDao(IUserDao stuDao)
21 {
22 this.userDaoImpl = stuDao;
23 }
24
25 public boolean delete(int id)
26 {
27 // TODO Auto-generated method stub
28 return userDaoImpl.delete(id);
29 }
30
31 public List<User> findAll()
32 {
33 // TODO Auto-generated method stub
34 return userDaoImpl.findAll();
35 }
36
37 public User findById(int id)
38 {
39 // TODO Auto-generated method stub
40 return userDaoImpl.findById(id);
41 }
42
43 public boolean insert(User stu)
44 {
45 // TODO Auto-generated method stub
46 userDaoImpl.insert(stu);
47 return true;
48 }
49
50 public boolean update(User stu)
51 {
52 // TODO Auto-generated method stub
53 return userDaoImpl.update(stu);
54 }
55 }
配置 Spring MVC 核心配置文件:applicationContext-controller.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/mvc
9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
10 http://www.springframework.org/schema/context
11 http://www.springframework.org/schema/context/spring-context.xsd">
12
13 <!-- 頁面View層基本信息設定 -->
14 <bean id="viewResolver"
15 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16 <property name="prefix" value="/" />
17 <property name="suffix" value=".jsp" />
18 </bean>
19
20 <!-- 支持spring3.0新的mvc注解 -->
21 <mvc:annotation-driven />
22
23 <!-- 對web包中的所有類進行掃描,以完成Bean創建和自動依賴注入的功能 -->
24 <context:component-scan base-package="com.ssm.web.contorller" />
25
26 <!-- 啟動Spring MVC的注解功能,完成請求和注解POJO的映射 -->
27 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
28 <property name="messageConverters">
29 <list>
30 <!-- 這里向Spring配置了JSON的 JAR -->
31 <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
32 </list>
33 </property>
34 </bean>
36 </beans>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/mvc
9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
10 http://www.springframework.org/schema/context
11 http://www.springframework.org/schema/context/spring-context.xsd">
12
13 <!-- 頁面View層基本信息設定 -->
14 <bean id="viewResolver"
15 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16 <property name="prefix" value="/" />
17 <property name="suffix" value=".jsp" />
18 </bean>
19
20 <!-- 支持spring3.0新的mvc注解 -->
21 <mvc:annotation-driven />
22
23 <!-- 對web包中的所有類進行掃描,以完成Bean創建和自動依賴注入的功能 -->
24 <context:component-scan base-package="com.ssm.web.contorller" />
25
26 <!-- 啟動Spring MVC的注解功能,完成請求和注解POJO的映射 -->
27 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
28 <property name="messageConverters">
29 <list>
30 <!-- 這里向Spring配置了JSON的 JAR -->
31 <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
32 </list>
33 </property>
34 </bean>
36 </beans>
新建 com.ssm.web.contorller.LoginContorller
1 package com.ssm.web.contorller;
2
3 import java.util.List;
4
5 import javax.annotation.Resource;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import org.springframework.stereotype.Controller;
9 import org.springframework.web.bind.annotation.PathVariable;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.servlet.ModelAndView;
13 import com.ssm.domain.User;
14 import com.ssm.service.IUserService;
15
16 @Controller
17 @RequestMapping("/user")
18 public class LoginContorller {
19
20 private IUserService userServiceImpl ;
21
22 public IUserService getUserServiceImpl() {
23 return userServiceImpl;
24 }
25 /*
26 * 因為Contorller是通過Annotation注解的
27 * 所以userServiceImpl沒有在XML文件中通過 property 來注冊
28 * 處理方式:同樣用Annotation注冊這個bean
29 */
30 @Resource
31 public void setUserServiceImpl(IUserService userServiceImpl) {
32 this.userServiceImpl = userServiceImpl;
33 }
34
35 /**
36 * 增
37 */
38 @RequestMapping(value = "/insert", method = RequestMethod.POST)
39 public String insert(HttpServletRequest request,
40 HttpServletResponse response, User user)
41 {
42 userServiceImpl.insert(user);
43 return "redirect:/user/allUser";
44 }
45
46 /**
47 * 刪
48 */
49 @RequestMapping("/delete/{id}")
50 public String delete(HttpServletRequest request,
51 HttpServletResponse response, @PathVariable("id")
52 int id)
53 {
54 userServiceImpl.delete(id);
55 return "redirect:/user/allUser";
56 }
57
58 /**
59 * 得到所有
60 */
61 @RequestMapping("/allUser")
62 public ModelAndView allUser(HttpServletRequest request,
63 HttpServletResponse response)
64 {
65 ModelAndView modelAndView = new ModelAndView();
66 List<User> stuList = userServiceImpl.findAll();
67 modelAndView.addObject("userList", stuList);
68 modelAndView.setViewName("allUser");
69 return modelAndView;
70 }
71
72 /**
73 * 修改
74 */
75 @RequestMapping("/pre4Update")
76 public ModelAndView update(HttpServletRequest request,
77 HttpServletResponse response, User user)
78 {
79 ModelAndView modelAndView = new ModelAndView();
80 modelAndView.addObject("user", user);
81 modelAndView.setViewName("updateUser");
82 return modelAndView;
83 }
84 @RequestMapping("/updateUser")
85 public String updateUser(HttpServletRequest request, HttpServletResponse response, User user)
86 {
87 this.userServiceImpl.update(user);
88 return "redirect:/student/allUser";
89 }
90
91 /**
92 * 用于跳轉
93 */
94 @RequestMapping("redir/{url}")
95 public String redir(HttpServletRequest request,
96 HttpServletResponse response, @PathVariable("url")
97 String url)
98 {
99 return url;
100 }
101 }
2
3 import java.util.List;
4
5 import javax.annotation.Resource;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import org.springframework.stereotype.Controller;
9 import org.springframework.web.bind.annotation.PathVariable;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.servlet.ModelAndView;
13 import com.ssm.domain.User;
14 import com.ssm.service.IUserService;
15
16 @Controller
17 @RequestMapping("/user")
18 public class LoginContorller {
19
20 private IUserService userServiceImpl ;
21
22 public IUserService getUserServiceImpl() {
23 return userServiceImpl;
24 }
25 /*
26 * 因為Contorller是通過Annotation注解的
27 * 所以userServiceImpl沒有在XML文件中通過 property 來注冊
28 * 處理方式:同樣用Annotation注冊這個bean
29 */
30 @Resource
31 public void setUserServiceImpl(IUserService userServiceImpl) {
32 this.userServiceImpl = userServiceImpl;
33 }
34
35 /**
36 * 增
37 */
38 @RequestMapping(value = "/insert", method = RequestMethod.POST)
39 public String insert(HttpServletRequest request,
40 HttpServletResponse response, User user)
41 {
42 userServiceImpl.insert(user);
43 return "redirect:/user/allUser";
44 }
45
46 /**
47 * 刪
48 */
49 @RequestMapping("/delete/{id}")
50 public String delete(HttpServletRequest request,
51 HttpServletResponse response, @PathVariable("id")
52 int id)
53 {
54 userServiceImpl.delete(id);
55 return "redirect:/user/allUser";
56 }
57
58 /**
59 * 得到所有
60 */
61 @RequestMapping("/allUser")
62 public ModelAndView allUser(HttpServletRequest request,
63 HttpServletResponse response)
64 {
65 ModelAndView modelAndView = new ModelAndView();
66 List<User> stuList = userServiceImpl.findAll();
67 modelAndView.addObject("userList", stuList);
68 modelAndView.setViewName("allUser");
69 return modelAndView;
70 }
71
72 /**
73 * 修改
74 */
75 @RequestMapping("/pre4Update")
76 public ModelAndView update(HttpServletRequest request,
77 HttpServletResponse response, User user)
78 {
79 ModelAndView modelAndView = new ModelAndView();
80 modelAndView.addObject("user", user);
81 modelAndView.setViewName("updateUser");
82 return modelAndView;
83 }
84 @RequestMapping("/updateUser")
85 public String updateUser(HttpServletRequest request, HttpServletResponse response, User user)
86 {
87 this.userServiceImpl.update(user);
88 return "redirect:/student/allUser";
89 }
90
91 /**
92 * 用于跳轉
93 */
94 @RequestMapping("redir/{url}")
95 public String redir(HttpServletRequest request,
96 HttpServletResponse response, @PathVariable("url")
97 String url)
98 {
99 return url;
100 }
101 }
最后,在web.xml 中添加 Spring 的字符過濾器
1 <!-- 添加過濾器 -->
2 <filter>
3 <filter-name>encodingFilter</filter-name>
4 <filter-class>
5 org.springframework.web.filter.CharacterEncodingFilter
6 </filter-class>
7 <init-param>
8 <param-name>encoding</param-name>
9 <param-value>utf-8</param-value>
10 </init-param>
11 <init-param>
12 <param-name>forceEncoding</param-name>
13 <param-value>true</param-value>
14 </init-param>
15 </filter>
16 <filter-mapping>
17 <filter-name>encodingFilter</filter-name>
18 <url-pattern>/*</url-pattern>
19 </filter-mapping>
2 <filter>
3 <filter-name>encodingFilter</filter-name>
4 <filter-class>
5 org.springframework.web.filter.CharacterEncodingFilter
6 </filter-class>
7 <init-param>
8 <param-name>encoding</param-name>
9 <param-value>utf-8</param-value>
10 </init-param>
11 <init-param>
12 <param-name>forceEncoding</param-name>
13 <param-value>true</param-value>
14 </init-param>
15 </filter>
16 <filter-mapping>
17 <filter-name>encodingFilter</filter-name>
18 <url-pattern>/*</url-pattern>
19 </filter-mapping>
posted on 2014-05-12 18:57 00001000 閱讀(786) 評論(0) 編輯 收藏 所屬分類: SpringMVC3/Spring3/MyBatis3