在如今的Java Web开发过程中,各种各样框架层出不穷。在工作中,框架的使用也越来越频繁。
今天介绍一下如今比較流行的SpringMVC、Mybatis和Spring框架。学习一下怎样在项目中使用它们。本次项目的创建使用maven来完毕。
1、使用maven创建web项目。选择Maven Project,catalogs选择webapps,输入groupId,artifactId,完毕就可以。
2、在pom.xml中引入相关的依赖:
<properties> <spring.version>3.2.12.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> </dependency> <!-- spring依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.5</version> </dependency> <!-- jsp相关依赖 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>test</scope> </dependency> </dependencies>
2、创建spring配置文件
在src下创建applicationContext.xml,内容临时为空。
3、在web.xml中引入spring
在web.xml中加入例如以下内容:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
4、添加spring-mvc配置
在WEB-INF下添加spring-servlet.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.demo.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
在web.xml中引入例如以下内容:
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
在此处要特别注意:servlet-name假设是spring。则springmvc的配置文件就必须是spring-servlet.xml
5、mybatis配置
在src下创建mybatis的配置文件mybatis-config.xml,内容例如以下:
<?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" /> <setting name="lazyLoadingEnabled" value="false" /> <setting name="defaultStatementTimeout" value="30" /> </settings> <mappers> <mapper resource="mybatis/UserMapper.xml" /> </mappers> </configuration>
在applicationContext.xml文件里配置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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <context:component-scan base-package="com.demo" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean>
当中jdbc.properties文件也在src下:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost/test jdbc.username=root jdbc.password=root6、创建model、dao、service
UserModel:
package com.demo.model; public class UserModel { private int id; private String name; private int age; private String address; //get set方法 }
UserDaoImpl:
package com.demo.dao.impl; import java.util.List; import org.mybatis.spring.support.SqlSessionDaoSupport; import com.demo.dao.UserDao; import com.demo.model.UserModel; public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { public boolean insert(UserModel user) { int count = getSqlSession().insert("insertUser", user); if(count > 0) { return true; } return false; } public boolean update(UserModel user) { return true; } public boolean delete(String userid) { return true; } public UserModel getUser(int userid) { List<UserModel> list = getSqlSession().selectList("selectUserById", userid); return list != null && list.size() > 0 ? list.get(0) : null; } public List<UserModel> getAllUser() { // TODO Auto-generated method stub return null; } }
UserServiceImpl:
package com.demo.service.impl; import org.springframework.beans.factory.annotation.Autowired; import com.demo.dao.UserDao; import com.demo.model.UserModel; import com.demo.service.UserService; public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public boolean insertUser(UserModel user) { return userDao.insert(user); } }
UserController:
package com.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.demo.model.UserModel; import com.demo.service.UserService; @Controller @RequestMapping("/user/") public class UserController { @Autowired private UserService userService; @RequestMapping("addUser.do") public String addUser() { return "addUser"; } @RequestMapping("saveUser.do") public ModelAndView saveUser(UserModel userModel) { ModelAndView mv = new ModelAndView(); boolean b = userService.insertUser(userModel); if(b) { mv.setViewName("addUserSuccess"); } else { mv.setViewName("addUserFail"); } return mv; } }
在applicationContext.xml中配置UserDao和UserService:
<bean id="userDao" class="com.demo.dao.impl.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <bean id="userService" class="com.demo.service.impl.UserServiceImpl" />
在src/mybatis下创建User相关的数据库操作:
<?7、前台页面: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="user"> <resultMap type="com.demo.model.UserModel" id="UserModel"> <result column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> <result column="address" property="address" jdbcType="VARCHAR"/> </resultMap> <insert id="insertUser" parameterType="com.demo.model.UserModel"> insert into t_user(`name`,`age`,`address`) values( #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{address,jdbcType=VARCHAR} ); </insert> <select id="selectUserById" parameterType="INTEGER" resultMap="UserModel"> select `id`,`name`,`age`,`address` from t_user where `id` = #{userid,jdbcType=INTEGER}; </select> <select id="selectAllUser" resultType="com.demo.model.UserModel"> select `id`,`name`,`age`,`address` from t_user </select> </mapper>
在WEB-INF/page下创建页面。该路径在sprng-servlet.xml中。
addUser.jsp内容例如以下:
<form action="${pageContext.request.contextPath }/user/saveUser.do"> <table> <tr> <td>姓名</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age" /></td> </tr> <tr> <td>地址</td> <td><input type="text" name="address" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交" /> </td> </tr> </table>
8、启动项目后,通过index.jsp訪问user/addUser.do进入addUser.jsp。输入信息点击提交。将信息插入到数据库,成功后。跳转至addSuccess.jsp