入门实例

1先建个动态项目

2配置web.xml:

  • 配置IOC容器applicationContext.xml的路径和初始化
  • 配置调度控制器DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <!-- 配置Spring IoC配置文件路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <!-- 配置ContextLoaderListener用以初始化Spring IoC容器 -->
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置调度控制器DispatcherServlet -->
    <servlet>
        <!--根据name找到/WEB-INF/dispatcher-servlet.xml作为调度控制器配置文件载入Web工程中 -->
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 使得Dispatcher在服务器启动的时候就初始化 -->
        <load-on-startup>2</load-on-startup>
    </servlet>

    <!-- 地址栏调度控制 -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

3.配置applicationContext.xml

  • 配置数据库数据源DataSource
  • Mybatis
  • 数据源数据管理事务器
  • 自动扫描哪些mapper bean
<?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:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- 使用注解配置 -->
	<context:annotation-config />

	<!-- 数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/chapter14" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
		<property name="maxActive" value="255" />
		<property name="maxIdle" value="5" />
		<property name="maxWait" value="10000" />
	</bean>

	<!-- 集成mybatis -->
	<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!--指定映射器路径-->
		<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
	</bean>

	<!-- 配置数据源事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 采用自动扫描方式创建mapper bean -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="basePackage" value="com.ssm.chapter14" />
	    <property name="SqlSessionFactory" ref="SqlSessionFactory" />
	    <property name="annotationClass" value="org.springframework.stereotype.Repository" />
	</bean>
</beans>

2.1由于classpath:/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>

    <!-- 指定映射器路径 -->
    <mappers>
        <mapper resource="com/ssm/chapter14/mapper/RoleMapper.xml" />
    </mappers>
</configuration>

3.配置dispatcher-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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- 使用注解驱动 -->
	<mvc:annotation-driven />

	<!-- 定义扫描装载been的包 -->
	<context:component-scan base-package="com.*" />

	<!-- 定义视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
			<!-- 将Web工程/WEB-INF/JSP文件夹,且文件结尾为jsp的文件作为视图渲染 -->
		p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

	<!-- 如果有配置数据库事务,需要开启注解事务的,需要开启这段代码 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

4.写个简单的pojo对象Role

package com.ssm.chapter14.pojo;

public class Role {
	private Long id;
	private String roleName;
	private String note;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}

}

5.写个Role对应的接口DAO,用于数据访问层

package com.ssm.chapter14.dao;

import org.springframework.stereotype.Repository;

import com.ssm.chapter14.pojo.Role;

@Repository
public interface RoleDao {

	public Role getRole(Long id);
}

6.写个RoleMapper.xml,用于映射DAO

<?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.ssm.chapter14.dao.RoleDao">
	<select id="getRole" parameterType="long" resultType="com.ssm.chapter14.pojo.Role">
		select id, role_name as roleName, note from t_role where id = #{id}
	</select>
</mapper>

7.写个业务层,接口和实现分开实现藕松

package com.ssm.chapter14.service;

import com.ssm.chapter14.pojo.Role;

public interface RoleService {

	public Role getRole(Long id);
}

package com.ssm.chapter14.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ssm.chapter14.dao.RoleDao;
import com.ssm.chapter14.pojo.Role;
import com.ssm.chapter14.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

    //业务层调用数据访问层
	@Autowired
	private RoleDao roleDao = null;

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Role getRole(Long id) {
		return roleDao.getRole(id);
	}

}

8.写控制层

package com.ssm.chapter14.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.ssm.chapter14.pojo.Role;
import com.ssm.chapter14.service.RoleService;

@Controller
//url映射
@RequestMapping("/role")
public class RoleController {
	// 注入角色服务类,控制层调用业务层
	@Autowired
	private RoleService roleService = null;

    //url映射
	@RequestMapping(value = "/getRole", method = RequestMethod.GET)
	//此时地址栏应该是http://localhost:8080/项目名/role/getRole.do?id=x
	//参数为地址栏传进来的参数id
	public ModelAndView getRole(@RequestParam("id") Long id) {
		Role role = roleService.getRole(id);
		ModelAndView mv = new ModelAndView();
		//设置渲染视图名称为roleDetails
		mv.setViewName("roleDetails");
		//根据视图解析器定义,应该创建个/WEB-INF/jsp/roleDetails.jsp文件进行渲染

		// 给数据模型添加一个角色对象
		mv.addObject("role", role);
		return mv;
	}

<!--	// 获取角色
	@RequestMapping(value = "/getRole2", method = RequestMethod.GET)
	public ModelAndView getRole2(@RequestParam("id") Long id) {
		Role role = roleService.getRole(id);
		ModelAndView mv = new ModelAndView();
		mv.addObject("role", role);
		// 指定视图类型为json
		mv.setView(new MappingJackson2JsonView());
		return mv;
	}-->
}

5.创建个/WEB-INF/jsp/roleDetails.jsp文件进行渲染

<%@ page pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>out标签的使用</title>
</head>
<body>
</body>
<center>
	<table border="1">
		<tr>
			<td>标签</td>
			<td></td>
		</tr>
		<tr>
			<td>角色编号</td>
			//使用了JSTL和EL语言进行优化
			<td><c:out value="${role.id}"></c:out></td>
		</tr>
		<tr>
			<td>角色名称</td>
			<td><c:out value="${role.roleName}"></c:out></td>
		</tr>
		<tr>
			<td>角色备注</td>
			<td><c:out value="${role.note}"></c:out></td>
		</tr>
	</table>
</center>
</html>
08-07 02:37