1.新建一个maven web app项目
结构如下
resources的资源文件如下
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" 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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- @Component, @Repository, @Service, @Controller, @Autowired, @Resources --> <!-- 用注解进行开发 --> <context:annotation-config></context:annotation-config> <!-- 注解扫描包 --> <context:component-scan base-package="com.demo"> <!-- 这里不加载Controller的bean --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 1. 数据源 --> <!-- 读取db.properties文件. 读取到数据库信息 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 2. 创建sqlSessionFactory ==> mybatis核心配置文件的读取 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 3.扫描mybatis的mapper接口路径 --> <!-- 这个bean可以把我们的mapper接口直接扫描到. 直接把接口扫描完. 注册到spring的bean中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!-- 会在提供的base包下寻找interface .根据interface的名字. 将首字母小写生成这个接口所对应的bean --> <property name="basePackage" value="com.demo.mapper"></property> </bean> <!-- 4.事务处理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txManager" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="search*" read-only="true"/> <tx:method name="select*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.demo.service.*.*.*(..))" id="cut"/> <aop:advisor advice-ref="txManager" pointcut-ref="cut"/> </aop:config> <!-- 用注解处理事务 <tx:annotation-driven transaction-manager="transactionManager"/> --> </beans>
applicationContext-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 开启注解. 扫描 --> <context:annotation-config></context:annotation-config> <context:component-scan base-package="com.demo.controller"></context:component-scan> <!-- 过滤掉js, jpg, png, css, 静态文件 --> <mvc:default-servlet-handler/> <!-- 开启mvc --> <mvc:annotation-driven /> <!-- 地址解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
db.properties 记得修改用户名和密码
# 219.168.23.10 线上服务器地址 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=##### jdbc.password=#####
log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG,Console # Console output... log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.org.apache=INFO
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><!-- mybatis的核心配置 --> <!-- mybatis的运行配置 --> <settings> <!-- 开启二级缓存 --> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <!-- 如果这个属性是true,那么你的类中, 任何一个方法被执行.都要去加载属性, 这个时候懒加载是没有效果的. --> <setting name="aggressiveLazyLoading" value="false"/> </settings> </configuration>
StuMapper.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.demo.mapper.StuMapper" > <resultMap id="BaseResultMap" type="com.demo.pojo.Stu" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List" > id, name, age </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from student where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from student where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.demo.pojo.Stu" > insert into student (id, name, age ) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER} ) </insert> <insert id="insertSelective" parameterType="com.demo.pojo.Stu" > insert into student <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> <if test="age != null" > age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> <if test="age != null" > #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.demo.pojo.Stu" > update student <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null" > age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.demo.pojo.Stu" > update student set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> <select id="getAllStu" resultMap="BaseResultMap"> select * from student </select> </mapper>
以上resources的配置文件完毕
2.下面是web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 读取除了mvc外的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/applicationContext.xml</param-value> </context-param> <!-- 整个web容器的动向由这个监听器进行监听. 这个监听器可以监听项目的启动. 从而直接加载核心配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 给出spring的路径 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup><!-- 当web容器加载的时候, 初始化spring --> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern><!-- 所有 --> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> </web-app>
3.下面是pom.xml的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.offcn.maven</groupId> <artifactId>ssm-01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.1</version> <scope>provided</scope> </dependency> <!--实现slf4j接口并整合--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> <scope>provided</scope> </dependency> <!--druid==>阿里巴巴数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.25</version> </dependency> <!--2.dao框架:MyBatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--mybatis自身实现的spring整合依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!--3.Servlet web相关依赖--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--4:spring依赖--> <!--1)spring核心依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.14.RELEASE</version> </dependency> <!--2)spring dao层依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.14.RELEASE</version> </dependency> <!--3)springweb相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.14.RELEASE</version> </dependency> <!--4)spring test相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <!--Aop要导入的包--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
4.jsp页面
list.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>Insert title here</title>
</head>
<body>
<a href="/stu/goToAdd">增加学生</a>
<table border="1" width="100%">
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${stuList }" var="stu">
<tr>
<td>${stu.id }</td>
<td>${stu.name }</td>
<td>${stu.age }</td>
<td><a href="/stu/goToUpdate?id=${stu.id }">修改</a></td>
<td><a href="/stu/del?id=${stu.id }">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
add.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>Insert title here</title> </head> <body> <form action="/stu/add" > 名字:<input id="name" type="text" name="name"> 年龄:<input id="age" type="text" name="age"> <input type="submit" value="提交"> </form> </body> </html>
update.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>Insert title here</title> </head> <body> <form action="/stu/update" > id:<input type="text" name="id" value="${stu.id}" readonly="readonly"> 名字:<input id="name" type="text" name="name" value="${stu.name}"> 年龄:<input id="age" type="text" name="age" value="${stu.age}"> <input type="submit" value="提交" > </form> </body> </html>
index.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/6/9 Time: 15:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 欢迎光临 <a href="/stu/list">点击跳转到列表页面</a> </body> </html>
5.以下是src的文件
contrlloer
package com.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.demo.pojo.Stu; import com.demo.service.StuService; @Controller @RequestMapping("stu") public class StuController { @Autowired private StuService stuService; @RequestMapping("list") public String list(Model model) { List<Stu> stuList = stuService.getAllStu(); model.addAttribute("stuList", stuList); return "list"; } @RequestMapping("goToAdd") public String goToAdd() { return "add"; } @RequestMapping("add") public String add(Stu stu) { stuService.insert(stu); return "redirect:list"; } @RequestMapping("goToUpdate") public String goToUpdate(Integer id, Model model) { Stu stu = stuService.selectByPrimaryKey(id); model.addAttribute("stu", stu); return "update"; } @RequestMapping("update") public String update(Stu stu) { stuService.updateByPrimaryKeySelective(stu); return "redirect:list"; } @RequestMapping("del") public String del(Integer id){ stuService.deleteByPrimaryKey(id); return "redirect:list"; } }
service接口
package com.demo.service; import java.util.List; import com.demo.pojo.Stu; public interface StuService { public List<Stu> getAllStu(); void insert(Stu stu); Stu selectByPrimaryKey(Integer id); void updateByPrimaryKeySelective(Stu stu); void deleteByPrimaryKey(Integer id); }
service接口实现类
package com.demo.service.imple; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.demo.mapper.StuMapper; import com.demo.pojo.Stu; import com.demo.service.StuService; @Service public class StuServiceImple implements StuService { @Autowired private StuMapper stuMapper; @Override public List<Stu> getAllStu() { return stuMapper.getAllStu(); } @Override public void insert(Stu stu) { stuMapper.insert(stu); } @Override public Stu selectByPrimaryKey(Integer id) { return stuMapper.selectByPrimaryKey(id); } @Override public void updateByPrimaryKeySelective(Stu stu) { stuMapper.updateByPrimaryKeySelective(stu); } @Override public void deleteByPrimaryKey(Integer id) { stuMapper.deleteByPrimaryKey(id); } }
mapper(或者Dao)
package com.demo.mapper; import java.util.List; import com.demo.pojo.Stu; public interface StuMapper { public List<Stu> getAllStu(); public Stu getById(int id); int deleteByPrimaryKey(Integer id); int insert(Stu record); int insertSelective(Stu record); Stu selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Stu record); int updateByPrimaryKey(Stu record); }
pojo实体类
package com.demo.pojo; public class Stu { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
以上就是一个学生信息的小Demo 大家可以尝试下哦