SpringMVC框架学习(2)--SpringMVC和Mybatis的整合

整个项目源码的下载地址:源码--FishRoad

整个项目的目录结构如下:

以上是整个项目的目录以及所用的jar包。

web.xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>FishRoad</display-name>

  <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/spring-*.xml</param-value>
	</context-param>

	<!-- 过滤器,所有文件参数用UTF-8编译 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- spring请求配置,指向springmvc的核心配置文件,并且定义所有以.xhtml结尾的请求都被springmvc拦截 ,加载顺序为1 -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- spring内存监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

spring-mvc.xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 扫描controller -->
	<context:component-scan base-package="com.fishroad.controller" />
	<!-- 扫描service层 -->
	<context:component-scan base-package="com.fishroad.service" />

	<!-- 视图模式下的前缀和后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/page/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 启动注解和POJO(java基本类) -->
	<bean
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
	</bean>

</beans>

spring-mybatis.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">

	<!-- 引入数据库配置文件 -->
	<!-- <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:/config/property/jdbc.properties" />
	</bean> -->

	<!-- 数据库配置 -->
<!-- 	<bean id="dataSource_1" class="org.apache.commons.dbcp.BasicDataSource" -->
<!-- 		destroy-method="close"> -->
<!-- 		<property name="driverClassName" value="${dataSource_1.diverClassName}" /> -->
<!-- 		<property name="url" value="${dataSource_1.url}" /> -->
<!-- 		<property name="username" value="${dataSource_1.username}" /> -->
<!-- 		<property name="password" value="${dataSource_1.password}" /> -->
<!-- 		<property name="initialSize" value="${dataSource_1.initialSize}" /> -->
<!-- 		<property name="maxActive" value="${dataSource_1.maxActive}" /> -->
<!-- 		<property name="maxIdle" value="${dataSource_1.maxIdle}" /> -->
<!-- 		<property name="minIdle" value="${dataSource_1.minIdle}" /> -->
<!-- 		<property name="maxWait" value="${dataSource_1.maxWait}" /> -->
<!-- 		<property name="testWhileIdle" value="${dataSource_1.testWhileIdle}" /> -->
<!-- 		<property name="timeBetweenEvictionRunsMillis" -->
<!-- 			value="${dataSource_1.timeBetweenEvictionRunsMillis}" /> -->
<!-- 		<property name="numTestsPerEvictionRun" value="${dataSource_1.numTestsPerEvictionRun}" /> -->
<!-- 		<property name="minEvictableIdleTimeMillis" value="${dataSource_1.minEvictableIdleTimeMillis}" /> -->
<!-- 		<property name="poolPreparedStatements" value="${dataSource_1.poolPreparedStatements}" /> -->
<!-- 		<property name="maxOpenPreparedStatements" value="${dataSource_1.maxOpenPreparedStatements}" /> -->
<!-- 		<property name="defaultAutoCommit" value="${dataSource_1.defaultAutoCommit}" /> -->
<!-- 		<property name="removeAbandoned" value="${dataSource_1.removeAbandoned}" /> -->
<!-- 		<property name="removeAbandonedTimeout" value="${dataSource_1.removeAbandonedTimeout}" /> -->
<!-- 		<property name="logAbandoned" value="${dataSource_1.logAbandoned}" /> -->
<!-- 	</bean> -->

	<!-- 数据库连接 -->
	<bean id="dataSource_1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
		<property name="username" value="sit_tis" />
		<property name="password" value="sit_tis" />
		<property name="maxIdle" value="5" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="timeBetweenEvictionRunsMillis" value="120000" />
		<property name="validationQuery" value="SELECT 1 FROM DUAL" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testOnBorrow" value="true" />
		<property name="removeAbandoned" value="true"></property>
		<property name="removeAbandonedTimeout" value="30"></property>
	</bean>

	<!-- 扫描dao层的接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.fishroad.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- 扫描dao层的xml文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource_1" />
		<property name="mapperLocations" value="classpath:com/fishroad/dao/*.xml"></property>
	</bean>

	<!-- 事物管理 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource_1" />
	</bean>

</beans>

userList.jsp内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<form action="./loginResult.xhtml">
	 <b>遍历List集合的全部元素:</b>
     <br>
     <c:forEach items="${user}" var="vo" >
     	${vo.userId} ${vo.userName}<br>
     </c:forEach>
     <br>
</form>
</body>
</html>

UserController 如下:

package com.fishroad.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fishroad.service.UserServiceImpl;
import com.fishroad.vo.User;

@RequestMapping("/user")
@Controller
public class UserController {

	@Resource
	private UserServiceImpl userService;

	@RequestMapping("/userlist")
	public String queryUserList(HttpServletRequest request, User user,
			Model model) {

		List<User> vo = userService.queryUserList();

		model.addAttribute("user", vo);

		return "userList";
	}

}

