Springmvc-02 拦截器,文件上传,ssm环境搭建-G09

Springmvc02

拦截器,文件上传,ssm环境搭建

八、 请求转发与重定向的问题
Springmvc 默认采用服务器内部转发的形式展示页面信息。同样也支持重定向
页面。
1.重定向到 jsp 页面

2.请求转发到试图,转发到controller

1)controller层PageController

/**
 * 请求转发与重定向
 */
@Controller
public class PageController {
    //page01重定向到v1.jsp
    @RequestMapping("page01")
    public  String page01(){
        return "redirect:v1.jsp";
    }
    //通过重定向传值 前台通过{param.a}取值
    @RequestMapping("page02")
    public  String page02(){
        return "redirect:v1.jsp?a=1&b=上海";
    }

    //通过重定向传值,解决传中文乱码情况,用此方法
    @RequestMapping("page04")
    public  String page04(RedirectAttributes attr){
        attr.addAttribute("a",1);
        attr.addAttribute("b","上海");
        return "redirect:v1.jsp";
    }

//也可以通过重定向到某一个controller方法 访问page05重定向到page06方法
    @RequestMapping("page05")
    public  String page05(){
        System.out.println("page05");

        return "redirect:page06";
    }

    @RequestMapping("page06")
    public  String page06(){
        System.out.println("page06");

        return "hello";
    }

    //请求转发到另外一个controller方法
    @RequestMapping("page07")
    public String page07(){
        System.out.println("page07");
        return "forward:page08";
    }

    @RequestMapping("page08")
    public String page08(){
        System.out.println("page08");
        return "hello";
    }

}


2)重定向页面v1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>测试重定向</title>
</head>
<body>
<h3> v1.jsp </h3>

a: ${param.a}<br>
b: ${param.b}<br>
</body>
</html>


九、 获取 request,response 对象
对于我们的方法默认方法的参数是空的,这时候要想获取 request,response
对象如何获取?

public ModelAndView queryUser(HttpServletRequest request,HttpServletResponse
response){
String userName= request.getParameter("userName");
ModelAndView mv=new ModelAndView();
mv.addObject("userName", userName);
mv.setViewName("request");
return mv;
}

十、 理解 ModelAndView 模型视图类

见名知意,从名字上我们可以知道 ModelAndView 中的 Model 代表模型,View
代表视图。即,这个类把要显示的数据存储到了 Model
属性中,要跳转的视图信息存
储到了 view 属性。我们看一下 ModelAndView 的部分源码,即可知其中关系

十一、 SpringMvc 之 Json 数据开发

@ResponseBody
该注解用于将 Controller 的方法返回的对象,通过适当的
HttpMessageConverter
转换为指定格式后,写入到 Response 对象的 body 数据区。
返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如 json、xml
等)
使用(通常用于 ajax 请求)
@RequestBody
该注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的
HttpMessageConverter 进行解析,然后把相应的数据绑定到要返回的对象上
,再把
HttpMessageConverter 返回的对象数据绑定到 controller 中方法的参数上
Json 数据使用好处
Json
在企业开发中已经作为通用的接口参数类型,在页面(客户端)解析很方便。

SpringMvc 对于 json 提供了良好的支持,这里需要修改相关配置,添加 json
数据支持
功能

1.添加 json 依赖 jar 包.pom.xml中添加依赖

<!-- 添加json 依赖jar包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

2.修改 servlet-context.xml
添加 json 转换器配置


    <!-- json 支持 -->
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    </bean>
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
            </list>
        </property>
    </bean>

3.Json 数据绑定的支持 controller层添加绑定方法


//把user传给前台json格式
@ResponseBody
@RequestMapping("hello09")
public User hello09(User user) {
    System.out.println(user);
    return user;
}


