前言:
本文章适用于在Eclipse上新建一个Maven Web SSM整合的项目,并显示Hello World页面以及连接数据库。
项目搭建:
File → New → Maven Project → Next
选择 maven-archetype-webapp
Group Id:一般填写域名 com.spring
Artifact Id: 一般填写项目名 springdemo
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.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>springdemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springdemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<commons-lang.version>2.6</commons-lang.version>
<slf4j.version>1.7.6</slf4j.version>
<spring.version>4.1.3.RELEASE</spring.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies><!-- 依赖关系管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<!--mybatis核心包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
</dependency>
<!--打印日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<exclusions> <!-- 排除 -->
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- 引入Mybatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.5</version>
</dependency>
</dependencies>
<build> <!-- 插件,和项目关系不大 -->
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.2.v20140723</version>
</plugin>
<!-- jdk版本号 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
metadata-complete="true">
<display-name>springdemo</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- springMVC核心配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 字符集过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/errors/404.jsp</location>
</error-page>
</web-app>
spring-mvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.ssm.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--<mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与
AnnotationMethodHandlerAdapter 两个bean,它解决了一些@controllerz注解使用时的提前配置-->
<!-- 静态资源处理, css, js, images -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- 静态资源可访问的设置方式 -->
<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="/WEB-INF/jsps/"/>
<!--视图解析后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
jdbc.properties(连接数据库 可以配多个数据源)
jdbc_driverClassName = com.mysql.jdbc.Driver
jdbc_url = jdbc:mysql://localhost:3306/sjk1?useSSL=true&useUnicode=true&characterEncoding=utf-8
jdbc_username = abc
jdbc_password = 123
dw_driverClass = com.mysql.jdbc.Driver
dw_jdbcUrl = jdbc:mysql://localhost:3306/sjk2?useSSL=true&useUnicode=true&characterEncoding=utf-8
dw_username = abc
dw_password = 123
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>
<!-- 命名空间 -->
<typeAliases>
<typeAlias alias="User" type="com.ssm.model.User"/>
</typeAliases>
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 4.0.0以后版本可以不设置该参数 -->
<property name="dialect" value="mysql"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
<!-- 和startPage中的pageNum效果一样-->
<property name="offsetAsPageNum" value="true"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true"/>
<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
<!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
<property name="pageSizeZero" value="true"/>
<!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
<property name="reasonable" value="true"/>
<!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
<!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
<!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->
<!-- 不理解该含义的前提下,不要随便复制该配置 -->
<property name="params" value="pageNum=start;pageSize=limit;"/>
<!-- 支持通过Mapper接口参数来传递分页参数 -->
<property name="supportMethodsArguments" value="true"/>
<!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
<property name="returnPageInfo" value="check"/>
</plugin>
</plugins>
</configuration>
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: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.xsd">
<!--引入jdbc配置 -->
<context:property-placeholder location="classpath*:config/jdbc.properties"/>
<!-- 扫描文件(自动将service层注入)-->
<context:component-scan base-package="com.ssm.service"/>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- c3p0连接池 -->
<property name="driverClass" value="${jdbc_driverClassName}"/>
<property name="jdbcUrl" value="${jdbc_url}"/>
<property name="user" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<!--连接池中保存的最大连接数目-->
<property name="maxPoolSize" value="20"/>
<!--连接池中保存的最少连接数目-->
<property name="minPoolSize" value="2"/>
<!-- 初始化连接大小 -->
<property name="initialPoolSize" value="2"/>
<!-- 获取连接最大等待时间 -->
<property name="maxConnectionAge" value="6000"/>
<!-- 连接池最大空闲 -->
<property name="maxIdleTime" value="60"/>
</bean>
<bean id="dataSource01" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${dw_driverClass}" />
<property name="jdbcUrl" value="${dw_jdbcUrl}" />
<property name="user" value="${dw_username}" />
<property name="password" value="${dw_password}" />
<!--连接池中保存的最大连接数目-->
<property name="maxPoolSize" value="20"/>
<!--连接池中保存的最少连接数目-->
<property name="minPoolSize" value="2"/>
<!-- 初始化连接大小 -->
<property name="initialPoolSize" value="2"/>
<!-- 获取连接最大等待时间 -->
<property name="maxConnectionAge" value="6000"/>
<!-- 连接池最大空闲 -->
<property name="maxIdleTime" value="60"/>
</bean>
<bean id="dynamicDataSource" class="com.ssm.test.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 指定lookupKey和与之对应的数据源 -->
<entry key="dataSource01" value-ref="dataSource01"></entry>
<entry key="dataSource" value-ref="dataSource"></entry>
</map>
</property>
<!-- 这里可以指定默认的数据源 -->
<property name="defaultTargetDataSource" ref="dataSource" />
</bean>
<!--配置sqlSessionFactory 并将数据源注入-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dynamicDataSource"/>
<!--指定要使用到到mybatis配置文件-->
<property name="configLocation" value="classpath:config/config.xml"/>
<!--用于配置mapper映射xml-->
<property name="mapperLocations" value="classpath:com/ssm/dao/*.xml"/>
</bean>
<!-- 创建数据映射器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao"/>
</bean>
<!-- 对数据源进行事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
DynamicDataSource.java
package com.ssm.test;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 从自定义的位置获取数据源标识
return DynamicDataSourceHolder.getDataSource();
}
}
DynamicDataSourceHolder.java
package com.ssm.test;
public class DynamicDataSourceHolder {
/**
* 注意:数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
*/
private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();
public static String getDataSource() {
return THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
UserService.java
package com.ssm.service;
import java.util.List;
import com.ssm.model.User;
public interface UserService {
public boolean login(String username,String password) throws Exception;
public List<User> findAll() throws Exception;
}
UserServiceImpl.java
package com.ssm.service.impl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import com.ssm.dao.IUserDao;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ssm.model.User;
import com.ssm.service.UserService;
@Service("UserService")
public class UserServiceImpl implements UserService{
/**
* 注入UserMapper接口
*/
@Autowired
IUserDao Mapper;
//登录方法的实现,从jsp页面获取username与password
public boolean login(String username, String password) {
User user = Mapper.selectByName(username);
if (user != null) {
if (user.getUsername().equals(username) && user.getPassword().equals(password))
return true;
}
return false;
}
public List<User> findAll() {
// TODO Auto-generated method stub
return Mapper.findAll();
}
}
User.java
package com.ssm.model;
/**
* 描述:登录用户实体类<BR>
* 创建人:CNSTT<BR>
* 时间:2018年7月18日下午18:06:32<BR>
* @version
*/
public class User {
private int id; //主键
private String username; //用户名
private String password; //密码
private int role; //权限
private int roleid; //权限id
private String rolename; //权限英文
private String description; //权限描述
private String task; //工作任务
private String user; //使用人
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public int getRoleid() {
return roleid;
}
public void setRoleid(int roleid) {
this.roleid = roleid;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
IUserDao.java
package com.ssm.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ssm.model.User;
public interface IUserDao {
public User selectById(int id);
public User selectByName(String username);
public List<User> findAll();
}
IUserDao.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">
<!--namespace用于与DAO层的接口类进行绑定,这样我们无需实现DAO层的接口
类,其接口类就能够自动的找到相关的SQL语句进行绑定实现-->
<mapper namespace="com.ssm.dao.IUserDao">
<!--select表示查询,它的id名称必须与DAO层接口的方法名相同,否则无法绑定-->
<select id="selectByName" parameterType="string" resultType="User">
select * from audit_system_user where username = #{username}
</select>
<select id="findAll" resultType="User"><!-- 查找所有用户有关信息 -->
select * from audit_system_user a left join audit_system_role b on a.ROLE= b.roleid order by id
</select>
</mapper>
UserController.java
package com.ssm.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.ssm.model.User;
import com.ssm.service.UserService;
import com.ssm.test.DynamicDataSourceHolder;
//@Controller注解用于标示本类为web层控制组件
@Controller
//@RequestMapping("/user")用于标定访问时对url位置
@RequestMapping("/user")
//在默认情况下springmvc的实例都是单例模式,所以使用scope域将其注解为每次都创建一个新的实例
@Scope("prototype")
public class UserController {
//自动注入业务层的userService类
@Autowired
UserService userService;
//login业务的访问位置为/user/login
@RequestMapping("/index")
public String login(User user,HttpServletRequest request)throws Exception{
DynamicDataSourceHolder.setDataSource("dataSource");
List<User> users =userService.findAll();//调用findAll方法来获取所有用户list
request.setAttribute("users",users);
return "index";
}
@RequestMapping("/login")
public String helloMvc(){
return "test";
}
}
import javax.servlet.http.HttpServletRequest;
如果报错请按百度操作添加server
正式运行
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.sql.*,java.io.*,java.util.*,java.text.SimpleDateFormat,java.util.Date"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello World
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.sql.*,java.io.*,java.util.*,java.text.SimpleDateFormat,java.util.Date"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<div>
<c:forEach items="${users}" var="users">
<p>${users.id}</p>
<p>${users.username}</p>
</c:forEach>
</div>
</body>
</html>
运行启动
jetty:run -Djetty.port=8082