Spring+SpringMVC+Mybatis+PostgreSQL+Bootstrap入门整合

原创
2018/03/05 16:28
阅读数 2.5K

Spring+SpringMVC+Mybatis+PostgreSQL+Bootstrap入门整合

数据库:PostgreSQL 10.x版本

可视化工具:pgAdmin4

本博客主要记录小帅丶自行搭建的一个简单框架,用于日后学习及日后想要利用该平台来完成部分简单重复的工作。工具是MyEclipse 2015 CI

各个jar版本说明:

        <!-- spring -->
        <spring.version>4.3.14.RELEASE</spring.version>
        <!-- log -->
        <commons-logging.version>1.1.3</commons-logging.version>
        <!-- Servlet -->
        <servlet.version>3.0.1</servlet.version>
        <jsp-api.version>2.2</jsp-api.version>
        <!-- jstl -->
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <!-- test -->
        <junit.version>3.8.1</junit.version>
        <!-- jdk -->
        <jdk.version>1.8</jdk.version>
        <maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
        <mybatis.version>3.4.4</mybatis.version>  
	<mybatis.spring.version>1.3.1</mybatis.spring.version>
	<druid.version>1.0.20</druid.version>
不完全是所有的jar版本。具体可以看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.0</modelVersion>
  <groupId>com.bjjuli.payplatform</groupId>
  <artifactId>jlpayp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1</version>
  <name>jlpayp</name>
  <url>http://maven.apache.org</url>
   <!-- 定义maven变量 -->
    <properties>
        <!-- spring -->
        <spring.version>4.3.14.RELEASE</spring.version>
        <!-- log -->
        <commons-logging.version>1.1.3</commons-logging.version>
        <!-- Servlet -->
        <servlet.version>3.0.1</servlet.version>
        <jsp-api.version>2.2</jsp-api.version>
        <!-- jstl -->
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <!-- test -->
        <junit.version>3.8.1</junit.version>
        <!-- jdk -->
        <jdk.version>1.8</jdk.version>
        <maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
        <mybatis.version>3.4.4</mybatis.version>  
		<mybatis.spring.version>1.3.1</mybatis.spring.version>
		<druid.version>1.0.20</druid.version>
    </properties>
  <dependencies>
  		<!-- fastjson -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.35</version>
		</dependency>
        <!-- 导入Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
   		<!-- druid相关包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
		<!-- MyBatis所需jar -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!--mybatis spring 插件 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>${mybatis.spring.version}</version>  
        </dependency> 
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.8.5</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.8.5</version>
		</dependency>
		<!-- Apache Upload -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version>
		</dependency>
     	<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>
	<dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.1.jre7</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>jlpayp</finalName>
  </build>
</project>

项目结构图:

                 

配置文件说明:

  • paypalt-jdbc.properties

数据库配置内容,驱动用户名密码等

#数据库驱动postgresql
driver=org.postgresql.Driver
url=jdbc:postgresql://127.0.0.1:5432/test
username=postgres
password=1234
#定义初始连接数  
initialSize=0
#定义最大连接数  
maxActive=20
#定义最大空闲  
maxIdle=20
#定义最小空闲  
minIdle=1
#定义最长等待时间  
maxWait=60000
  • spring-mvc.xml

项目注解扫描配置等

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" 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-4.0.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
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <!-- 自动扫描的包名 -->
    <context:component-scan base-package="com.juli.jlpayp.controller" />
    <!-- 默认的注解映射的支持 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 视图解释类,定义跳转的文件的前后缀 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 拦截器 -->
    <!-- <mvc:interceptors> <bean class="com.fpx.ce.foundation.preference.PreferenceChangeInterceptor" 
        /> <mvc:interceptor> <mvc:mapping path="/page/home"/> <bean class="com.fpx.ce.foundation.user.UserInterceptor" 
        /> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/service/**" /> 
        <bean class="com.fpx.ce.foundation.log.LogHandlerInterceptor" /> </mvc:interceptor> 
        <mvc:interceptor> <mvc:mapping path="/test/**" /> <mvc:mapping path="/service/**" 
        /> <bean class="com.lemon.finder.web.SharedRenderVariableInterceptor" /> 
        </mvc:interceptor> </mvc:interceptors> -->


    <!-- 对静态资源文件的访问 方案一 (二选一) -->
    <mvc:default-servlet-handler />

    <!-- 对静态资源文件的访问 方案二 (二选一) -->
    <!-- <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/> 
        <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> 
        <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/> -->
</beans>
  • spring.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:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <!-- 注解注册 -->
    <context:annotation-config />
    <context:component-scan base-package="com.juli.jlpayp" />
</beans>
  • spring-mybatis.xml

数据库连接池等相关ORM配置

<?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:p="http://www.springframework.org/schema/p"  
    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-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 自动扫描 -->  
    <context:component-scan base-package="com.juli.jlpayp" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:payplat-jdbc.properties" />  
    </bean>  
 
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
        <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>  
 <!-- 		<property name="validationQuery" value="SELECT 'x' from dual " /> -->
 		<property name="testWhileIdle" value="true" />
	    <property name="testOnBorrow" value="false" />
	    <property name="testOnReturn" value="false" />
    </bean>  
 
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:com/juli/jlpayp/mapping/*/*.xml"></property>  
    </bean>  
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.juli.jlpayp.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
 
