SpringMvc增删改查

SpringMvc增删改查

  • 一、前期准备
  • 二、逆向生成增删改查
    • 2.2.aspect切面层
    • 2.3.Mybatis generator逆向生成
    • 2.4.根据生成代码编写Biz层与实现类
  • 三、controller层代码编写
  • 四、前台代码与分页代码
  • 五、案例测试

一、前期准备

1.2.导入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.0modelVersion>

  <groupId>com.niyingroupId>
  <artifactId>zjlzy_ssmartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>zjlzy_ssm Maven Webappname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>

    
    
    <spring.version>5.0.2.RELEASEspring.version>
    
    <mybatis.version>3.4.5mybatis.version>
    
    <mysql.version>5.1.44mysql.version>
    
    <pagehelper.version>5.1.2pagehelper.version>
    
    <mybatis.spring.version>1.3.1mybatis.spring.version>
    
    <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    <commons.pool2.version>2.4.3commons.pool2.version>
    
    <log4j2.version>2.9.1log4j2.version>
    <log4j2.disruptor.version>3.2.0log4j2.disruptor.version>
    <slf4j.version>1.7.13slf4j.version>
    
    <junit.version>4.12junit.version>
    <servlet.version>4.0.0servlet.version>
    <lombok.version>1.18.2lombok.version>

    <mybatis.ehcache.version>1.1.0mybatis.ehcache.version>
    <ehcache.version>2.10.0ehcache.version>

    <redis.version>2.9.0redis.version>
    <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    <jackson.version>2.9.3jackson.version>
    <jstl.version>1.2jstl.version>
    <standard.version>1.1.2standard.version>
    <tomcat-jsp-api.version>8.0.47tomcat-jsp-api.version>
    <commons-fileupload.version>1.3.3commons-fileupload.version>
    <hibernate-validator.version>5.0.2.Finalhibernate-validator.version>

    <shiro.version>1.3.2shiro.version>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>


    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>${pagehelper.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>${mybatis.spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.mybatis.cachesgroupId>
      <artifactId>mybatis-ehcacheartifactId>
      <version>${mybatis.ehcache.version}version>
    dependency>
    
    <dependency>
      <groupId>net.sf.ehcachegroupId>
      <artifactId>ehcacheartifactId>
      <version>${ehcache.version}version>
    dependency>

    <dependency>
      <groupId>redis.clientsgroupId>
      <artifactId>jedisartifactId>
      <version>${redis.version}version>
    dependency>
    <dependency>
      <groupId>org.springframework.datagroupId>
      <artifactId>spring-data-redisartifactId>
      <version>${redis.spring.version}version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>${jackson.version}version>
    dependency>

    
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-dbcp2artifactId>
      <version>${commons.dbcp2.version}version>
      <exclusions>
        <exclusion>
          <artifactId>commons-pool2artifactId>
          <groupId>org.apache.commonsgroupId>
        exclusion>
      exclusions>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-pool2artifactId>
      <version>${commons.pool2.version}version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    

    
    
    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>jcl-over-slf4jartifactId>
      <version>${slf4j.version}version>
      <scope>runtimescope>
    dependency>

    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-apiartifactId>
      <version>${log4j2.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-coreartifactId>
      <version>${log4j2.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-slf4j-implartifactId>
      <version>${log4j2.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-webartifactId>
      <version>${log4j2.version}version>
      <scope>runtimescope>
    dependency>

    
    <dependency>
      <groupId>com.lmaxgroupId>
      <artifactId>disruptorartifactId>
      <version>${log4j2.disruptor.version}version>
    dependency>

    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>${servlet.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>${lombok.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>${jstl.version}version>
    dependency>
    <dependency>
      <groupId>taglibsgroupId>
      <artifactId>standardartifactId>
      <version>${standard.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.tomcatgroupId>
      <artifactId>tomcat-jsp-apiartifactId>
      <version>${tomcat-jsp-api.version}version>
    dependency>
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>${commons-fileupload.version}version>
    dependency>

    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-validatorartifactId>
      <version>${hibernate-validator.version}version>
    dependency>

    
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-coreartifactId>
      <version>${shiro.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-webartifactId>
      <version>${shiro.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-springartifactId>
      <version>${shiro.version}version>
    dependency>
  dependencies>

  <build>
    <finalName>zjlzy_ssmfinalName>
    <resources>
      
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
      resource>
      
      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>*.propertiesinclude>
          <include>*.xmlinclude>
        includes>
      resource>
    resources>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.pluginsgroupId>
          <artifactId>maven-compiler-pluginartifactId>
          <version>${maven.compiler.plugin.version}version>
          <configuration>
            <source>${maven.compiler.source}source>
            <target>${maven.compiler.target}target>
            <encoding>${project.build.sourceEncoding}encoding>
          configuration>
        plugin>
        <plugin>
          <groupId>org.mybatis.generatorgroupId>
          <artifactId>mybatis-generator-maven-pluginartifactId>
          <version>1.3.2version>
          <dependencies>
            
            <dependency>
              <groupId>mysqlgroupId>
              <artifactId>mysql-connector-javaartifactId>
              <version>${mysql.version}version>
            dependency>
          dependencies>
          <configuration>
            <overwrite>trueoverwrite>
          configuration>
        plugin>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.1.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.8.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.22.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
      plugins>
  build>
project>

1.3.导入配置文件

①jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://47.100.191.44:3308/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=test01
jdbc.password=test01

②generatorConfig.xml


DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    
    <properties resource="jdbc.properties"/>

    
    <classPathEntry location="D:\\temp1\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>

    
    <context id="infoGuardian">
        
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/> 
        commentGenerator>

        
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        
        <javaTypeResolver>
            
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        
        
        <javaModelGenerator targetPackage="com.niyin.model"
                            targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
            
            <property name="constructorBased" value="true"/>
            
            <property name="trimStrings" value="false"/>
            
            <property name="immutable" value="false"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="com.niyin.mapper"
                         targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>

        
        
        
        
        <javaClientGenerator targetPackage="com.niyin.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            
            <property name="enableSubPackages" value="false"/>
        javaClientGenerator>

        
        
        
        
        
        
        
        
        
        
        
        
        

        <table schema="" tableName="t_mvc_book" domainObjectName="book"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        table>



        
    context>
generatorConfiguration>

③log4j2.xml




<Configuration status="WARN" monitorInterval="30">
	<Properties>
		
		<Property name="LOG_HOME">/root/workspace/lucenedemo/logsProperty>
		<property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/errorproperty>
		<property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warnproperty>
		<property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%nproperty>
	Properties>

	<Appenders>
		
		<Console name="Console" target="SYSTEM_OUT">
			
			<ThresholdFilter level="trace" onMatch="ACCEPT"
				onMismatch="DENY" />
			
			
			<PatternLayout pattern="${PATTERN}" />
		Console>

		
		
		<File name="log" fileName="logs/test.log" append="false">
			<PatternLayout
				pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		File>
		
		<RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
			filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
			
			<ThresholdFilter level="info" onMatch="ACCEPT"
				onMismatch="DENY" />
			<PatternLayout
				pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<Policies>
				
				
				
				<TimeBasedTriggeringPolicy interval="1"
					modulate="true" />
				
				
			Policies>
		RollingFile>

		<RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
			filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
			<ThresholdFilter level="warn" onMatch="ACCEPT"
				onMismatch="DENY" />
			<PatternLayout
				pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<Policies>
				<TimeBasedTriggeringPolicy />
				<SizeBasedTriggeringPolicy size="2 kB" />
			Policies>
			
			<DefaultRolloverStrategy max="20" />
		RollingFile>

		<RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
			filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
			<ThresholdFilter level="error" onMatch="ACCEPT"
				onMismatch="DENY" />
			<PatternLayout
				pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<Policies>
				
				<TimeBasedTriggeringPolicy interval="1"
					modulate="true" />
				
			Policies>
		RollingFile>

	Appenders>

	
	<Loggers>
		
		<logger name="org.springframework" level="INFO">logger>
		<logger name="org.mybatis" level="INFO">logger>

		
		<logger name="org.springframework" level="ERROR" />
		<logger name="org.hibernate" level="ERROR" />
		<logger name="org.apache.struts2" level="ERROR" />
		<logger name="com.opensymphony.xwork2" level="ERROR" />
		<logger name="org.jboss" level="ERROR" />


		
		<root level="all">
			<appender-ref ref="Console" />
			<appender-ref ref="RollingFileInfo" />
			<appender-ref ref="RollingFileWarn" />
			<appender-ref ref="RollingFileError" />
		root>

	Loggers>

Configuration>

④spring-mybatis.xml


<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
    <context:annotation-config/>
    
    <context:component-scan base-package="com.niyin"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        
        <property name="initialSize" value="10"/>
        
        <property name="maxTotal" value="100"/>
        
        <property name="maxIdle" value="50"/>
        
        <property name="minIdle" value="10"/>
        
        
        <property name="maxWaitMillis" value="-1"/>
    bean>

    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="mapperLocations" value="classpath*:com/niyin/**/mapper/*.xml"/>
        
        <property name="typeAliasesPackage" value="com/niyin/**/model"/>
        
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        value>
                    property>
                bean>
            array>
        property>
    bean>

    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        
        <property name="basePackage" value="com/niyin/**/mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy/>
beans>

⑤spring-context.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <import resource="classpath:spring-mybatis.xml">import>
beans>

⑥spring-mvc.xml


<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: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/aop
      http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:component-scan base-package="com.niyin"/>

    
    <mvc:annotation-driven />

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView">property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    
    


    <aop:aspectj-autoproxy/>

beans>
```
<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">
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-context.xmlparam-value>
  context-param>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  

  
  <filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <async-supported>trueasync-supported>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <servlet>
    <servlet-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
    
    <async-supported>trueasync-supported>
  servlet>
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

⑦修改web.xml文件

二、逆向生成增删改查

2.1.导入相关util类

②PageBean.java

package com.niyin.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

public class PageBean implements Serializable {

	private static final long serialVersionUID = 2422581023658455731L;

	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map<String,String[]> map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getMap() {
		return map;
	}

	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
	
	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

2.2.aspect切面层

package com.niyin.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.niyin.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class PagerAspect {
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        PageBean pageBean=null;
        Object[] ags = args.getArgs();
        for (Object param:ags){
if (param instanceof PageBean){
    pageBean=(PageBean)param;
    break;
}
        }

        if (pageBean!=null&& pageBean.isPagination()){
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        }
        Object lst = args.proceed();
        if(pageBean!=null && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List) lst);
            pageBean.setTotal((int) pageInfo.getTotal());
        }
        return lst;
    }
}

2.3.Mybatis generator逆向生成

实体:

package com.niyin.model;

import lombok.ToString;

@ToString
public class book {
    private Integer bid;

    private String bname;

    private Float price;

    public book(Integer bid, String bname, Float price) {
        this.bid = bid;
        this.bname = bname;
        this.price = price;
    }

    public book() {
        super();
    }

    public Integer getBid() {
        return bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }
}

mapper

在这里插
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.niyin.mapper.bookMapper" >
  <resultMap id="BaseResultMap" type="com.niyin.model.book" >
    <constructor >
      <idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    constructor>
  resultMap>
  <sql id="Base_Column_List" >
    bid, bname, price
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  select>


  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  delete>
  <insert id="insert" parameterType="com.niyin.model.book" >
    insert into t_mvc_book (bid, bname, price
      )
    values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
      )
  insert>
  <insert id="insertSelective" parameterType="com.niyin.model.book" >
    insert into t_mvc_book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        bid,
      if>
      <if test="bname != null" >
        bname,
      if>
      <if test="price != null" >
        price,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        #{bid,jdbcType=INTEGER},
      if>
      <if test="bname != null" >
        #{bname,jdbcType=VARCHAR},
      if>
      <if test="price != null" >
        #{price,jdbcType=REAL},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.niyin.model.book" >
    update t_mvc_book
    <set >
      <if test="bname != null" >
        bname = #{bname,jdbcType=VARCHAR},
      if>
      <if test="price != null" >
        price = #{price,jdbcType=REAL},
      if>
    set>
    where bid = #{bid,jdbcType=INTEGER}
  update>
  <update id="updateByPrimaryKey" parameterType="com.niyin.model.book" >
    update t_mvc_book
    set bname = #{bname,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL}
    where bid = #{bid,jdbcType=INTEGER}
  update>

  <select id="selectByPager" resultType="com.niyin.model.book" parameterType="com.niyin.model.book" >
    select *  from t_mvc_book
    <where>
      <if test="bname!=null">
        and bname like concat('%',#{bname},'%')
      if>
    where>
  select>

mapper>
package com.niyin.mapper;

import com.niyin.model.book;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface bookMapper {
    int deleteByPrimaryKey(Integer bid);

    int insert(book record);

    int insertSelective(book record);

    book selectByPrimaryKey(Integer bid);

    int updateByPrimaryKeySelective(book record);

    int updateByPrimaryKey(book record);

    List<book> selectByPager(book b);
}

2.4.根据生成代码编写Biz层与实现类

Biz

package com.niyin.biz;

import com.niyin.model.book;
import com.niyin.utils.PageBean;

import java.util.List;

public interface bookBiz {
    int deleteByPrimaryKey(Integer bid);

    int insert(book record);

    int insertSelective(book record);

    book selectByPrimaryKey(Integer bid);

    int updateByPrimaryKeySelective(book record);

    int updateByPrimaryKey(book record);

    List<book>listPager(book b, PageBean pageBean);
}

impl

package com.niyin.biz.impl;

import com.niyin.biz.bookBiz;
import com.niyin.mapper.bookMapper;
import com.niyin.model.book;
import com.niyin.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class bookBizImpl implements bookBiz {
    @Autowired
    private bookMapper bookMapper;
    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }

    @Override
    public int insert(book record) {
        return bookMapper.insert(record);
    }

    @Override
    public int insertSelective(book record) {
        return bookMapper.insertSelective(record);
    }

    @Override
    public book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }

    @Override
    public int updateByPrimaryKeySelective(book record) {
        return bookMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(book record) {
        return bookMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<book> listPager(book b, PageBean pageBean) {
        return bookMapper.selectByPager(b);
    }
}

三、controller层代码编写

package com.niyin.web;


import com.niyin.biz.bookBiz;
import com.niyin.model.book;
import com.niyin.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/clz")
public class bookController {
    @Autowired
    private bookBiz bookBiz;

    @RequestMapping("/list")
    public String list(book b, HttpServletRequest request){
        PageBean pageBeanage=new PageBean();
        pageBeanage.setRequest(request);
        List<book> books = bookBiz.listPager(b, pageBeanage);
        request.setAttribute("lst",books);
        request.setAttribute("pageBean",pageBeanage);
        return "list";
    };

    @RequestMapping("/add")
    public String add(book b){
        int i = bookBiz.insertSelective(b);
        return "redirect:list";
    };

    @RequestMapping("/del")
    public String del(book b){
      bookBiz.deleteByPrimaryKey(b.getBid());
        return "redirect:list";
    };
    @RequestMapping("/edit")
    public String edit(book b){
        bookBiz.updateByPrimaryKeySelective(b);
        return "redirect:list";
    };

@RequestMapping("/preSave")
    public String preSave(book b, Model model) {
    if (b!=null&&b.getBid()!=null&&b.getBid()!=0){
        book bs = bookBiz.selectByPrimaryKey(b.getBid());
        model.addAttribute("bs",bs);
    }
    return "edit";
}


}
package com.niyin.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
@RequestMapping("/page/{page}")
public String toPage(@PathVariable("page") String page){
    return page;
}
    @RequestMapping("/page/{dir}{page}")
    public String toDirPage(@PathVariable("dir") String dir,@PathVariable("page") String page){
        return dir + "/"+ page;
    }

        @RequestMapping("/order/presave")
        public String orderpre() {
            return "/order/presave";

        }
    @RequestMapping("/clz/presave")
    public String clzerpre() {
        return "/clz/presave";

    }

}

四、前台代码与分页代码

①PageTag.java

package com.niyin.tag;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.niyin.utils.PageBean;

public class PageTag extends BodyTagSupport{
	private PageBean pageBean;// 包含了所有分页相关的元素
	
	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	@Override
	public int doStartTag() throws JspException {
//		没有标签体,要输出内容
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}

	private String toHTML() {
		StringBuffer sb = new StringBuffer();
//		隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
//		上一次请求的URL
		sb.append("
"); sb.append(" "); // 上一次请求的参数 Map<String, String[]> paramMap = pageBean.getMap(); if(paramMap != null && paramMap.size() > 0) { Set<Entry<String, String[]>> entrySet = paramMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { // 参数名 String key = entry.getKey(); // 参数值 for (String value : entry.getValue()) { // 上一次请求的参数,再一次组装成了新的Form表单 // 注意:page参数每次都会提交,我们需要避免 if(!"page".equals(key)) { sb.append(" "); } } } } sb.append(""
); // 分页条 sb.append(""); // 分页执行的JS代码 sb.append(""); return sb.toString(); } }

②zking.tld



<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    
  <description>zking 1.1 core librarydescription>
  <display-name>zking coredisplay-name>
  <tlib-version>1.1tlib-version>
  <short-name>zkingshort-name>
  <uri>http://jsp.veryedu.cnuri>
  
  
  <tag>
    <name>pagename>
    <tag-class>com.niyin.tag.PageTagtag-class>
    <body-content>JSPbody-content>
    <attribute>
        <name>pageBeanname>
        <required>truerequired>
        <rtexprvalue>truertexprvalue>
    attribute>
  tag>
  
taglib>

③list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">script>
    <title>博客列表title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }

        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }

        .page-item.go-input {
            margin: 0 10px;
        }
    style>
head>
<body>
<form class="form-inline"
      action="${pageContext.request.contextPath }/clz/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="bname"
               placeholder="请输入书籍名称">
        
        
<%--        <input name="pagination" value="false" type="hidden">--%>
    div>
    <button type="submit" class="btn btn-primary mb-2">查询button>
    <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/clz/preSave">新增a>
form>

<table class="table table-striped bg-success">
    <thead>
    <tr>
        <th scope="col">博客IDth>
        <th scope="col">标题th>
        <th scope="col">关键字th>
        <th scope="col">操作th>
    tr>
    thead>
    <tbody>
    <c:forEach  var="b" items="${lst }">
        <tr>
            <td>${b.bid }td>
            <td>${b.bname }td>
            <td>${b.price }td>
            <td>
                <a href="${pageContext.request.contextPath }/clz/preSave?bid=${b.bid}">修改a>
                <a href="${pageContext.request.contextPath }/clz/del?bid=${b.bid}">删除a>
            td>
        tr>
    c:forEach>
    tbody>
table>

<z:page pageBean="${pageBean }">z:page>
body>
html>

④edit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>博客的编辑界面title>
head>
<body>
<form action="${pageContext.request.contextPath }/clz/${empty bs ? 'add' : 'edit'}" method="post">
    id:<input type="text" name="bid" value="${bs.bid }"><br>
    bname:<input type="text" name="bname" value="${bs.bname }"><br>
    price:<input type="text" name="price" value="${bs.price }"><br>
    <input type="submit">
form>
body>
html>

五、案例测试

5.1.模糊查询
SpringMvc增删改查_第1张图片

5.2.新增
SpringMvc增删改查_第2张图片

5.3.修改
SpringMvc增删改查_第3张图片

5.4.删除
SpringMvc增删改查_第4张图片

5.5.分页
SpringMvc增删改查_第5张图片

你可能感兴趣的:(tomcat,java)