4`.Jsp 页面取值,返回json对象

image.png

十二、 拦截器
SpringMVC 中的 Interceptor 拦截器也是相当重要和相当有用的,它的主要作
用是拦截用户的请求并进行相应的处理。比如通过它来进行权限验证,或者是来判断
用户是否登陆等操作。
对于 springmvc 拦截器的定义方式有两种方式
1. 实现接口: org.springframework.web.servlet.HandlerInterceptor
*2. 继承适配器*
***org.springframework.web.servlet.handler.HandlerInterceptorAdapter

3.实现 HandlerInterceptor 接口方式定义我们的拦截器代码如下:

3.1--controller层加UserController,模拟用户登录实现拦截


/**
 * 测试拦截器 User
 */
@Controller
@RequestMapping("user")
public class UserController {
/*
放开login的拦截
将登陆信息存到session中
 */
    @RequestMapping("login")
    public String login(User user, HttpSession session){
        session.setAttribute("user", user);
        System.out.println("登陆成功");
        return "index";
    }

//模拟用户登陆,无登录实现拦截
    @RequestMapping("queryUser")
    @ResponseBody
    public User login(Integer id){
        User user = new User();
        user.setId(id);
        user.setName("zhangsan");
        user.setAge(19);
        return user;
    }



}


3.2对应配置有两种方式:servlet-context.xml配置
配置方式一(拦截所有请求配置方式):

<!-- 配置拦截器 -->
<mvc:interceptors>
    <!-- 拦截所有请求 -->
  <bean class="com.shsxt.interceptor.MyHandlerInterceptor"></bean> </mvc:interceptor>


配置方式二(拦截指定请求配置方式)


<!-- 配置拦截器 -->
<mvc:interceptors>
    <!-- 拦截所有请求 -->
    <!--<bean class="com.shsxt.interceptor.MyHandlerInterceptor"></bean>-->

    <mvc:interceptor>
        <mvc:mapping path="/user/**"/><!-- 只拦截/user 开头的请求 -->
        <mvc:exclude-mapping path="/user/login"/><!--排除掉指定请求-->
        <bean class="com.shsxt.interceptor.MyHandlerInterceptor"></bean>
    </mvc:interceptor>

<!--多个拦截器配置(多个拦截器组成一个拦截器链 )-->
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.shsxt.interceptor.MyHandlerInterceptor2"></bean>
    </mvc:interceptor>
</mvc:interceptors>


3.3配置拦截器

新建packageMyHandlerInterceptor


/**
 * 测试拦截器
 */
public class MyHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("before target method...");

        /***
         * 判断session是否为空,简单模拟用户是否登录
         * */
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if(null==user){
            System.err.println("没有登陆");
            return false;
        }
        return true;// 返回false 整个请求停止; true代表继续执行
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("after target method...");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("after view method...");
    }
}


4.继承 HandlerInterceptorAdapter 方式定义拦截器

(实际上最终还是HandlerInterceptor 接口实现)

4.1 创建拦截器

Inteceptor中创建MyHandlerInterceptor2

image.png
/**
 * 继承 HandlerInterceptorAdapter 方式定义拦截器(
 */
public class MyHandlerInterceptor2 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 222");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 222");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion 222");
    }
}


4.2 servlet-context.xml中添加拦截配置(同上)

4.3UserController类中加登录方法(同上)

十三、 SpringMvc 文件上传

1.Pom 文件修改 添加 commons-fileupload 依赖

<!--文件上传依赖-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>


2.servlet-context.xml中配置

<!--    文件上传配置-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>


3.controller中加上传方法 FileController.java

 
/**
 *文件上传类
 */
@Controller
public class FileController {

    @RequestMapping("uploadFile")
    @ResponseBody
    public String uploadFile(HttpServletRequest request){
        // 1. 强制转换
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
        // 2. 获取上传文件
        MultipartFile file = mr.getFile("file");
        // 3. 非空判断
        if(null!=file && !file.isEmpty()){
            // 获取上传文件夹的路径
            String path=request.getSession().getServletContext().getRealPath("upload");
            // 获取原始名字
            String filename = file.getOriginalFilename();
            // 4. 存储
            try {
                file.transferTo(new File(path, filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "success";
    }

}


4.前台表单选择上传文件file.jsp页面 ,上传到服务器存储路径为upload

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="uploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit"> 提交</button>
</form>
</body>
</html>


5,测试页面上传

image.png
image.png

十四、 SSM 框架集成环境搭建
对于 spring 与 mybatis
的环境集成,我们已经集成过了,只需要把原来集成的代码
生成器的项目(spring_mybatis_自动化代码生成)拿过来修改相关的配置就可以了,
具体步骤如下:

1. jar 包依赖添加(原有基础上继续添加 springmvc 相关依赖 jar
包及对应
jetty 插件) 修改 pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>

<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>com.shsxt</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm Maven Webapp</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- spring 核心jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring 测试jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring事物 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- aspectj切面编程的jar -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>


    <!-- c3p0 连接池 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!-- 添加mybatis与Spring整合的核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- mysql 驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <!-- 日志打印相关的jar -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.2</version>
    </dependency>

    <!-- 分页插件配置 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.0</version>
    </dependency>

    <!-- spring web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring mvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- web servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <!-- 添加json 依赖jar包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

    <!-- 文件上传包依赖 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>ssm</finalName>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>


    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
          </dependency>
        </dependencies>
      </plugin>

      <!-- 配置jetty插件 -->
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.21</version>
        <configuration>
          <scanIntervalSeconds>10</scanIntervalSeconds>
          <contextPath>/ssm</contextPath>
        </configuration>
      </plugin>

    </plugins>

  </build>
</project>


2.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">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
    <description>char encoding filter</description>
    <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <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:servlet-context.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>
</web-app>


3. Springmvc 配置文件 servlet-context.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        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/aop
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


    <!-- 扫描com.shsxt.controller 下包 -->
    <context:component-scan base-package="com.shsxt.controller" />
    <!-- mvc 请求映射处理器与适配器 -->
    <mvc:annotation-driven />

    <!--配置视图解析器 默认的视图解析器- -->
    <bean id="defaultViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
        <property name="contentType" value="text/html" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>


    <!-- json 支持 -->
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    </bean>
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
            </list>
        </property>
    </bean>


    <!-- 文件上传配置 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>

</beans>


4.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" 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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 扫描基本包 过滤controller层 -->
    <context:component-scan base-package="com.shsxt" >
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!-- 加载properties 配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <aop:aspectj-autoproxy /><!-- aop -->

    <!-- 配置c3p0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></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="get*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!-- aop 切面配置 -->
    <aop:config>
        <aop:pointcut id="servicePointcut"
                      expression="execution(* com.shsxt.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut" />
    </aop:config>

    <!-- 配置 sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml" />

        <property name="mapperLocations" value="classpath:com/shsxt/mapper/*.xml" />
    </bean>

    <!-- 配置扫描器 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描com.shsxt.dao这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="com.shsxt.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>


5.数据库配置db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456


6.日志打印导入

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


7.mybatis集成配置,包扫描及别名

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- po 包扫描 -->
    <typeAliases>
        <package name="com.shsxt.po" />
    </typeAliases>

    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <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,不配置映射的用默认值 -->
            <property name="params"
                      value="pageNum=start;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=countsql" />
        </plugin>
    </plugins>

</configuration>


8. generatorConfig.xml更改生成路径及仓库路径

image.png

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--数据库驱动-->
    <classPathEntry    location="E:/m2/repository/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar"/>
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.shsxt.po" targetProject="E:/java_28/ssm/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.shsxt.mapper" targetProject="E:/java_28/ssm/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.shsxt.dao" targetProject="E:/java_28/ssm/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>


9.mybatis-generator自动生成UserMapper.xml,及po中User类等

生成目录如下

image.png

10.更改UserMapper.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" >
<mapper namespace="com.shsxt.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.shsxt.po.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_pwd" property="userPwd" jdbcType="VARCHAR" />
    <result column="real_name" property="realName" jdbcType="VARCHAR" />
    <result column="nation" property="nation" jdbcType="VARCHAR" />
    <result column="card_id" property="cardId" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, user_pwd, real_name, nation, card_id
  </sql>
  <select id="queryById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="delete" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.shsxt.po.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userPwd != null" >
        user_pwd,
      </if>
      <if test="realName != null" >
        real_name,
      </if>
      <if test="nation != null" >
        nation,
      </if>
      <if test="cardId != null" >
        card_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        #{realName,jdbcType=VARCHAR},
      </if>
      <if test="nation != null" >
        #{nation,jdbcType=VARCHAR},
      </if>
      <if test="cardId != null" >
        #{cardId,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="update" parameterType="com.shsxt.po.User" >
    update user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        user_pwd = #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        real_name = #{realName,jdbcType=VARCHAR},
      </if>
      <if test="nation != null" >
        nation = #{nation,jdbcType=VARCHAR},
      </if>
      <if test="cardId != null" >
        card_id = #{cardId,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
<!--  查询 分页使用-->

  <select id="queryForPage" parameterType="com.shsxt.base.BaseQuery" resultMap="BaseResultMap">
    SELECT * from user
  </select>
</mapper>


11.导入Base包工具包

1)AssertUtil.java

package com.shsxt.base;

public class AssertUtil {
    
    /**
     * 表达式结果真时判断
     * @param expression
     * @param msg
     */
    public static void isTrue(Boolean expression,String msg){
        if(expression){
            throw new ParamException(msg);
        }   
    }
    public static void isTure(Boolean expression){
        if(expression){
            throw new ParamException("参数异常");
        }
    }   
    /**
     * 参数为空时
     * @param object
     * @param msg
     */
    public static void isNull(Object object,String msg){
        if(object==null){
            throw new ParamException(msg);
        }
    }
    /**
     * 参数不空时
     * @param object
     * @param msg
     */
    public static void notNull(Object object,String msg){
        if(object!=null){
            throw new ParamException(msg);
        }
    }
}


2)BaseMapper.java

package com.shsxt.base;

import org.springframework.dao.DataAccessException;

import java.util.List;
import java.util.Map;

public interface BaseMapper<T> {
    /**
     * 添加记录不返回主键
     * @param entity
     * @return
     * @throws DataAccessException
     */
    public int insert(T entity) throws DataAccessException;
    /**
     * 
     * @param entities
     * @return
     * @throws DataAccessException
     */
    public int insertBatch(List<T> entities) throws DataAccessException;
    /**
     * 查询总记录数
     * @param map
     * @return
     */
    @SuppressWarnings("rawtypes")
    public int queryCountByParams(Map map) throws DataAccessException;
    /**
     * 查询记录 通过id
     * @param id
     * @return
     */
    public T queryById(Integer id) throws DataAccessException;

    /**
     * 分页查询记录
     * @param baseQuery
     * @return
     */
    public List<T> queryForPage(BaseQuery baseQuery) throws DataAccessException;
    /**
     * 查询记录不带分页情况
     * @param map
     * @return
     */
    @SuppressWarnings("rawtypes")
    public List<T> queryByParams(Map map) throws DataAccessException;

    /**
     * 更新记录
     * @param entity
     * @return
     */
    public int update(T entity) throws DataAccessException;

    /**
     * 批量更新
     * @param map
     * @return
     * @throws DataAccessException
     */
    public int updateBatch(Map map) throws DataAccessException;

    /**
     * 删除记录
     * @param id
     * @return
     */
    public int delete(Integer id) throws DataAccessException;

    /**
     * 批量删除
     * @param ids
     * @return
     */
    public int deleteBatch(int[] ids) throws DataAccessException;
}


3)BaseQuery.java分页查询

package com.shsxt.base;

public class BaseQuery {
    /**
     * 分页页码
     */
    private int pageNum=1;
    
    /**
     * 每页记录数
     */
    private int pageSize=10;

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}


4)BaseService.java

package com.shsxt.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

public abstract class BaseService<T> {
    @Autowired
    public BaseMapper <T> baseMapper;
    
    /**
     * 添加记录
     * @param entity
     * @return
     * @throws Exception
     */
    public int insert(T entity) throws Exception{
        int result= baseMapper.insert(entity);
        return result;
    }
    
    /**
     * 批量添加记录
     * @param entities
     * @return
     * @throws Exception
     */
    public int insertBatch(List<T> entities) throws Exception{
        return baseMapper.insertBatch(entities);
    }
    
    
    /**
     * 根据参数统计记录数
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public int queryCountByParams(Map map)throws Exception{
        return baseMapper.queryCountByParams(map);
    }
    
    
    
    
    /**
     * 查询记录通过id
     * @param id
     * @return
     * @throws Exception
     */
    public T queryById(Integer id)throws Exception{
        AssertUtil.isNull(id, "记录id非空!");
        return baseMapper.queryById(id);
    }
    
    
    /**
     * 分页查询
     * @param baseQuery
     * @return
     * @throws Exception
     */
    public PageInfo<T> queryForPage(BaseQuery baseQuery)throws Exception{
        PageHelper.startPage(baseQuery.getPageNum(),baseQuery.getPageSize());
        List<T> list= baseMapper.queryForPage(baseQuery);       
        PageInfo<T> pageInfo=new PageInfo<T>(list);
        return pageInfo;        
    }
    
    
    
    
    /**
     * 
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public List<T> queryByParams(Map map)throws Exception{  
        return baseMapper.queryByParams(map);  
    }
    
    
    
    /**
     * 查询记录
     * @param entity
     * @return
     * @throws Exception
     */
    public int update(T entity)throws Exception{
        return baseMapper.update(entity);
    }
    
    
    /**
     * 批量更新
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public int updateBatch(Map map) throws Exception{
        return baseMapper.updateBatch(map);
    }
    
    /**
     * 删除记录
     * @param id
     * @return
     * @throws Exception
     */
    public int delete(Integer id) throws Exception{
        // 判断 空
        AssertUtil.isNull(id, "记录id非空!");
        AssertUtil.isNull(queryById(id), "待删除的记录不存在!");
        return  baseMapper.delete(id);
    }
    
    /**
     * 批量删除
     * @param ids
     * @return
     */
    public int deleteBatch(int[] ids) throws Exception{
        AssertUtil.isNull(ids.length==0,"请至少选择一项记录!");
        return  baseMapper.deleteBatch(ids);
    }
}


5)ParamException.java

package com.shsxt.base;

/**
 * 参数异常类
 * @author Administrator
 *
 */
public class ParamException extends RuntimeException{
    /**
     * 
     */
    private static final long serialVersionUID = -5962296753554846774L;
    
    /**
     * 错误状态码
     */
    private int errorCode;

    public ParamException() {
    }   
    /**
     * 错误消息
     * @param msg
     */
    public ParamException(String msg) {
        super(msg);
    }
    public ParamException(int errorCode,String msg){
        super(msg);
        this.errorCode=errorCode;
    }
    public int getErrorCode() {
        return errorCode;     
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}


12.UserMapper.java继承BaseMapper<User> ,增加注释


@Repository
public interface UserMapper extends BaseMapper<User> {


13.service包中新建UserService继承BserService<User>,调用UserMapper


/**
 *环境搭建调用userMapper
 */
@Service
public class UserService extends BaseService<User> {
    @Autowired
    private UserMapper userMapper;
}


14.controller层新建UserController,测试userd的增删,改查及分页功能


/**
 * 增删改查及分页功能
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("addUser")
    @ResponseBody
    public String addUser(User user) throws Exception {
        userService.insert(user);
        return "添加成功";
    }

    @RequestMapping("delUser")
    @ResponseBody
    public String delUser(Integer id) throws Exception {
        userService.delete(id);
        return "删除成功";
    }

    @RequestMapping("updateUser")
    @ResponseBody
    public String updateUser(User user) throws Exception {
        userService.update(user);
        return "更新成功";
    }

    @RequestMapping("queryUserList")
    @ResponseBody
    public PageInfo<User> queryUserList(BaseQuery query) throws Exception {
        return userService.queryForPage(query);
    }

}


15启动 jetty 服务器

16.视图页面部分代码接收结果显示:

测试添加user功能

image.png

测试分页查询功能

image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容