Spring整合SpringMVC
(1)创建web工程,最后勾选自动创建web.xml文件
(2)导包
(3)实体类
package entity;
public class UserInfo { private Integer id; private String name; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UserInfo(Integer id, String name, String password) { super(); this.id = id; this.name = name; this.password = password; } public UserInfo(String name, String password) { super(); this.name = name; this.password = password; } public UserInfo() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "UserInfo [id=" + id + ", name=" + name + ", password=" + password + "]"; }
}
|
(4)创建dao包->>定义方法
package dao;
import entity.UserInfo;
public interface UserInfoMapper { public UserInfo login(UserInfo userInfo); }
|
(5)创建UserInfoMapper.xml->>实现方法
<?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.UserInfoMapper"> <resultMap type="entity.UserInfo" id="userInfoResult"> <id column="id" property="id" /> <result property="name" column="name" /> <result property="password" column="password" /> </resultMap> <select id="login" parameterType="entity.UserInfo" resultMap="userInfoResult"> select * from userInfo where name=#{name} and password=#{password} </select> </mapper> |
(6)创建db.properties
driver=oracle.jdbc.OracleDriver url=jdbc:oracle:thin:@localhost:1521:orcl username=test01 password=123456 |
(7)创建batis-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> <!-- 加载属性文件 --> <properties resource="db.properties"> </properties> <!-- 定义别名 --> <typeAliases> <typeAlias type="entity.UserInfo" alias="UserInfo"/> </typeAliases> <!-- 配置batis文件 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- 到最后需要注释掉 --> <mappers> <mapper resource="dao/UserInfoMapper.xml"/> </mappers> </configuration> |
(8)创建tools包,创建工具类DBUtils.java
package tools;
import java.io.IOException; import java.io.Reader;
import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class DBUtils { private static SqlSessionFactory factory; static { try { //读取配置文件 Reader reader = Resources.getResourceAsReader("batis-config.xml"); //创建SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** * 打开session * @param flag * @return */ public static SqlSession getSession(boolean flag) { return factory.openSession(flag); } /** * 关闭session * @param session */ public static void close(SqlSession session) { if(session!=null) { session.close(); } } /** * 事务回滚 * @param session */ public static void rollback(SqlSession session) { if(session!=null) { session.rollback(); } } /** * 事务提交 * @param session */ public static void commit(SqlSession session) { if(session!=null) { session.commit(); } }
}
|
(6)创建Testdao.java
package testDao;
import org.apache.ibatis.session.SqlSession; import org.junit.Test;
import dao.UserInfoMapper; import entity.UserInfo; import tools.DBUtils;
public class testUserInfo { @Test public void testLogin() { SqlSession session=null; session=DBUtils.getSession(true); UserInfo userInfo=new UserInfo("Tom","123");
UserInfo user = session.selectOne("dao.UserInfoMapper.login",userInfo); //UserInfo user = session.getMapper(UserInfoMapper.class).login(userInfo); if(user==null) { System.out.println("登录失败!"); }else { System.out.println("登录成功!"); }
if(session!=null) { session.close(); } }
}
|
(5创建service包,定义方法,接口UserInfoService.java
package service;
import entity.UserInfo;
public interface UserInfoService { public UserInfo login(UserInfo userInfo); }
|
(6)创建service.impl包,实现方法UserInfoServiceImpl.java
package service.impl;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service;
import dao.UserInfoMapper; import entity.UserInfo; import service.UserInfoService;
@Service("userInfoService") public class UserInfoServiceImpl implements UserInfoService { @Autowired @Qualifier("userInfoMapper") UserInfoMapper mapper;
public UserInfoMapper getMapper() { return mapper; }
public void setMapper(UserInfoMapper mapper) { this.mapper = mapper; }
@Override public UserInfo login(UserInfo userInfo) { return mapper.login(userInfo); }
}
|
(7)创建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 加载属性文件 --> <!-- <context:property-placeholder location="classpath:db.properties" /> --> <!-- 配置数据源 --> <bean id="dataSource" destroy-method="close" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="oracle.jdbc.OracleDriver" /> <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl" /> <property name="user" value="test01" /> <property name="password" value="123456" /> <property name="maxPoolSize" value="40" /> <property name="minPoolSize" value="1" /> <!--初始化连接数 --> <property name="initialPoolSize" value="1" /> <!--连接的最大空闲时间,超时的连接将被丢弃,单位:秒 --> <property name="maxIdleTime" value="60" /> <!--没有连接可用时,等待连接的时间,单位:毫秒 --> <property name="checkoutTimeout" value="2000" /> </bean> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:batis-config.xml"></property> </bean> <!-- 扫描包 --> <context:component-scan base-package="dao,service" /> <!-- 配置实现类(接口) --> <bean id="userInfoMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="dao.UserInfoMapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="trancManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事务规则 --> <tx:advice id="txAdvice" transaction-manager="trancManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="query*" propagation="SUPPORTS" read-only="true" /> <tx:method name="login" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <aop:pointcut id="pointCut" expression="execution(* service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" /> </aop:config>
<bean id="service" class="service.impl.UserInfoServiceImpl"> <property name="mapper" ref="userInfoMapper"></property> </bean> <!-- 到后面可注释 --> </beans> |
(8)创建TestService.java
package serviceTest;
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import entity.UserInfo; import service.UserInfoService;
public class TestUser {
@Test public void testLogin() { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); UserInfoService service=(UserInfoService) context.getBean("service"); UserInfo user=new UserInfo("Tom","123"); if(service.login(user ) == null) { System.out.println("fail"); }else { System.out.println("succ"); } } }
|
(9)创建spring-mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 扫描Controller包 --> <context:component-scan base-package="controller"></context:component-scan> <!-- 一键式配置,通过注解的方式进行Spring MVC开发 --> <mvc:annotation-driven /> <!-- 配置解析器,mapping:将静态资源映射到指定的路径下 location:本地静态资源文件所在的目录 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> |
(10)配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Demo02</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>
<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> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
</web-app> |
(11)创建Controller
package controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
import entity.UserInfo; import service.UserInfoService;
@Controller//标注一个普通的JavaBean成为可以处理请求的控制器 public class UserInfoController { @Autowired @Qualifier("userInfoService") UserInfoService userInfoService;
public UserInfoService getUserInfoService() { return userInfoService; }
public void setUserInfoService(UserInfoService userInfoService) { this.userInfoService = userInfoService; }
@RequestMapping("/login.do")//通过请求URL进行映射 public String login(UserInfo user) { System.out.println(user); if(userInfoService.login(user)!=null) { return "index"; } return "login"; } @RequestMapping("/login.html") public String loginIndex() { return "login"; }
}
|
(12)创建jsp文件夹,创建jsp页面,login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>登录界面</title> </head> <body> <div> <form action="${pageContext.request.contextPath}/login.do" method="post"> 登录名:<input type="text" name="name" value="Tom"><br> 密码:<input type="password" name="password" value="123"><br> <input type="submit" value="登录"> </form> </div> </body> </html> |