低调大师

您现在的位置是:首页>文章详情

文章详情

SpringMVC,Spring,MyBatis基本整合

2019-07-08 603热度
SpringMVC,Spring,MyBatis基本整合

说明:

    本项目配置一个SSM项目的基本整合,环境为JDK1.8

        使用Spring,SpringMVC,MyBatis,Logback,Druid,Fastjson,Oracle等技术

        项目结构图如下:

            

1.首先新建一个Maven项目

    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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.xujun</groupId>
<artifactId>day13.springmvc</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>springmvc</name>
<description>springmvc</description>

<dependencies>
<!-- commons Start -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!-- 文件上传支持(commons-io) -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>

<!-- Logback相关依赖 Start(slf4j-api) -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- Logback相关依赖 Ends -->

<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>

<!-- Spring相关依赖 Start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jcl</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- Spring相关依赖 Ends -->

<!-- Druid(数据库连接池) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

<!-- MyBatis相关依赖 Start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- MyBatis相关依赖 Ends -->

<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4.0-atlassian-hosted</version>
</dependency>

</dependencies>

<build>
<plugins>
<!-- 编译插件(设置源代码的JDK版本,目标代码JDK版本,编译字符集) -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>

</project>

2.配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- Spring的配置 Start -->
<context-param>
<description>配置spring读取的xml文件,param-name是spring规定,spring自动加载以下内容.</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring的配置 Ends -->

<!-- SpringMVC 配置 Start -->

<!-- Web请求编码过滤器,POST中文乱码解决方案 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- DispatcherServlet 配置加载 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 以下配置springmvc-servlet.xml放在包内或部署的classes目录下的对应目录下皆可. -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- SpringMVC 配置 Ends -->

</web-app>

3.配置SpringMVC

    新建配置文件springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 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:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- @ResponseBody返回JSON数据中文乱码解决,注意,此配置一定要在<mvc:annotation-driven/>配置前面 -->
<property name="messageConverters">
<list>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