IUserService.java 文件如下:

package com.fishroad.service;

import java.util.List;

import com.fishroad.vo.User;

public interface IUserService {

	List<User> queryUserList();

}

UserServiceImpl.java文件如下:

package com.fishroad.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fishroad.dao.UserDaoMapper;
import com.fishroad.vo.User;

@Service("userService")
public class UserServiceImpl implements IUserService {

	@Resource
	private UserDaoMapper userDao;

	@Override
	public List<User> queryUserList() {
		return userDao.queryUserList();
	}

}

UserDaoMapper.java接口如下:

package com.fishroad.dao;

import java.util.List;

import com.fishroad.vo.User;

public interface UserDaoMapper {

	List<User> queryUserList();

}

UserDaoMapper.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="com.fishroad.dao.UserDaoMapper">
	<!-- 用户登录方法 -->
	<select id="queryUserList" resultType="com.fishroad.vo.User">
	select userid as userId,username as username
	from sys_user
	where effectflag='E'

	</select>
</mapper>

User.java 文件:

package com.fishroad.vo;

public class User {

	private String userId;
	private String userName;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

}
时间: 2024-10-08 08:57:26

SpringMVC框架学习(2)--SpringMVC和Mybatis的整合的相关文章

SpringMVC框架学习笔记(1)——HelloWorld

搭建SpringMVC框架 1.添加jar包 jsp-api.jar servlet-api.jar jstl.jar commons-logging-1.1.1.jar spring-beans-4.1.6.RELEASE.jar spring-context-4.1.6.RELEASE.jar spring-core-4.1.6.RELEASE.jar spring-expression-4.1.6.RELEASE.jar spring-tx-4.1.6.RELEASE.jar spring

SpringMVC框架学习笔记(二)

6. 源码分析(了解) 通过前端控制器源码分析springmvc的执行过程. 第一步:前端控制器接收请求 调用doDispatch 第二步:前端控制器调用处理器映射器查找 Handler 第三步:调用处理器适配器执行Handler,得到执行结果ModelAndView 第四步:视图渲染,将model数据填充到request域. 视图解析,得到view: 调用view的渲染方法,将model数据填充到request域 渲染方法: 7. 入门程序小结 通过入门程序理解springmvc前端控制器.处

SpringMVC框架学习

Spring MVC 通过一套 MVC 注解,可以让 POJO 成为处理请求的控制器,无须实现任何接口 1. 搭建环境: 1). 加入 jar 包: commons-logging-1.1.1.jar spring-aop-4.0.0.RELEASE.jar spring-beans-4.0.0.RELEASE.jar spring-context-4.0.0.RELEASE.jar spring-core-4.0.0.RELEASE.jar spring-expression-4.0.0.RE

SpringMVC框架学习笔记(4)——结果跳转方式

1.设置ModelAndView对象.根据View和视图解析器跳转到指定页面(视图解析器前缀+viewname+视图解析器后缀) @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { ModelAndView mv = new ModelAndView(); mv.setViewName("hello"); mv.a

SpringMVC框架学习笔记(2)——使用注解开发SpringMVC

1.配置web.xml <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-v

Java SpringMVC框架学习(三)springMVC的执行流程

具体执行逻辑如下: 浏览器提交请求到中央调度器. 中央调度器将请求转给处理器映射器. 处理器映射器根据请求, 找到请求对应的处理器, 并将其封装为处理器执行链返回给中央调度器. 中央调度器根据处理器执行链中的处理器, 找到能够执行该处理器的适配器. 适配器调用执行处理器. 处理器将处理结果以及要跳转的视图封装到一个对象ModelAndView中, 并将其返回给处理器适配器. 适配器将结果返回给中央调度器. 中央调度器调用视图解析器, 将ModelAndView中的视图名封装为视图对象. 视图解析

SpringMVC框架学习笔记(3)——controller配置汇总

1.通过URL对应bean <!-- 配置handlerMapper 映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- 配置Controller 自定义控制器 --> <bean name="/hello.do" class="cn.sxt.controller.HelloCo

SpringMVC框架学习笔记——各种异常、报错解决

1.Target runtime com.genuitec.runtime.generic.jee60 is not defined. 找到导入项目的.setting文件夹org.eclipse.wst.common.project.facet.core.xml文件 删除<runtime name="com.genuitec.runtime.generic.jee60"/>这一段 2.Implementation of project facet jst.web.jstl

Java SpringMVC框架学习(二)httpServeltRequest和Model传值的区别

为什么大多程序在controller中给jsp传值时使用model.addAttribute()而不使用httpServeletRequest.setAttribute()? 事实上model数据,最终spring也是写到HttpServletRequest属性中,只是用model更符合mvc设计,减少各层间耦合. @RequestMapping(value="/list",method=RequestMethod.GET) public String list(Model model