我是根据这篇博客自己学习这个实例的:AndyLizh的专栏 SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
上面的这篇博客里有怎么搭建 Maven 环境,根据数据表自动生成 Mybatis 的Dao层,Service层,Maping xml文件等教程。
下面是我的实例实现的详细步骤、源代码和一些笔记、遇到的问题
Eclipse版本 Neon.1a Release (4.6.1)
apache-maven-3.3.9
数据库 MySQL5.7.12
maven 配置的中央仓库阿里云地址
setting.xml
.
.
<mirrors>
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/public/url>
<mirrorOf>centralmirrorOf>
mirror>
mirrors>
.
.
源代码下载
建好之后会提示下面的错误:
The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path index.jsp
在项目右键 Java Build Path
添加 Tomcat 服务器的依赖
修改 JRE 版本, Edit 更改为 Eclipse 工作空间默认的 JRE 版本,我的是1.8
之后还要在pom.xml文件中声明 jre 的版本(配置pom.xml文件时给出),和你
Java Build Path
中配置的版本要相同,否则 maven update project又会回到1.5版本,这个版本和项目目录下.settings/org.eclipse.wst.common.project.facet.core.xml
的配置有关
...
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>2.3.2version>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
默认的 pom.xml 内容:
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.jxustgroupId>
<artifactId>SSM-Test2artifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>SSM-Test2 Maven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>SSM-Test2finalName>
build>
project>
Maven Project 最重要的就是配置这个 pom.xml 文件,我在引用别人的pom.xml文件时,发生了很多问题,这和 maven 中央仓库的地址应该也有关系。
说到阿里云的maven中央仓库的jar包,在我的测试中,像Spring 和Mybatis 最新的jar包都还没有,需要低一个版本才有
在配置 pom.xml 过程中,遇到了的几个问题:
2.0版本前叫org.codehaus.jackson ,2.0版本之后com.fasterxml.jackson ,配置方式不同
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.5version>
dependency>
<dependency>
<groupId>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.13version>
dependency>
升级 Spring 或者 Mybatis 的版本是,mybatis-spring 包的版本也要跟着升级
spring 版本 4.0.2,Mybatis 的版本为3.2.6时,mybatis-spring的jar包1.2.0就行
spring 版本 4.3.3,Mybatis 的版本为3.4.0时,mybatis-spring的jar包1.3.0才可以
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
org.mybatis.spring.SqlSessionFactoryBean
找不到 配置了mybatis spring 版本的不对
.
Maven引入需要的SSM 框架jar包,修改后:
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.jxustgroupId>
<artifactId>SSM-Test2artifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>SSM-Test2 Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.3.3.RELEASEspring.version>
<mybatis.version>3.4.0mybatis.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-oxmartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.25version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.1.41version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.5version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.9version>
dependency>
dependencies>
<build>
<finalName>SSM-Test2finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>2.3.2version>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
有些jar包并不一定会用到
之后保存,右击项目-maven-update project,如果出现以下的异常
JavaServer Faces 2.2 can not be installed : One or more constraints have not been satisfied.
JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer. SSM-Test2
这是web.xml
文件头信息配置的不正确,原来的2.3,不符合要求。
解决步骤1:web.xml
头信息替换为下面的代码:
web.xml
<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_3_0.xsd"
id="WebApp_ID" version="3.0">
web-app>
解决步骤2:关闭Eclipse,修改项目目录下.settings/org.eclipse.wst.common.project.facet.core.xml
的配置
<installed facet="jst.web" version="2.3"/>
改为
<installed facet="jst.web" version="3.0"/>
重启Eclipse,右击项目-maven-update project(不行,就先移除项目,导入)
具体步骤参考:http://www.cnblogs.com/jebeljebel/p/4421098.html
之后可以在 Java Build Path
中查看自己 maven 下载的jar包。
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_ssm
username=root
password=root
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
注意字符后面不要带空格,特别是当你复制别人的代码时,例如 ‘root ‘,我就是犯了这个错误
包的路径,在创建之后,记得改为自己的路径
spring-mybatis.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.jxust.ssm" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="initialSize" value="${initialSize}">property>
<property name="maxActive" value="${maxActive}">property>
<property name="maxIdle" value="${maxIdle}">property>
<property name="minIdle" value="${minIdle}">property>
<property name="maxWait" value="${maxWait}">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/jxust/ssm/mapping/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jxust.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
通过日志来输出各种调试信息
log4j.properties
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
建表语句和原始数据
mysql> use db_ssm;
Database changed
mysql> CREATE TABLE tb_user(
-> id int(11) NOT NULL AUTO_INCREMENT,
-> user_name varchar(40) NOT NULL,
-> password varchar(40) NOT NULL,
-> age int(4) NOT NULL,
-> PRIMARY KEY(id))
-> ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.33 sec)
mysql> select * from tb_user;
+----+-----------+----------+-----+
| id | user_name | password | age |
+----+-----------+----------+-----+
| 1 | 李白 | 123454 | 23 |
| 2 | 杜甫 | 234234 | 23 |
+----+-----------+----------+-----+
2 rows in set (0.00 sec)
该工具可根据MySQL中的表(tb_user)自动创建实体类、MyBatis映射文件以及Dao接口
参考博文:http://blog.csdn.net/zhshulin/article/details/23912615
红色部分为自动生成的文件,UserMaping.xml里各种包路径,要修改成自己的,尤其是namespace,要关联为创建的UserDao(因为使用了动态代理实现)
你可以自己去尝试自动创建,下面给出这3个文件(注释是我加的)。
User.java
package com.jxust.ssm.pojo;
/**
* 用户实体类
* 对应数据表tb_user
* @author Peng
* @Date2016年12月10日下午10:30:16
*/
public class User {
private Integer id;
private String userName;
private String password;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";
}
}
UserDao.java
package com.jxust.ssm.dao;
import com.jxust.ssm.pojo.User;
/**
* User类Dao层接口
*
* 之前我们会在dao层自己手动实现dao层然后自动注入SqlSessionTemplate 实例
* 来调用具体的方法 比如 insert("","") selectOne("","") 等方法
* 其中第一个参数就是映射文件的地址: namespace+id 而第二个参数就是传递的条件这样mybatis
* 就会按照我们传递的这两个参数找到具体的映射文件进行解析查询。
* 而这里使用动态代理就省去了我们实现dao接口的这一步骤,而是由spring提我们实现了
* @author Peng
* @Date2016年12月10日下午10:31:27
*/
public interface UserDao {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
自动创建的文件中,有增删改查的各种方法,动态SQL等,如果你想了解详细的使用方法:http://blog.csdn.net/peng_hong_fu/article/details/53235271
UserMapper.xml
<mapper namespace="com.jxust.ssm.dao.UserDao">
<resultMap id="BaseResultMap" type="com.jxust.ssm.pojo.User">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
resultMap>
<sql id="Base_Column_List">
id, user_name, password, age
sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.Integer">
select
<include refid="Base_Column_List" />
from tb_user
where id = #{id,jdbcType=INTEGER}
select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from
tb_user
where id = #{id,jdbcType=INTEGER}
delete>
<insert id="insert" parameterType="com.jxust.ssm.pojo.User">
insert into tb_user (id,
user_name, password,
age)
values (#{id,jdbcType=INTEGER},
#{userName,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
insert>
<insert id="insertSelective" parameterType="com.jxust.ssm.pojo.User">
insert into tb_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
if>
<if test="userName != null">
user_name,
if>
<if test="password != null">
password,
if>
<if test="age != null">
age,
if>
trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
if>
<if test="age != null">
#{age,jdbcType=INTEGER},
if>
trim>
insert>
<update id="updateByPrimaryKeySelective" parameterType="com.jxust.ssm.pojo.User">
update tb_user
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
if>
set>
where id = #{id,jdbcType=INTEGER}
update>
<update id="updateByPrimaryKey" parameterType="com.jxust.ssm.pojo.User">
update tb_user
set
user_name = #{userName,jdbcType=VARCHAR},
password =
#{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id =
#{id,jdbcType=INTEGER}
update>
mapper>
UserService.java
package com.jxust.ssm.service;
import com.jxust.ssm.pojo.User;
/**
* Service层接口
* @author Peng
* @Date2016年12月11日下午7:05:05
*/
public interface UserService {
//根据id查找
public User getUserById(Integer userid);
//添加一条数据
public int insert(User user);
}
UserServiceImpl.java
package com.jxust.ssm.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jxust.ssm.dao.UserDao;
import com.jxust.ssm.pojo.User;
import com.jxust.ssm.service.UserService;
/**
* userService 接口的实现类
*
* @author Peng
* @Date2016年12月11日上午11:50:01
*/
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
/**
* 因为没有在spring的文件中显式的声明userService实现类,直接通过getBean得到 userService 会找不到
* 需要显式配置 @Service ("userService"),指定bean的名称
* 相当与
*/
@Resource
private UserDao userDao;
public User getUserById(Integer userid) {
return this.userDao.selectByPrimaryKey(userid);
}
@Override
public int insert(User user) {
return this.userDao.insert(user);
}
}
使用Junit测试,TestMyBatis为使用 spring 的测试方法,TestMyBatis2为不使用 spring 的普通方法
TestMyBatis.java
package com.test;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.jxust.ssm.pojo.User;
import com.jxust.ssm.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
/**
* 测试spring整合mybatis spring方式
*
* @author Peng
* @Date2016年12月11日上午11:52:56
*/
public class TestMyBatis {
private static Logger logger = Logger.getLogger(TestMyBatis.class);
@Resource
private UserService userService = null;
/**
* 测试查询
*/
@Test
public void test1() {
User user = userService.getUserById(2);
logger.info("值:" + user.getUserName());
logger.info(JSON.toJSONString(user));
}
/**
* 测试添加
*/
@Test
public void test2() {
User user = new User();
user.setUserName("杜甫3");
user.setPassword("234234");
user.setAge(23);
int count = userService.insert(user);
logger.info("count:" +count);
}
}
TestMyBatis2.java
package com.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jxust.ssm.pojo.User;
import com.jxust.ssm.service.UserService;
/**
* 测试spring整合mybatis 普通方式
* @author Peng
* @Date2016年12月11日上午11:52:11
*/
public class TestMyBatis2 {
private ApplicationContext ac = null;
private UserService userService = null;
@Before
public void before() {
ac = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");
userService = (UserService) ac.getBean("userService");
}
/**
* 测试查询
*/
@Test
public void test1() {
User user = userService.getUserById(2);
System.out.println(user.toString());
}
/**
* 测试添加
*/
@Test
public void test2() {
User user = new User();
user.setUserName("杜甫");
user.setPassword("234234");
user.setAge(23);
int count = userService.insert(user);
System.out.println("插入"+count+"条数据成功");
}
}
测试结果:
...
[org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
[com.test.TestMyBatis] - 值:杜甫
[com.test.TestMyBatis] - {"age":23,"id":2,"password":"234234","userName":"杜甫"}
[org.springframework.context.support.GenericApplicationContext] - Closing org.springframework.context.support.GenericApplicationContext@55d56113: startup date [Sun Dec 11 20:23:43 CST 2016]; root of context hierarchy
正确输入结果,则测试成功!
项目结构为:
SpringMVC 涉及到视图了,需要配置web.xml文件
和SpringMVC的配置文件了
web.xml
web.xml
<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_3_0.xsd"
id="WebApp_ID" version="3.0">
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mybatis.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springDispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springDispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
使用 Eclipse在 web.xml 文件中,可以使用
Alt+/
快速创建ContextLoaderListener
和DispatcherServlet
两个过滤器配置
springmvc.xml
springmvc.xml
<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:mvc="http://www.springframework.org/schema/mvc"
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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.jxust.ssm.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
bean>
beans>
spring配置文件和springmvc配置文件的两个自动扫描的路径范围,最好不要重复,使用
和
指定不扫描和扫描的条件
UserController.java
package com.jxust.ssm.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.jxust.ssm.pojo.User;
import com.jxust.ssm.service.UserService;
@Controller
public class UserController {
/**
* 使用@Autowired也可以,@Autowired默认按类型装配
* @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
*/
@Resource
private UserService userService;
/**
* 测试查询
*
* @param id
* @param model
* @return
*/
@RequestMapping("/showUser")
public String testtoshowUser(@RequestParam(value = "id") Integer id, Model model) {
System.out.println("id:" + id);
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "showUser";
}
/**
* 测试添加数据
*
* @param id
* @param model
* @return
*/
@RequestMapping("/insertUser")
public String testinsertUser() {
User user = new User();
user.setUserName("李清照");
user.setPassword("3232322");
user.setAge(22);
int count = userService.insert(user);
System.out.println("插入" + count + "条数据成功");
return "showUser";
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsptitle>
head>
<body>
<a href="showUser?id=2">ShowUser pagea><br>
<a href="insertUser">insertUser a>
body>
html>
showUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试title>
head>
<body>
id:${user.id} <br>
userName: ${user.userName} <br>
password: ${user.password} <br>
age: ${user.age} <br>
body>
html>
JSP页面写完,就可以发布了
Maven 项目就是小,没有jar包,只有 30k
源代码下载:http://download.csdn.net/detail/peng_hong_fu/9708357