<!-- 静态资源映射(通用) -->
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/3rd/**" location="/3rd/" />
<mvc:resources mapping="/upload/**" location="/upload/" />

<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />

<!-- 开启Controller注解支持 -->
<context:component-scan base-package="org.xujun.controller"></context:component-scan>

<!-- SpringMVC上传文件时,需配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<!-- 视图解析器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 拦截器配置 -->
<mvc:interceptors>
<!-- 可配多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- [/**]表示所有url包括子url路径 -->
<mvc:mapping path="/**"/>
<!-- 不拦截静态资源路径下的请求 -->
<mvc:exclude-mapping path="/css/**"/>
<mvc:exclude-mapping path="/img/**"/>
<mvc:exclude-mapping path="/js/**"/>
<mvc:exclude-mapping path="/3rd/**"/>
<mvc:exclude-mapping path="/upload/**"/>
<bean class="org.xujun.intercepter.BaseHandlerInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

</beans>

4.配置Spring+MyBatis

    新建配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">

<!-- 加载相关资源文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:oracle.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"></property>
</bean>

<!-- 自动扫描的包名 -->
<context:component-scan base-package="org.xujun.service.impl"></context:component-scan>

<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.oracle.driverClassName}"/>
<property name="url" value="${jdbc.oracle.url}"/>
<property name="username" value="${jdbc.oracle.username}"/>
<property name="password" value="${jdbc.oracle.password}"/>
<property name="maxActive" value="${jdbc.oracle.maxActive}"/>
<property name="initialSize" value="${jdbc.oracle.initialSize}"/>
<property name="maxWait" value="60000"/>
<property name="minIdle" value="5"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="180"/>
<property name="connectionProperties" value="config.decrypt=true"/>
</bean>

<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载MyBatis的全局配置文件 -->
<property name="mapperLocations" value="classpath:org/xujun/dao/*Mapper.xml" />
</bean>

<!-- Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<!-- 对**.dao包内进行扫描 -->
<property name="basePackage" value="org.xujun.dao"/>
</bean>

<!-- 事务管理器,对MyBatis操作数据库事务控制,Spring使用jdbc的事务控制类 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" scope="singleton">
<!-- 数据源dataSource在applicationContext-mybatis.xml中配置了 -->
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 注解的事务管理@Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

</beans>

    新建配置文件oracle.properties

# Oracle数据库配置
# 配置说明
# driverClassName : 数据库驱动的名称
# url : 数据库的地址
# username : 用户名
# password : 密码
# maxActive : 最大激活连接数
# initialSize : 连接池启动时创建的初始化连接数量
jdbc.oracle.driverClassName=oracle.jdbc.OracleDriver
jdbc.oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.oracle.username=zy_study
jdbc.oracle.password=root
jdbc.oracle.maxActive=20
jdbc.oracle.initialSize=5

5.配置logback

    新建配置文件logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 基本信息配置 -->
<property name="localAppName" value="org.xujun"/>
<property name="logHomeDir" value="${user.dir}/logs/logback"/>
<property name="logbackLevel" value="DEBUG"/>
<contextName>default</contextName>

<!-- 控制台输出配置 -->
<appender name="ConsoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg %n</pattern>
</encoder>
</appender>

<!-- 针对本项目配置的日志 Start -->
<appender name="LOCALAPP_DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<Prudent>false</Prudent>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logHomeDir}/${localAppName}/debug/debug-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>10</MaxHistory> <!-- 日志保留的个数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>

<appender name="LOCALAPP_WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<Prudent>false</Prudent>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logHomeDir}/${localAppName}/warn/warn-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>10</MaxHistory> <!-- 日志保留的个数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>

<appender name="LOCALAPP_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<Prudent>false</Prudent>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logHomeDir}/${localAppName}/info/info-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>10</MaxHistory> <!-- 日志保留的个数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>

<appender name="LOCALAPP_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<Prudent>false</Prudent>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logHomeDir}/${localAppName}/error/error-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>10</MaxHistory> <!-- 日志保留的个数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>
<!-- 针对本项目配置的日志 Ends -->

<!-- 针对第三方配置的日志 Start -->
<appender name="THIRDPART_DEFAULT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Encoding>UTF-8</Encoding>
<Prudent>false</Prudent>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logHomeDir}/${localAppName}/thirdpart/thirdpart-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>10</MaxHistory> <!-- 日志保留的个数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>
<!-- 针对第三方配置的日志 Ends -->

<!-- 针对指定包配置的日志 Start -->
<logger name="test" addtivity="false" level="${logbackLevel}">
<appender-ref ref="ConsoleAppender"/>
</logger>

<logger name="org" addtivity="false" level="${logbackLevel}">
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="THIRDPART_DEFAULT"/>
</logger>

<logger name="com" addtivity="false" level="${logbackLevel}">
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="THIRDPART_DEFAULT"/>
</logger>

<!-- log4jdbc 专用配置 -->
<logger name="jdbc.sqltiming" addtivity="false" level="${logbackLevel}">
<appender-ref ref="ConsoleAppender"/>
</logger>

<logger name="jdbc.resultsettable" level="INFO"></logger>
<logger name="jdbc.sqlonly" level="OFF"></logger>
<logger name="jdbc.audit" level="OFF"></logger>
<logger name="jdbc.resultset" level="OFF"></logger>
<logger name="jdbc.connection" level="OFF"></logger>
<!-- 针对指定包配置的日志 Ends -->

<!-- 根logger<root>此标签必须设置在最后面方可正常读取,否则系统将识别为无输出控制.
只有一个level属性,用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL. 默认是DEBUG. <root>可以包含零个或多个<appender-ref>元素,标识这个appender将会添加到这个loger. -->
<root level="WARN">
<!-- <appender-ref ref="ConsoleAppender"/> -->
</root>

</configuration>

6.项目中代码结构

       

7.各个类的代码详情

    7.1.HelloController.java

package org.xujun.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.xujun.model.Users;
import org.xujun.service.UserService;

import com.alibaba.fastjson.JSONObject;

@Controller
public class HelloController {

@Autowired
private UserService userService;

/**
* 返回JSP页面
*/
@RequestMapping("/hello.html")
public ModelAndView hello() {
String user = userService.getUser();
System.out.println(user);

ModelAndView mv = new ModelAndView();
mv.addObject("name", user);
mv.setViewName("hello");
return mv;
}

/**
* JSON
*/
@RequestMapping("/json.ajax")
@ResponseBody
public JSONObject json() {
JSONObject data = new JSONObject();
data.put("xujun", 666);
data.put("zz", "haha");
return data;
}

/**
* 图片验证码
* @param response HttpServletResponse
* @param time 随机时间
* @throws Exception 图片异常
*/
@RequestMapping("/image_code.jpg")
public void imageCode(HttpServletRequest request, HttpServletResponse response, String time) throws Exception {
BufferedImage newImgCode = newImgCode(105, 32, "abcd");
ImageIO.write(newImgCode, "jpg", response.getOutputStream()); // 将图片验证码输出
}


/**
* 获取图片验证码
* @param width 宽
* @param height 高
* @param code 验证码
* @return 图片验证码
*/
public static BufferedImage newImgCode(int width, int height, String code) {
int size = code.length();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics(); // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
g.fillRect(0, 0, width, height);
g.setColor(new Color(245, 244, 208)); // 默认文字颜色
g.setFont(new Font("Arial", Font.CENTER_BASELINE, 24)); // 设置默认文字大小
// 画干拢线
Random random = new Random();
for (int i = 0; i <= size * 4; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x + xl, y + yl);
}
// 将文字写入图片
String randomString = code;
for (int i = 1; i <= size; i++) {
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121))); // 设置颜色区间变化
g.drawString(randomString.charAt(i - 1) + "", 18 * i, 26);
}
return image;
}

/**
* 单个参数
*/
@RequestMapping("/param.html")
public ModelAndView param() {
ModelAndView mv = new ModelAndView();
mv.setViewName("param");
return mv;
}