</beans>  
  • web.xml

针对于项目的启动和一些拦截配置

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <display-name>test-spring</display-name>
    <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:payplat-log4j.properties</param-value>
	</context-param>
    <!-- Spring配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring MVC配置 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml,classpath:spring-mybatis.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 中文过滤器 -->
    <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>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

创建一个Demo

  • UserController.java

页面请求处理层

package com.juli.jlpayp.controller;


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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.juli.jlpayp.pojo.user.User;
import com.juli.jlpayp.service.user.UserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	UserService userService;
        //登录页面跳转
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(){
		return "login";
	}
         //登录请求处理
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestParam("userName")String userName,
						@RequestParam("passWord")String passWord,
						HttpSession session,Model model){
		User user = userService.retrieve(userName, passWord);
		System.out.println(JSONObject.toJSONString(user));
		if(user!=null){
			return "user/userList";
		}else{
			return "login";
		}
	}

}
  • UserService.java

业务实现接口类

package com.juli.jlpayp.service.user;


import com.juli.jlpayp.pojo.user.User;

public interface UserService {
	public User retrieve(String userName,String passWord);
}
  • UserServiceImpl.java

业务实现类

package com.juli.jlpayp.service.user.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.juli.jlpayp.dao.user.UserDao;
import com.juli.jlpayp.pojo.user.User;
import com.juli.jlpayp.service.user.UserService;
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	UserDao userMapper;
	public User retrieve(String userName, String passWord) {
		User users = userMapper.retrieve(userName, passWord);
		return users;
	}

}
  • UserDao.java

业务实现DAO层

package com.juli.jlpayp.dao.user;


import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import com.juli.jlpayp.pojo.user.User;
@Mapper
public interface UserDao {
	public User retrieve(@Param("userName")String userName,@Param("passWord")String passWord);
}
  • UserMapper.xml

具体的sql执行

<?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.juli.jlpayp.dao.user.UserDao">

	<select id="retrieve" resultType="com.juli.jlpayp.pojo.user.User">
		select
		"userId","userName","userPassword"
		from "excel_user" where "userName" = #{userName} and "userPassword"=#{passWord}
	</select>

	<select id="list" resultType="com.juli.jlpayp.pojo.user.User">
		select
		`userId`,`userName`,`userPassword`
		from excel_user
		<choose>
			<when test="sort != null and sort.trim() != ''">
				order by ${sort} ${order}
			</when>
			<otherwise>
				order by userId desc
			</otherwise>
		</choose>
		<if test="offset != null and limit != null">
			limit #{offset}, #{limit}
		</if>
	</select>

	<select id="count" resultType="int">
		select count(*) from excel_user
	</select>
</mapper>
  • login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>登录</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="<%=basePath%>bootstrap/css/bootstrap.min.css">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
  <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body>
    <div class="container">
        <h1>登录页面</h1>
        <hr />
        <form action="<%=basePath%>user/login" method="post">
            <div class="form-group">
                <label for="userName">UserName:</label> <input type="text"
                    class="form-control" id="userName" name="userName"
                    placeholder="请输入用户名" />
            </div>
            <div class="form-group">
                <label for="password">Password:</label> <input type="text"
                    class="form-control" id="passWord" name="passWord"
                    placeholder="请输入密码" />
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-sm btn-success">Sign
                    in</button>
            </div>
        </form>
    </div>
</body>
<!-- Bootstrap core JavaScript Placed at the end of the document so the pages load faster -->
<script src="<%=basePath%>js/jquery.min.js"></script>
<script src="<%=basePath%>bootstrap/js/bootstrap.min.js"></script>
</html>

  • 登录演示

PostgresqlSQL数据库表字段:

展开阅读全文
加载中

作者的其它热门文章

打赏
0
10 收藏
分享
打赏
0 评论
10 收藏
0
分享
返回顶部
顶部