目录
IDE使用的是eclipse(虽然IDEA更好用,但eclipse可能在工作中更通用,还是得用熟才行),搭建SSM项目之前,需要配置好如下环境:
以及eclipse的插件:
当你配置好Maven环境后,就可以在eclipse中直接创建Maven项目。
File->New->Other->【Maven Project】->不勾选Create a simple project
(图2.1.1 创建Maven Project)
点击Next->选择webapp
输入Group Id(组织名)与Artifact Id(项目名),然后它就会帮我们自动生成好一个包名。
点击Finish,这样就创建好了一个Maven工程,以下是目录结构。
可以看到项目现在是报错了,那是因为还没有引入所需要的jar包,接下来是要导入项目所需要的包。
创建好项目后,先加入Tomact库,项目->右键菜单->BuildPath->Configure Build Path->Libraries->Add Library->选中Server Runtime->Next->选中你的Tomcat版本->Finish。
打开项目下的pom.xml文件(所有jar包依赖都写在这个文件中,进行统一管理),并将以下内容复制粘贴到\标签之后即可,使用Ctrl+S保存xml文件。
导入的依赖如下所示:
<properties>
<spring.version>4.3.5.RELEASEspring.version>
<mybatis.version>3.2.7mybatis.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
<junit.version>4.9junit.version>
properties>
<dependencies>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.4.0.Finalversion>
dependency>
<dependency>
<groupId>javax.validationgroupId>
<artifactId>validation-apiartifactId>
<version>2.0.1.Finalversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
<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>aopalliancegroupId>
<artifactId>aopallianceartifactId>
<version>1.0version>
dependency>
<dependency>
<groupId>org.ow2.asmgroupId>
<artifactId>asmartifactId>
<version>4.2version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.13version>
dependency>
<dependency>
<groupId>cglibgroupId>
<artifactId>cglibartifactId>
<version>2.2.2version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.7version>
dependency>
<dependency>
<groupId>dom4jgroupId>
<artifactId>dom4jartifactId>
<version>1.6.1version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>javax.servlet.jsp.jstlgroupId>
<artifactId>jstl-apiartifactId>
<version>1.2version>
<exclusions>
<exclusion>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
exclusion>
<exclusion>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.glassfish.webgroupId>
<artifactId>jstl-implartifactId>
<version>1.2version>
<exclusions>
<exclusion>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
exclusion>
<exclusion>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
exclusion>
<exclusion>
<groupId>javax.servlet.jsp.jstlgroupId>
<artifactId>jstl-apiartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.apache.taglibsgroupId>
<artifactId>taglibs-standard-implartifactId>
<version>1.2.5version>
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.2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.36version>
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>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.13version>
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>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
plugins>
build>
(注意\标签下的JRE版本与你的Java环境是否一致,不一致需要进行修改)
写入了pom.xml文件后,我们还需要更新Maven项目,选中项目->右键菜单->Maven->Update Project->选择ok,此时eclips开始自动下载pom.xml中所指定的jar包。
如果你是第一次整合ssm,我强烈建议你就按照以下的文件命名方式。
ssm框架的需要配置的文件如下:
创建好如下的文件目录结构(包名、文件名可以自己进行修改),文件目录如下:
创建好文件目录之后,我们就可以开始写配置文件了,注意按照自己的目录结构修改每个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"
version="3.0">
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="mapperLocations" value="classpath:/com/rhine/studySSM/mapper/*.xml">property>
<property name="configLocation" value="classpath:SqlMapConfig.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rhine.studySSM.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.rhine.studySSM.service.impl.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
aop:config>
<context:component-scan base-package="com.rhine.studySSM.service"/>
beans>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///testconn
jdbc.username=root
jdbc.password=abc123456
最好加上jdbc前缀,以防止命名冲突,使得spring创建DataSource的bean失败。
<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"
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:component-scan base-package="com.rhine.studySSM.controller" />
<mvc:annotation-driven enable-matrix-variables="true" />
<mvc:default-servlet-handler />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
bean>
beans>
<configuration>
<typeAliases>
<package name="com.rhine.studySSM.domain"/>
typeAliases>
configuration>
以上,我们就完成了SSM(spring+spring mvc+mybatis)的整合,接下来,就以一个用户登录的例子,完成一次前端与后台的请求和响应。
为了之后查阅每一层中的代码格式方便,所以特意在文章中贴上了几乎所有的代码。如果你不想在文章中查看具体的代码细节,可直接在文末查看代码的下载地址。
字段名 | 类型 | 主键 | Not NULL |
---|---|---|---|
id | int | √ | √ |
name | varchar | √ | |
password | varchar | √ |
sql脚本如下:
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'rhine', 'abc123');
INSERT INTO `user` VALUES ('2', 'cyy', 'abc123');
所有的前端页面都防止在webapp文件夹中。
文件目录结构如下所示:
<%@ 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>
<h1>用户登录h1>
<hr/>
<form action="${pageContext.request.contextPath }/user/login" method="POST">
用户名:<input type="text" name="name"><br>
密 码:<input type="password" name="password"><br>
<input type="submit" value="登录">
form>
body>
html>
注意\标签中的name属性必须与User类中的字段名一一对应。
<%@ 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>Indextitle>
head>
<body>
<h1>登录失败!请重新登录!h1>
body>
html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Indextitle>
head>
<body>
<h1>你好<c:out value="${sessionScope.user.name }"/>, 早上好!h1>
body>
html>
通过session获取到用户名,并使用jstl标签打印在页面上。
你如果学习过ssm框架,那你对后台代码的结构应该完全不陌生。
package com.rhine.studySSM.domain;
import java.io.Serializable;
@SuppressWarnings("serial")
public class User implements Serializable{
private Integer id;
private String name;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
与数据库中的字段名一一对应,如果不同,则需要设置别名。
package com.rhine.studySSM.mapper;
import org.springframework.stereotype.Repository;
import com.rhine.studySSM.domain.User;
@Repository
public interface UserMapper {
User userlogin(User user);
}
<mapper namespace="com.rhine.studySSM.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.rhine.studySSM.domain.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="passsword" jdbcType="VARCHAR" property="password"/>
resultMap>
<select id="userlogin" parameterType="com.rhine.studySSM.domain.User" resultType="com.rhine.studySSM.domain.User">
SELECT * FROM user WHERE name=#{name} AND password=#{password}
select>
mapper>
package com.rhine.studySSM.service;
import com.rhine.studySSM.domain.User;
public interface IUserService {
User userlogin(User user);
}
package com.rhine.studySSM.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.rhine.studySSM.domain.User;
import com.rhine.studySSM.mapper.UserMapper;
import com.rhine.studySSM.service.IUserService;
@Service
public class UserService implements IUserService{
@Resource
UserMapper userMapper;
@Override
public User userlogin(User user) {
return userMapper.userlogin(user);
}
}
package com.rhine.studySSM.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
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.rhine.studySSM.domain.User;
import com.rhine.studySSM.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService userService;
@RequestMapping("/login")
public String login(User user, Model model, HttpServletRequest req) {
HttpSession session = req.getSession();
if(user != null) {
User loginUser = userService.userlogin(user);
if(loginUser != null) {
System.out.println("登录成功");
session.setAttribute("user", loginUser);
return "homepage/index";
}else {
System.out.println("登录失败");
return "fail";
}
}
return "fail";
}
}
在tomcat中运行程序,并根据数据库user表中的已有数据,进行登录,效果如下:
(早上开始写的,写完都中午了,还早上好…哈哈。写博客还是挺花时间的,不过后面回顾起来更省时间!)
SSM就已经整合完成了,现在有了这个模板,就不需要每次都去重复的配置项目了,省去了很多事情。
gitee地址:https://gitee.com/Rhine/StudySSM