06.产品操作
08.用户操作
09.权限控制
10.权限关联与控制
11.AOP日志
06.产品操作
SSM 环境搭建与产品操作
1.数据库与表结构介绍
PLSQL Developer 13 是一个集成开发环境,专门面向Oracle数据库存储程序单元的开发PL/SQL Developer侧重于易用性、代码品质和生产力 。
在maven bin目录下运行以下命令:
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.1.0 -Dpackaging=jar -Dfile=D:mntojdbc14-10.2.0.1.0.jar以上地址信息部分,请根据本地jar包的信息自行修改。
创建用户与授权
数据库我们使用Oracle
-- 用户名 ssm08 -- 登录密码 itheima
-- Create the user create user SSM08 identified by itheima; -- Grant/Revoke role privileges grant connect to SSM08; grant resource to SSM08;
产品表信息描述
CREATE TABLE product( id varchar2(32) default SYS_GUID() PRIMARY KEY, productNum VARCHAR2(50) NOT NULL, productName VARCHAR2(50), cityName VARCHAR2(50), DepartureTime timestamp, productPrice Number, productDesc VARCHAR2(500), productStatus INT, CONSTRAINT product UNIQUE (id, productNum) ) insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,productdesc, productstatus) values ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-002', '北京三日游', '北京', to_timestamp('10-10-2018 10:10:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1200, '不错的旅行', 1); insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,productdesc, productstatus) values ('12B7ABF2A4C544568B0A7C69F36BF8B7', 'itcast-003', '上海五日游', '上海', to_timestamp('25-04-2018 14:30:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1800, '魔都我来了', 0); insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,productdesc, productstatus) values ('9F71F01CB448476DAFB309AA6DF9497F', 'itcast-001', '北京三日游', '北京', to_timestamp('10-10-2018 10:10:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1200, '不错的旅行', 1);
2.SSM环境搭建maven工程
使用Maven管理项目,创建parent工程和子模块。
解决maven项目创建archetype过慢的问题:
archetypeCatalog internal
heima_ssm_parent父工程的
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>cn.bjut</groupId> <artifactId>heima_ssm</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <!-- 统一管理jar包版本 --> <properties> <spring.version>5.0.15.RELEASE</spring.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> <shiro.version>1.2.3</shiro.version> <mybatis.version>3.5.2</mybatis.version> <mysql.version>8.0.17</mysql.version> <oracle.version>10.2.0.1.0</oracle.version> <spring.security.version>5.0.10.RELEASE</spring.security.version> </properties> <!-- 锁定jar包版本 --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> </dependencies> </dependencyManagement> <!-- 项目依赖jar包 --> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--oracle数据库驱动--> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>${oracle.version}</version> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <!-- 添加tomcat7插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </build> <modules> <module>heima_ssm_dao</module> <module>heima_ssm_domain</module> <module>heima_ssm_utils</module> <module>heima_ssm_service</module> <module>heima_ssm_web</module> </modules> </project>
1.3在domain编写实体类
package cn.bjut.ssm.domain; import java.util.Date; /** * 商品信息 */ public class Product { private String id; // 主键 private String productNum; // 编号 唯一 private String productName; // 名称 private String cityName; // 出发城市 private Date departureTime; // 出发时间 private String departureTimeStr; //方便网页展示,数据库里没有对应字段 private double productPrice; // 产品价格 private String productDesc; // 产品描述 private Integer productStatus; // 状态 0 关闭 1 开启 private String productStatusStr; //方便网页展示,数据库里没有对应字段
实体类的pom.xml添加对后面步骤编写的工具类的依赖坐标
<dependencies> <dependency> <groupId>cn.bjut</groupId> <artifactId>heima_ssm_utils</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
选择子模块heima_ssm_dao ,在它的pom.xml里引入兄弟模块的依赖坐标。
<dependencies> <dependency> <groupId>cn.bjut</groupId> <artifactId>heima_ssm_domain</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
新建两个package在java&resources目录下
cn.bjut.ssm.dao
新建一个接口,IProductDao
package cn.bjut.ssm.dao; import cn.bjut.ssm.domain.Product; import java.util.List; public interface IProductDao { //查询所有的产品信息 public List<Product> findAll() throws Exception; }
选择子模块heima_ssm_service ,在它的pom.xml里引入兄弟模块(dao层)的依赖坐标。
<dependencies> <dependency> <groupId>cn.bjut</groupId> <artifactId>heima_ssm_dao</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
在java目录下新建一个package ,在里面新建一个实现类的包impl
cn.bjut.ssm.service
编写接口 IProductService
package cn.bjut.ssm.service; import cn.bjut.ssm.domain.Product; import java.util.List; public interface IProductService { //查询所有的产品信息 public List<Product> findAll() throws Exception; }
编写接口的实现类 ProductServiceImpl
@Service @Transactional //注解的方式配置spring事务管理 public class ProductServiceImpl implements IProductService { @Autowired private IProductDao productDao; @Override public List<Product> findAll()throws Exception{ return productDao.findAll(); } }
1.SSM环境搭建与产品操作.pdf 里面是用mybatis的注解方式查询操作数据库,现在我选择用.xml配置文件的方式使用mybatis
在 heima_ssm_dao 子模块的resources目录下,新建一个cn.bjut.ssm.dao包(package),然后在其中新建一个文件:
IProductDao.xml 【如果是mybatis整合spring框架,这里的.xml配置文件的文件名必须和与之对应接口的文件名完全一致!】
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
namespace属性的值为:接口的全限定类名。resultType是实体类的全限定类名。【测试后发现整合spring框架并且分父子工程依赖模块,resultType就必须写全限定类名】数据库的字段名放前面,实体类的成员变量名放后面。
<?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="cn.bjut.ssm.dao.IProductDao"> <select id="findAll()" resultType="cn.bjut.ssm.domain.Product"> select id, productNum productNum, productName productName, cityName cityName, DepartureTime DepartureTime, productPrice productPrice, productDesc productDesc, productStatus productStatus from product </select> </mapper>
下面将引入框架用到的各种配置文件
db.properties
day02资料
heima_ssm_dao子模块的resources目录
jdbc.driver=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@192.168.0.104:1521:orcl jdbc.username=ssm08 jdbc.password=itheima
ip地址可以通过ipconfig命令在cmd中获得,1521是oracle数据库的默认端口号。
log4j.properties
heima_ssm_web子模块的resources目录
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m # LOGFILE is set to be a File appender using a PatternLayout. # log4j.appender.LOGFILE=org.apache.log4j.FileAppender # log4j.appender.LOGFILE.File=d:axis.log # log4j.appender.LOGFILE.Append=true # log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout # log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m
applicationContext-dao.xml
heima_ssm_dao子模块的resources目录下新建的spring目录
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">使用c3p0数据库连接池
<!--配置c3p0数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--DAO层配置文件开始--> <!--加载数据库配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!--配置c3p0数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /> <!--扫描pojo包,给包下所有pojo对象起别名--> <property name="typeAliasesPackage" value="cn.bjut.ssm.domian"/> </bean> <!--扫描dao接口包路径,生成包下所有接口的代理对象,并且放入spring容器中--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.bjut.ssm.dao"/> </bean> <!--DAO层配置文件结束--> </beans>
sqlMapConfig.xml
heima_ssm_dao子模块的resources目录下新建的mybatis目录的里面。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 配置日志输出类型 --> <setting name="logImpl" value="LOG4J"/> </settings> </configuration>
在heima_ssm_service子模块的resources目录下,新建一个Directory目录名为spring里面放着
applicationContext-trans.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--service层配置文件开始--> <!-- 配置spring创建容器时注解要扫描的包--> <context:component-scan base-package="cn.bjut.ssm.service"/> <!--aop面向切面编程,切面就是切入点和通知的组合--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务的通知--> <tx:advice id="txadvice" transaction-manager="transactionManager"> <!-- 配置事务的属性 propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。 查询方法可以选择SUPPORTS。 read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。 --> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!--配置切面--> <aop:config> <!-- 配置切入点表达式--> <aop:pointcut id="pointcut1" expression="execution(* cn.bjut.ssm.service.impl.*.*(..))"/> <!--建立切入点表达式和事务通知的对应关系 --> <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/> </aop:config> <!--service层配置文件结束--> </beans>
applicationContext-trans.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--service层配置文件开始--> <!-- 配置spring创建容器时,开启注解要扫描的包--> <context:component-scan base-package="cn.bjut.ssm.dao"/> <context:component-scan base-package="cn.bjut.ssm.service"/> <!--aop面向切面编程,切面就是切入点和通知的组合--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置Spring的声明式事务管理 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!--service层配置文件结束--> </beans>
web子模块的resources目录
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <import resource="classpath:spring/applicationContext-dao.xml"/> <import resource="classpath:spring/applicationContext-service.xml"/> </beans>
webappWEB-INF目录下
web.xml 未分页方案
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 配置加载类路径的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 前端控制器(加载classpath:springmvc.xml 服务器启动创建servlet) --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 服务器启动的时候,让DispatcherServlet对象创建 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 解决中文乱码过滤器 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
springmvc.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller的注解,别的不扫描 --> <context:component-scan base-package="cn.bjut.ssm.controller"/> <!--开启对SpringMVC注解的支持:处理器映射器,处理器适配器--> <mvc:annotation-driven/> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- JSP文件所在的目录 --> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--释放静态资源,哪些静态资源不拦截--> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/plugins/" mapping="/plugins/**" /> <!-- 支持AOP的注解支持,AOP底层使用代理技术 JDK动态代理,要求必须有接口 cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式 --> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>主页</title> </head> <body> <a href="${pageContext.request.contextPath}/product/findAll.do">查询所有的产品信息</a> </body> </html>
把静态资源文件夹 css、img、plugins文件夹拷贝到webapp目录下;
把pages文件夹放入 WEB-INF目录下。
最后开始编写web子模块的controller类:
ProductController
package cn.bjut.ssm.controller; import cn.bjut.ssm.service.IProductService; import cn.bjut.ssm.domain.Product; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/product") public class ProductController { @Autowired private IProductService productService; //产品添加 // @RequestMapping("/save.do") // public String save(Product product) throws Exception { // productService.save(product); // return "redirect:findAll.do"; // } //查询全部产品 @RequestMapping("/findAll.do") public ModelAndView findAll() throws Exception { ModelAndView mv = new ModelAndView(); List<Product> ps = productService.findAll(); mv.addObject("productList", ps); mv.setViewName("product-list1"); return mv; } }
回到heima_ssm_utils这个子模块下,新建一个工具类。
cn.bjut.ssm.utils.DateUtils
package cn.bjut.ssm.utils; import java.text.ParseException; // import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { //日期转换成字符串 public static String date2String(Date date, String patt) { SimpleDateFormat sdf = new SimpleDateFormat(patt); String format = sdf.format(date); return format; } //字符串转换成日期 public static Date string2Date(String str, String patt) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(patt); Date parse = sdf.parse(str); return parse; } }
heima_ssm_web的pom.xml里面可以添加一个Tomcat7的插件。
<?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"> <parent> <artifactId>heima_ssm</artifactId> <groupId>cn.bjut</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>heima_ssm_web</artifactId> <packaging>war</packaging> <name>heima_ssm_web Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <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> <dependency> <groupId>cn.bjut</groupId> <artifactId>heima_ssm_service</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <build> <finalName>heima_ssm_web</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8888</port> </configuration> </plugin> </plugins> </build> </project>
使用IDEA并且指定Tomcat7插件测试运行的 网页访问路径如下
http://localhost:8888/heima_ssm_web/
6.产品操作-查询全部产品3
根据.jsp页面的需要,重新编辑cn.bjut.ssm.domain
Product.java
package cn.bjut.ssm.domain; import cn.bjut.ssm.utils.DateUtils; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * 商品信息 */ public class Product { private String id; // 主键 private String productNum; // 编号 唯一 private String productName; // 名称 private String cityName; // 出发城市 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm") private Date departureTime; // 出发时间 private String departureTimeStr; //为了页面显示,数据库里没有的字段 private double productPrice; // 产品价格 private String productDesc; // 产品描述 private Integer productStatus; // 状态 0 关闭 1 开启 private String productStatusStr; //为了页面显示,数据库里没有的字段 public String getDepartureTimeStr() { if(departureTime!=null){ departureTimeStr= DateUtils.date2String(departureTime,"yyyy-MM-dd HH:mm:ss"); } return departureTimeStr; } public void setDepartureTimeStr(String departureTimeStr) { this.departureTimeStr = departureTimeStr; } public String getProductStatusStr() { if (productStatus != null) { // 状态 0 关闭 1 开启 if(productStatus==0) productStatusStr="关闭"; if(productStatus==1) productStatusStr="开启"; } return productStatusStr; } public void setProductStatusStr(String productStatusStr) { this.productStatusStr = productStatusStr; } //===============================================================================// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProductNum() { return productNum; } public void setProductNum(String productNum) { this.productNum = productNum; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public Date getDepartureTime() { return departureTime; } public void setDepartureTime(Date departureTime) { this.departureTime = departureTime; } public double getProductPrice() { return productPrice; } public void setProductPrice(double productPrice) { this.productPrice = productPrice; } public String getProductDesc() { return productDesc; } public void setProductDesc(String productDesc) { this.productDesc = productDesc; } public Integer getProductStatus() { return productStatus; } public void setProductStatus(Integer productStatus) { this.productStatus = productStatus; } //========================================================================================// }
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> <!--接口+XML配置使用mybatis时的那些sql语句放置的路径--> <property name="mapperLocations" value="classpath:cn/bjut/ssm/dao/*.xml"/> </bean> <!--扫描dao接口包路径,生成包下所有接口的代理对象,并且放入spring容器中--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.bjut.ssm.dao"/> </bean>此时测试SSM项目会提示报错,理由是找不到findall()方法。因为讲师用的是注解开发mybatis ,而我这里是用:接口类+.xml配置文件的方式。
前面在给oracle数据库创建users ssm08时候,没有指定tablespace,会导致后面没有权限查到数据表。ITHEIMA是DBA权限创建PRODUCT表时所在的表空间。
-- alter user username default tablespace userspace alter user ssm08 default tablespace ITHEIMA;
查询全部产品的
ProductController
@Controller @RequestMapping("/product") public class ProductController { @Autowired private IProductService productService; //查询全部产品 @RequestMapping("/findAll.do") public ModelAndView findAll() throws Exception { ModelAndView mv = new ModelAndView(); List<Product> ps = productService.findAll(); mv.addObject("productList", ps); mv.setViewName("product-list"); return mv; } }
7.product-list.jsp页面制作
使用IDEA处理JSP页面的脚本内容,替换的快捷键是 Ctrl+R
Except Comments可以排除注释的内容。
../
被替换为
${pageContext.request.contextPath}
如果使用MySQL做数据库,那么语句语法是有不同的要注意。
use itheima; drop table if exists `product`; -- 创建1个表 CREATE TABLE `product`( `id` varchar(32) NOT NULL, `productNum` varchar(50) NOT NULL, `productName` varchar(50), `cityName` varchar(50), `departureTime` timestamp, `productPrice` INT, `productDesc` varchar(500), `productStatus` INT, PRIMARY KEY (`id`) ); -- 插入测试数据 insert into product (id, productNum, productName, cityName, departureTime, productPrice,productDesc, productStatus) values ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-002', '北京三日游', '北京', '2018-10-10 10:10:00', 1200, '不错的旅行', 1); insert into product (id, productNum, productName, cityName, departureTime, productPrice,productDesc, productStatus) values ('9F71F01CB448476DAFB309AA6DF9497F', 'itcast-001', '北京三日游', '北京', '2018-10-10 10:10:00', 1200, '不错的旅行', 1); insert into product (id, productNum, productName, cityName, departureTime, productPrice,productDesc, productStatus) values ('12B7ABF2A4C544568B0A7C69F36BF8B7', 'itcast-003', '上海五日游', '上海', '2019-10-10 14:30:00', 1800, '魔都我来了', 0);
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/itheima?serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=root
8.main.jsp页面制作
当前项目默认的index.jsp长得比较简陋,我们希望从index.jsp直接跳转到视觉效果更好的 main.jsp 前端页面。
注释掉超链接<a标签,引入一个 <jsp:forward 标签
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>主页</title> </head> <body> <%--<a href="${pageContext.request.contextPath}/product/findAll.do">查询所有的产品信息</a>--%> <jsp:forward page="WEB-INF/pages/main.jsp"></jsp:forward> </body> </html>
图片资源加载不成功,最后把images目录移动到webapp目录下。
<!-- 内容区域 --> <div class="content-wrapper"> <%--资源相对路径--%> <img src="${pageContext.request.contextPath}/images/center.jpg" width="100%" height="100%" /> </div>
9.产品操作-添加产品流程描述
10.产品操作-产品添加操作
添加产品用资料里给的product-add.jsp页面文件,我把它重命名为product-add2.jsp放到webapp/page/目录下。
在WEB-INF/pages/product-list2.jsp页面的“新建”按钮处添加一个onclick属性,写入浏览器直接跳转文件资源路径。
<button type="button" class="btn btn-default" title="新建" onclick="location.href='../page/product-add2.jsp'"><i class="fa fa-file-o"></i> 新建</button>
控制类方法的添加
ProductController
@Controller @RequestMapping("/product") public class ProductController { @Autowired private IProductService productService; //查询全部产品 @RequestMapping("/findAll.do") public ModelAndView findAll() throws Exception { ModelAndView mv = new ModelAndView(); List<Product> ps = productService.findAll(); mv.addObject("productList", ps); mv.setViewName("product-list2"); return mv; } //产品添加后跳转查询产品 @RequestMapping("/save.do") public String save(Product product)throws Exception{ productService.save(product); return "redirect:findall.do"; } }
Service层
ProductServiceImpl
@Service @Transactional //注解的方式配置spring事务管理 public class ProductServiceImpl implements IProductService { @Autowired private IProductDao productDao; @Override public List<Product> findAll()throws Exception{ return productDao.findAll(); } //服务层保存添加产品调用了DAO层对象的方法 @Override public void save (Product product){ productDao.save(product); } }
DAO层接口的@Insert注解插入数据
public interface IProductDao { //查询所有的产品信息 @Select("select * from product") public List<Product> findAll() throws Exception; // https://www.cnblogs.com/MarlonKang/p/11491217.html @Insert({"insert into product(productNum,productName,cityName,departureTime,productPrice,productDesc,productStatus)", "values(#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})"}) public void save(Product product); }
SQL语句不在一行会报错,所以在每一行都用一对 英文双引号,然后在外侧添加一对{ } ,第一行SQL末尾有一个英文,
//在springMVC框架下的实体类的Date类型的成员变量上使用 //可以实现页面表单提交字符串数据转化成Date类型JAVA数据 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
拓展练习: 删除按钮,通过网页上的 checkbox选中的实现。
-- 查询PRODUCT表中数据 select * from product t;
-- 删除PRODUCT表中数据通过productNum值 delete from PRODUCT where PRODUCTNUM = '1234567890';
使用PL/SQL Developer再Commit一下,提交事务。
现在我们需要在product-list.jsp这个用来展示查询所有产品信息的网页上,添加删除按钮的功能实现。首先要解决的是,那一组自动产生的checkbox的value值的获取和选中状态的判断。这里使用了jQurey技术。
参考教程: checkbox 复选框全选代码
<c:forEach var="product" items="${productList}" varStatus="s" > <tr> <td><input type="checkbox" value="${product.id}" name="Ids" id ="${s.index}" ></td> <td>${product.id}</td> <td>${product.productNum} </td> <td>${product.productName}</td> <td>${product.cityName}</td> <td>${product.departureTimeStr}</td> <td class="text-center">${product.productPrice}</td> <td class="text-center">${product.productDesc}</td> <td class="text-center">${product.productStatusStr}</td> <td class="text-center"> <button type="button" class="btn bg-olive btn-xs">订单</button> <button type="button" class="btn bg-olive btn-xs">详情</button> <button type="button" class="btn bg-olive btn-xs">编辑</button> </td> </tr> </c:forEach>
工具栏那部分按钮代码如下。
<button type="button" class="btn btn-default" title="新建" onclick="location.href='../page/product-add2.jsp'"><i class="fa fa-file-o"></i> 新建</button> <button type="button" class="btn btn-default" title="删除" onclick="deleteProduct()"><i class="fa fa-trash-o"></i> 删除</button>
测试jQuery获取checkbox数组对象,并提取数组元素checkbox的value值。
<script> function deleteProduct() { var arrayObj =document.getElementsByName("Ids"); //s.index从0开始,所以第一行的checkbox的id=0 var checkbox =document.getElementById("0"); //第一弹出的是checkbox的总行数 alert(arrayObj.length); //第二弹出的是第一行的产品ID值 alert(checkbox.value); //获取数组的元素,通过数组索引 //数组索引值为显示的checkbox行数减一 var testGetArrValue=arrayObj[1]; //第三弹出整个checkbox数组中被索引的第2个元素的value值 alert(testGetArrValue.value); var selectList = []; alert(selectList.length); //第四弹出数组初始长度0 $('input[name=Ids]:checked ').each(function () { //这里用所选复选框或运算后的值 //jQuery数组的push方法 selectList.push($(this).val()); }); alert(selectList.length); //第五弹出选中的checkbox个数 } </script>
现在的需求是:如何把JSP页面里的字符串数组-->后台的数组变量。
2 JavaWeb+黑马旅游网javaweb2-15Jquery第1节 JQuery基础 4_JQuery对象和JS对象区别与转换.mp4
服务器端无法直接使用浏览器客户端内容,必须先提交到服务器才行,用表单或者ajax来提交var变量。
2 JavaWeb+黑马旅游网javaweb2-16Ajax和JSON第2节 JQuery方式实现Ajax
通过ajax提交数组时,后端spring MVC中的@RequestParam获取不到参数。ajax请求时增加:traditional: true 就可以正常提交了。
product-list2.jsp
<script> function deleteProduct() { var arrayObj =document.getElementsByName("Ids"); //s.index从0开始,所以第一行的checkbox的id=0 var checkbox =document.getElementById("0"); //第一弹出的是checkbox的总行数 alert(arrayObj.length); //第二弹出的是第一行的产品ID值 alert(checkbox.value); //获取数组的元素,通过数组索引 //数组索引值为显示的checkbox行数减一 var testGetArrValue=arrayObj[1]; //第三弹出整个的checkbox数组中第二行的产品ID值 alert(testGetArrValue.value); var selectList = []; alert(selectList.length); //第四弹出数组初始长度0 $('input[name=Ids]:checked ').each(function () { //这里用所选复选框或运算后的值 //jQuery数组的push方法 selectList.push($(this).val()); }); alert(selectList.length); //第五弹出选中的checkbox总个数 //用jQuery实现AJAX请求提交数据到服务器端 //保存数据到服务器,成功时控制台打印显示信息 var selectListTest = new Array(); selectListTest[0] = "param1"; selectListTest[1] = "param2"; selectListTest[2] = "param3"; $.ajax({ type:"POST", url:"${pageContext.request.contextPath}/product/delete.do", contentType:"application/json",//jQuery的ajax提交数组使得springMVC使用必填参数 //接收用@requestBody data:JSON.stringify(selectList), //数组通过JSON.stringify格式化 success:function (data) { alert(data); } }); } </script>
Web层的Controler控制类的method
//删除产品的某个分类通过产品ID编号 @RequestMapping("/delete.do") public String deleteByNum(@RequestBody List<String> selectList)throws Exception{ System.out.println( "JSP页面通过AJAX技术提交POST请求的路径找到。" ); System.out.println( selectList ); //从List中遍历字符串完成删除操作 for (String productId :selectList ) { System.out.println( productId ); productService.deleteByNum(productId); } System.out.println( "JSP页面通过AJAX技术提交字符串数组成功实现。" ); return"redirect:findAll.do"; }
DAO层接口
package cn.bjut.ssm.dao; import cn.bjut.ssm.domain.Product; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; public interface IProductDao { //查询所有的产品信息 @Select("select * from product") public List<Product> findAll() throws Exception; // https://www.cnblogs.com/MarlonKang/p/11491217.html @Insert({"insert into product(productNum,productName,cityName,departureTime,productPrice,productDesc,productStatus)", "values(#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})"}) public void save(Product product); //删除产品通过产品的ID属性值,oracle数据库的TABLE列的别名字段不区分大小写。 @Delete("delete from PRODUCT where ID = #{id}") public void deleteByNum(String id); }
经过测试,实现了通过浏览器页面上的“删除”按钮+checkbox 来删除oracle数据库的产品表中的信息。
==================================================
end