文章目录
基础配置
基本概念及基本依赖
-
基本概念及基本依赖
新建文件夹
- src/mian/java (此下面放项目标准包)
- src/test/java(测试)
- src/main/resources(放配置)
- 一般的标准包为:entity,dao,biz,controller等
- controller:加注解@Controller,@RequestMapper("/xxx")
在pom.xml 把junit版本改成4.12并把build里放入代码 设置jdk版本配置
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>mavan-compiler-plugin</artifactId> <version>3.5.3</version> <configuration> <target>1.8</target> <source>1.8</source> </configuration> </plugin> </plugins>
配置在src/mian/webapp/WEB-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" id="WebApp_ID" version="3.1"> </web-app>
依赖导入
在xml 中的 dependencies 引入这些依赖
<properties> <spring.version>5.1.5.RELEASE</spring.version>//后面写spring版本可简写${spring.version} </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> //文件上传 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- loback支持 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.4</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.25</version> </dependency> </dependencies>
最后在项目的属性→Deployment Assembly→add: maven依赖
mybatis主配置(xml file,需引用dtd文件)
-
mybatis-config.xml
<!-- 实现日志输出到logback --> <settings> <!-- <setting name="logImpl" value="STDOUT_LOGGING" /> --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="lazyLoadTriggerMethods" value="equals"/> <setting name="cacheEnabled" value="true"/> <!-- 让mybatis自动将xxx_xxx列名映射到xxxXx的属性名 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> 若使用了spring-mybatis配置文件 则不必配置以下配置! <environments default="kf"> <environment id="kf"> <!-- 事务管理配置 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据源也就是连接池的配置:数据库连接参数的配置 --> <dataSource type="POOLED"> <!-- 真正放连接参数的地方 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/shop1905" /> <property name="username" value="root" /> <property name="password" value="19980220" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/CommonMapper.xml" />引用一个映射文件<!-- --> <mapper resource="mapper/GoodsMapper.xml" /> <mapper resource="mapper/GoodsTypeMapper.xml" /> <mapper resource="mapper/UserInfoMapper.xml" /> <mapper class="com.octopus.mybatisDemo.dao.GoodsDao2"/> <mapper resource="mapper/GoodsMapper.xml"/> <mapper resource="mapper/GoodsTypeMapper.xml"/> <mapper resource="mapper/UserInfoMapper.xml"/> <mapper resource="mapper/SysUserMapper.xml"/> <mapper resource="mapper/OrderInfoMapper.xml"/> <mapper resource="mapper/OrderDetailMapper.xml"/> </mappers>
springmvc基本配置(Spring bean configuration)
-
springmvc基本配置(Spring bean configuration)
创建Spring bean configuration-主配置文件:
//让spring扫描所有的包, <context:component-scan base-package="com.octopus"/>//记得在下面的Namespaces勾context //导入其他配置 <import resource="xxx.xml" />
springmvc的配置文件 (记得勾选下方mvc)
<mvc:annotation-driven /> //识别注解 <!-- 标准的spring视图配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/content/"></property><!-- value为页面路径 --> <property name="suffix" value=".jsp"></property><!-- 返回不用写后缀.jsp(默认) --> </bean> <!-- 文件上传的支持 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSizePerFile" value="5000000"></property><!-- 文件最大值 --> </bean>
web.xml 的配置(为了能让spring接管)
<servlet> <servlet-name>springservlet</servlet-name><!-- 对应下面的名 --> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <!-- 初始化 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value><!-- 主配置路径 --> </init-param> </servlet> <servlet-mapping><!-- 映射 --> <servlet-name>springservlet</servlet-name> <!-- 对应上面的名 --> <url-pattern>*.do</url-pattern><!-- 接管所有.do请求(不写后缀默认.do) --> </servlet-mapping>
spring-mybatis基本配置(Spring bean configuration)
-
spring-mybatis基本配置
<!-- 数据库连接 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 连接的数据库: <property name="url" value="jdbc:mysql://localhost:3306/shop1905?characterEncoding=UTF-8"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="username" value="root"></property> <property name="password" value="19980220"></property> <property name="maxActive" value="100"></property> </bean> <!-- spring接管mybatis的主要切入点 --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property><!--ref对应上面id --> <!-- 接管mybatis的主配置 value写路径名,classpath默认在resources--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 接管mapper路径文件 --> <property name="mapperLocations" value="classpath:/mapper/*.xml"></property> </bean> <!-- mapper接口扫描配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.octopus.dao"></property> </bean>
基本功能实现
mapper的使用
UserInfoDao的接口 (接口记得注解:@mapper)
mapper的定义(mapper namespace=“xxx” 写对应的接口Dao路径, id=“dao的方法名”,resultType=“对应的实体类或者返回类型” )
- 用resultType必须使用骆驼命名法 使表数据自动转换名字 则需要在mybatis主配置文件中设置
- 也要在mybatis主配置文件或spring-mybatis配置文件中 设置填入好mapper的路径
SqlSession session = MySqlSessionFactory.openSession();//连接数据库
UserInfoDao userInfoDao = session.getMapper(UserInfoDao.class);//通过mapper实现接口功能
UserInfoDao user = userInfoDao.get(1L); //通过id获取对象
文件上传
-
文件上传
上传页面html:
form action="test/test1.do" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file" /> <input type="submit" value="提交" />
控制器中:@Controller
@RequestMapping("/test1") public String test1(MultipartFile file, HttpServletRequest req) { //file与网页的name="file"同名对应 String filename = file.getOriginalFilename(); logger.info("接收到文件:"+filename); req.setAttribute("filename", filename); return "test1";//返回的jsp页面 }
返回的jsp页面:
收到的文件名为:${filename}
日志功能
日志的配置文件xm
-
日志的配置文件xml
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <contextName>logback</contextName> <!--输出到控制台--> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!--按天生成日志--> <appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Prudent>true</Prudent> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern> applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log </FileNamePattern> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %d{yyyy-MM-dd HH:mm:ss} -%msg%n </Pattern> </layout> </appender> <root level="INFO"> <appender-ref ref="console"/> <appender-ref ref="logFile" /> </root> </configuration>
日志在控制器中的实现
@Controller
@RequestMapping("/test")
public class TestController {
//设置日志
private final static Logger logger = LoggerFactory.getLogger(TestController.class);//本类名
@RequestMapping("/test1")
public String test1(MultipartFile file, HttpServletRequest req) {
String filename = file.getOriginalFilename();
logger.info("接收到文件:"+filename); //后台显示
req.setAttribute("filename", filename);
return "test1";
}
}
登陆账号功能
-
登陆账号
在业务类设接口类
public interface UserLoginBiz { public String LOGIN_SUCCESS="success"; public String LOGIN_FAILED="failed"; public String login(String username,String password); public UserInfoDO findUserByUsername(String username); }
在业务类实现类(加注释@Service)
@Service public class UserLoginBizImpl implements UserLoginBiz{ private static final Logger logger = LoggerFactory.getLogger(UserLoginBizImpl.class); @Autowired private UserInfoDao userInfoDao; public String login(String username, String password) { String result = LOGIN_FAILED; //实现业务 UserInfoDO user =null; Map<String,Object> map = new HashMap<String, Object>(); map.put("userName", username); List<UserInfoDO> list = userInfoDao.list(map); if(list.size()!=0) { user=list.get(0); if(user.getUserPwd().equals(password)) { result=LOGIN_SUCCESS; } } //记录日志 logger.info("用户登录:"+username+",结果为:"+result); return result; } public UserInfoDO findUserByUsername(String username) { Map<String,Object> map = new HashMap<String, Object>(); map.put("userName", username); List<UserInfoDO> list = userInfoDao.list(map); if(list.size()!=0) { UserInfoDO user =list.get(0); user.setUserPwd(""); return user; } return null; } }
控制器上 实现功能
@Controller @RequestMapping("/user") public class LogoinController { @Autowired private UserLoginBiz loginBiz; @RequestMapping("/login") @ResponseBody public Map<String,Object> login(String username,String password,HttpServletRequest req){ Map<String,Object> returnData = new HashMap<String, Object>(); String result=loginBiz.login(username, password); if(UserLoginBiz.LOGIN_SUCCESS.equals(result)) { returnData.put("code",0); //处理会话跟踪 HttpSession session =req.getSession(); session.setAttribute("LOGIN_USER", loginBiz.findUserByUsername(username)); }else { returnData.put("code",1); returnData.put("msg","用户名或者密码不正确"); } return returnData; } }
页面上登陆html
用户名:<input type="text" name="username"/><br/> 密码 码:<input type="password" name="pwd"><br/> <input type="button" value="登录" onclick="doLogin()"> <script type="text/javascript"> function doLogin() { //表单验证 //获取数据 var username =$("input[name='username']").val(); var pwd=$("input[name='pwd']").val(); //提交并验证 $.ajax({ url:"user/login.do", //数据传送地址 type:"post", data:{ username:username, //传给地址的参数username,名字要对应 password:pwd },success:function(data){ //获取地址返回值 if(data.code==0){ location.href="/ssmdemo/"; //返回到首页 }else{ alert("登录失败"); } } }); //根据结果进行下一步操作 } </script>
输入账号正确后跳转到首页(jsp)
<%@page pageEncoding="UTF-8" %> <html> <head> <meta charset="UTF-8"> </head> <body> <h2>欢迎,${LOGIN_USER.userName}</h2> </body> </html>
事务管理
-
事务管理
- begin → commit
- begin → rollback
- begin 开启事务
- commit 提交事务
- rollback 回滚事务
事务中 要么一起执行 要么一起不执行 //navicat中begin关键字识别有问题
//mysql也支持start启动事务
call proc();Spring 实现事务:(Spring bean configuration)
-
通过注解选择事务特性: tx:annotation-driven (记得下面勾tx,使用注解) //推荐
//可使用注解支持事务
2.直接用AOP实现声明式事务:(不需要使用注解,记得下面勾aop)
<!-- 事务管理类:是一种增强类 记得下面勾tx ref要对应spring-mybatis里数据库连接id名--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 使用aop声明式事务需要一个tx:advice --> <tx:advice id="txAdvice" transaction-manager="transactionManager"><!--对应上面id--> <!-- 确定哪些特性的方法需要事务的支持 --> <tx:attributes> <tx:method name="trans*" propagation="REQUIRED"/><!-- 这个配置描述什么方法需要什么事务特性 --> <tx:method name="save*" propagation="REQUIRED"/><!-- 支持事务 --> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <!-- 只读 --> </tx:attributes> </tx:advice> <!-- 标准AOP方式将增强织入到切点 --> <aop:config> <aop:pointcut expression="execution(* com.octopus.biz.impl.*.*(..))" id="allBizMethod"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="allBizMethod"/> <!--ref都对应上面id--> </aop:config>
业务类接口
public interface TransferBiz { public int SUCCESS=0; public int FAIL=1; /** * * @param from 转出账户 * @param to 转入账户 * @param amount 金额 * @return 是否成功 */ public int tranfer(TbAccountDO from,TbAccountDO to,long amount); //根据对象获取数据 public TbAccountDO get(Long id); }
业务实现类
@Service public class TransferBizImpl implements TransferBiz{ @Autowired private TbAccountDao dao; @Transactional 注解方式完成事务管理 public int tranfer(TbAccountDO from, TbAccountDO to, long amount) { int r =SUCCESS; from.setBalance(from.getBalance()-amount); to.setBalance(to.getBalance()+amount); dao.update(to); dao.update(from); return r; } public TbAccountDO get(Long id) { return dao.get(id); } }
测试类 实现此事务操作
@ContextConfiguration("classpath:applicationContext.xml") @RunWith(SpringJUnit4ClassRunner.class) public class TestUserTransBiz { @Autowired private TransferBiz biz; @Test public void testTrans() { TbAccountDO from = biz.get(1L);//转出账户 TbAccountDO to= biz.get(2L);//转入账户 biz.tranfer(from, to, 1111); } }
事务传播特性 @Transactional(propagation=xxx)
set select transaction isolation level xxxxx ;