@RequestMapping("/do-param.ajax")
@ResponseBody
public JSONObject doParam(String name, String passwd) {
JSONObject data = new JSONObject();
data.put("name", name);
data.put("passwd", passwd);
return data;
}

/**
* 封装对象
*/
@RequestMapping("/login.html")
public ModelAndView login() {
ModelAndView mv = new ModelAndView();
mv.setViewName("login");
return mv;
}

@RequestMapping("/do-login.ajax")
@ResponseBody
public JSONObject doLogin(Users u) {
JSONObject data = new JSONObject();
data.put("userName", u.getUaseName());
data.put("password", u.getPassword());
return data;
}


/**
* 上传
*/
@RequestMapping("/upload.html")
public ModelAndView upload() {
ModelAndView mv = new ModelAndView();
mv.setViewName("upload");
return mv;
}

/**
* 上传文件处理
* @param file 文件
* @param request HttpServletRequest
* @return 上传结果
*/
@RequestMapping("/upload-files.ajax")
@ResponseBody
public JSONObject uploadFiles(MultipartFile file, HttpServletRequest request) throws Exception {
// 原文件名
String oldFileName = file.getOriginalFilename();
// 计算完整路径
String rootPath = request.getSession().getServletContext().getRealPath("/") + "upload/";
System.out.println(rootPath);
// 将文件放于项目部署路径下的upload文件夹下
File targetFile = new File(rootPath, oldFileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile); //保存文件

JSONObject data = new JSONObject();
data.put("suc", "ok");
return data;
}

}

    7.2.UsersMapper.java

package org.xujun.dao;

import java.util.List;

import org.xujun.model.Users;

public interface UsersMapper {

List<Users> findUsersList();
}

    7.3.UsersMapper.xml

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="org.xujun.dao.UsersMapper">

<select id="findUsersList" resultType="org.xujun.model.Users">
SELECT * FROM "users"
</select>

</mapper>

    7.4.BaseHandlerInterceptor.java

package org.xujun.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
* <p>Title : BaseHandlerInterceptor</p>
* <p>Description : 系统最高权限拦截器</p>
* <p>DevelopTools : Eclipse_x64_v4.6.2</p>
* <p>DevelopSystem : Windows10</p>
* <p>Company : org.xujun</p>
* @author : XuJun
* @date : 2016年11月23日 上午9:55:39
* @version : 6.0.0
*/
public class BaseHandlerInterceptor implements HandlerInterceptor {

/**
* 进入Handler方法之前执行
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param handler handler
* @return true(放行) or false(拦截)
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("before");
return true;
}

/**
* 进入Handler方法之后,返回modelAndView之前执行(可以往MV里面填充公用的ModelAndView)
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param handler handler
* @param mv ModelAndView
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
System.out.println("mv 执行");
}

/**
* 执行Handler完成后执行(统一异常处理,统一日志处理)
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param handler handler
* @param e 异常信息
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
System.out.println("after");
}

}

    7.5.Users.java

package org.xujun.model;

import java.util.Date;

/**
* <p>Title : Users</p>
* <p>Description : Users Model</p>
* <p>DevelopTools : Eclipse_x64_v4.7.2</p>
* <p>DevelopSystem : Windows10</p>
* <p>Company : org.xujun</p>
* @author : XuJun
* @date : 2018年4月1日 下午2:48:35
* @version : 1.0.0
*/
public class Users {

private Integer userId;
private String uaseName;
private String password;
private Integer age;
private Date time;

public Users() {
}

public Users(Integer userId, String uaseName, String password, Integer age, Date time) {
this.userId = userId;
this.uaseName = uaseName;
this.password = password;
this.age = age;
this.time = time;
}

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUaseName() {
return uaseName;
}

public void setUaseName(String uaseName) {
this.uaseName = uaseName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Date getTime() {
return time;
}

public void setTime(Date time) {
this.time = time;
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Users [userId=");
builder.append(userId);
builder.append(", uaseName=");
builder.append(uaseName);
builder.append(", password=");
builder.append(password);
builder.append(", age=");
builder.append(age);
builder.append(", time=");
builder.append(time);
builder.append("]");
return builder.toString();
}

}

    7.6.UserService.java

package org.xujun.service;

public interface UserService {

String getUser();

}

    7.7.UserServiceImpl.java

package org.xujun.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xujun.dao.UsersMapper;
import org.xujun.model.Users;
import org.xujun.service.UserService;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UsersMapper usersMapper;

@Transactional(rollbackFor = Exception.class)
public String getUser() {
List<Users> findUsersList = usersMapper.findUsersList();
for(Users u : findUsersList) {
System.out.println(u.toString());
}
return "xujun";
}

}
收藏 (0)

如果您喜欢本网站,欢迎打赏。

打赏多少您说了算,谢谢您对低调大师的支持!!!

支付宝扫一扫

个人博客,低调大师,许军

微信扫一扫

个人博客,低调大师,许军

相关文章

    文章评论

    共有0条评论来说两句吧...