记录下自己用idea来搭建SSM框架的步骤。为新手指指路,也为自己留个后路!
由于ssm框架有很多jar包需要导入,因此我们选择用maven来管理项目。如果有不会创建maven项目的同学,请参考我的这篇文章 : IDEA创建maven项目
网上整合出的pom文件代码有很多,新手可以不必自己一个个收集jar包。
这里直接放出完整的代码,内涵注释,先不多做解释~直接替换都行!
粘贴完以后,记得点import changes哦!
然后赶紧做下一步,别傻等着jar下完~人生很短暂!且打代码且珍惜!
<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>xx.xxxxgroupId>
<artifactId>ssmartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>ssm Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring.version>4.3.5.RELEASEspring.version>
<mybatis.version>3.4.1mybatis.version>
<jstl.version>1.2jstl.version>
properties>
<dependencies>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.7version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.41version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>${jstl.version}version>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
先按照我给的图创建好项目结构。
差不多是一个标准ssm的项目架构,架构说明这块写的有误的地方请大家指正!
目录名 | 说明 |
---|---|
controller | 控制器,写接口的地方 |
dao | 数据交互层 |
pojo | 模型层,放对象,也是mvc中的model层 |
service | 业务逻辑层 |
impl | 业务实现层 |
utils | 存放工具类 |
mapper | mybatis里调用的sql的xml |
sql | 可以存放被多次调用的相同的sql语句 |
jdbc.properties | 连接数据库的配置文件 |
log4j.properties | 配置log的文件 |
spring-mvc.xml | 配置springmvc的文件 |
spring-mybatis.xml | 配置spring和mybatis的文件 |
这部分大家酌情修改,主要修改包名,数据库连接信息。
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=root
#密码
jdbc.password=123456
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
root>
configuration>
<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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="cn.asghoul.controller"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
<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:tx="http://www.springframework.org/schema/tx"
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">
<context:component-scan base-package="cn.asghoul.service"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="cn.asghoul.pojo"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="cn.asghoul.dao"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
package cn.asghoul.pojo;
public class User {
int id;
String name;
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;
}
}
<mapper namespace="cn.asghoul.dao.UserDao">
<select id="selectUser" resultType="User" parameterType="hashmap">
SELECT * FROM user
<if test="id != null and id != '' ">
<where>
AND id = #{id}
where>
if>
select>
mapper>
package cn.asghoul.dao;
import cn.asghoul.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List<User> selectUser(Map<String,Object> map);
}
package cn.asghoul.service;
import cn.asghoul.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserService {
List<User> selectUser(Map<String,Object> map);
}
package cn.asghoul.service.impl;
import cn.asghoul.dao.UserDao;
import cn.asghoul.pojo.User;
import cn.asghoul.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
@Override
public List selectUser(Map map) {
return userDao.selectUser(map);
}
}
这里我写了2个接口,一个是返回对象,自动转成json的案例。另一个是返回jsp,下面我会把数据挂上jsp。
package cn.asghoul.controller;
import cn.asghoul.pojo.User;
import cn.asghoul.service.UserService;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("")
public class UserController {
@Autowired
UserService userService;
@ResponseBody
@RequestMapping(value = "selectUserAsJson")
public List selectUserAsJson(String id){
List users = new ArrayList<>();
Map map = new HashMap<>();
map.put("id",id);
users = userService.selectUser(map);
return users;
}
@RequestMapping(value = "selectUserAsJsp")
public ModelAndView selectUserAsJsp(String id){
List users = new ArrayList<>();
Map map = new HashMap<>();
map.put("id",id);
users = userService.selectUser(map);
ModelAndView model = new ModelAndView();
model.addObject("users",users);
model.setViewName("index");
return model;
}
}
这里注意,我写的是views文件夹下的那个index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2>Hello World!h2>
<table>
<thead>
<th>
<td>idtd>
<td>nametd>
<td>agetd>
th>
thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}td>
<td>${user.name}td>
<td>${user.age}td>
tr>
c:forEach>
tbody>
table>
body>
html>
<web-app 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"
version="3.1">
<display-name>ssmdisplay-name>
<description>ssm_Alpha_0.0.1description>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<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>
<servlet>
<servlet-name>SpringMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-*.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>SpringMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
首先我们用sql语句,创建一个表,并添加2条数据。
CREATE TABLE `user` (
`id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '张三', '20'), ('2', '李四', '23');
然后我们运行起项目~随后用浏览器访问
http://localhost:8080/ssm/selectUserAsJsp
http://localhost:8080/ssm/selectUserAsJson
可以看到如下的效果
注:这里需要先为项目配置Tomcat,配置过程很简单,大家可以百度一下~
如果你的效果与我一样,那么恭喜你已经成功啦~
如果有问题的同学可以给我留言
如果ok的同学可以再试试下面链接的效果哦~
http://localhost:8080/ssm/selectUserAsJsp?id=1
http://localhost:8080/ssm/selectUserAsJson?id=2