Spring boot实例
代码下载http://pan.baidu.com/s/1c2aXLkc 密码:2joh
1、代码包规划

Application主类
package com.smart;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.WebApplicationInitializer; import javax.sql.DataSource; //@Configuration
//@ComponentScan
//@EnableAutoConfiguration
@SpringBootApplication
@EnableTransactionManagement
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer {
@Bean
public PlatformTransactionManager txManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
} public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
2 、持久层
UserDao类
findUserByUserName():根据用户名获取对象
updateLoginInfo():更新用户积分,最后登录IP及最后登录时间
package com.smart.dao;
import com.smart.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class UserDao {
private JdbcTemplate jdbcTemplate; private final static String MATCH_COUNT_SQL = " SELECT count(*) FROM t_user " +
" WHERE user_name =? and password=? ";
private final static String UPDATE_LOGIN_INFO_SQL = " UPDATE t_user SET " +
" last_visit=?,last_ip=?,credits=? WHERE user_id =?"; public int getMatchCount(String userName, String password) { return jdbcTemplate.queryForObject(MATCH_COUNT_SQL, new Object[]{userName, password}, Integer.class);
} public User findUserByUserName(final String userName) {
String sqlStr = " SELECT user_id,user_name,credits "
+ " FROM t_user WHERE user_name =? ";
final User user = new User();
jdbcTemplate.query(sqlStr, new Object[]{userName},
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
user.setUserId(rs.getInt("user_id"));
user.setUserName(userName);
user.setCredits(rs.getInt("credits"));
}
});
return user;
} public void updateLoginInfo(User user) {
jdbcTemplate.update(UPDATE_LOGIN_INFO_SQL, new Object[]{user.getLastVisit(),
user.getLastIp(), user.getCredits(), user.getUserId()});
}
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
LoginLogDao类
package com.smart.dao; import com.smart.domain.LoginLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; @Repository
public class LoginLogDao {
@Autowired
private JdbcTemplate jdbcTemplate; //保存登陆日志SQL
private final static String INSERT_LOGIN_LOG_SQL= "INSERT INTO t_login_log(user_id,ip,login_datetime) VALUES(?,?,?)"; public void insertLoginLog(LoginLog loginLog) {
Object[] args = { loginLog.getUserId(), loginLog.getIp(),
loginLog.getLoginDate() };
jdbcTemplate.update(INSERT_LOGIN_LOG_SQL, args);
}
}
3、业务层
UserService类
package com.smart.service; import com.smart.dao.LoginLogDao;
import com.smart.dao.UserDao;
import com.smart.domain.LoginLog;
import com.smart.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
public class UserService { private UserDao userDao; private LoginLogDao loginLogDao; public boolean hasMatchUser(String userName, String password) {
int matchCount =userDao.getMatchCount(userName, password);
return matchCount > 0;
} public User findUserByUserName(String userName) {
return userDao.findUserByUserName(userName);
} @Transactional
public void loginSuccess(User user) {
user.setCredits( 5 + user.getCredits());
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
userDao.updateLoginInfo(user);
loginLogDao.insertLoginLog(loginLog);
} @Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} @Autowired
public void setLoginLogDao(LoginLogDao loginLogDao) {
this.loginLogDao = loginLogDao;
}
}
4、展现层
处理请求:
LoginCommand
package com.smart.web;
public class LoginCommand {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
LoginController
package com.smart.web; import com.smart.domain.User;
import com.smart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Date; @RestController
public class LoginController{
private UserService userService; @RequestMapping(value = {"/","/index.html"})
public ModelAndView loginPage(){
return new ModelAndView("login");
} @RequestMapping(value = "/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){
boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),
loginCommand.getPassword());
if (!isValidUser) {
return new ModelAndView("login", "error", "用户名或密码错误。");
} else {
User user = userService.findUserByUserName(loginCommand
.getUserName());
user.setLastIp(request.getLocalAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
} @Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
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"> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter3</artifactId>
<name>Spring4.x</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
Springboot Controller返回值类型
1、返回页面
@Controller
public class UserController {
@RequestMapping("/logout")
public String logout() {
SecurityUtils.getSubject().logout();
return "login1"; //返回对应的名的页面
}
}
2、返回返回json格式的数据。
@Controller
public class UserController {
@RequestMapping("/logout")
@ResponseBody //加入@ResponseBody 会把返回值写入的http相应body里,详情请自行百度
public String logout() {
SecurityUtils.getSubject().logout();
return "login1";
}
}
3、@RestController注解相当于@ResponseBody + @Controller合在一起的作用
Spring boot实例的更多相关文章
- 【docker】centOS7上部署的mysql和spring boot服务,要求,mysql的时间、java程序服务的时间和宿主机的时间完全保持一致【修改mysql时区,临时和永久】【修改spring boot配置文件时区】【修改docker启动spring boot实例程序时区】
要求:centOS7上部署的mysql和spring boot服务,要求,mysql的时间.java程序服务的时间和宿主机的时间完全保持一致: ============================ ...
- Spring Boot实例Hello World Demo
Spring Boot要求Maven的版本达到3.2或以上. 实例: POM: <project xmlns="http://maven.apache.org/POM/4.0.0&qu ...
- Spring Boot2 系列教程(二十八)Spring Boot 整合 Session 共享
这篇文章是松哥的原创,但是在第一次发布的时候,忘了标记原创,结果被好多号转发,导致我后来整理的时候自己没法标记原创了.写了几百篇原创技术干货了,有一两篇忘记标记原创进而造成的一点点小小损失也能接受,不 ...
- Spring Boot 一个依赖搞定 session 共享,没有比这更简单的方案了!
有的人可能会觉得题目有点夸张,其实不夸张,题目没有使用任何修辞手法!认真读完本文,你就知道松哥说的是对的了! 在传统的单服务架构中,一般来说,只有一个服务器,那么不存在 Session 共享问题,但是 ...
- Spring boot配置多个Redis数据源操作实例
原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...
- Spring Boot + Spring Data + Elasticsearch实例
Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...
- spring boot整合redis多实例
最近项目中遇到需要连接两个redis实例的情况,于是就在spring boot原先的基础上修改了一点. 首先,添加所需的依赖 <dependency> <groupId>org ...
- Spring boot项目搭建及简单实例
Spring boot项目搭建 Spring Boot 概述 Build Anything with Spring Boot:Spring Boot is the starting point for ...
- spring boot 测试插件使用及result风格实例1&打包启动
本节主要内容: 1:spring boot 小插件使用 2:构建第一个简单的result风格的实例并访问 3:将项目打成jar包后启动并访问. 一:添加boot devtools插件: 执行完成后,查 ...
随机推荐
- find and xargs
调整搜索深度 -mandepth 搜索当前目录,而不进入子目录: find . -maxdepth 0 -name "debug*" Linux中find常见用法示例 ·find ...
- python--面向对象封装
from collectoins import namedtuple Point=namedtuple('point',['x','y']) t1=Point(1,2) print(t1.x) pri ...
- 对canvas arc()中counterclockwise参数的一些误解
一直没有很细心地去研究CanvasRenderingContext2D对象的arc方法,对它的认识比较模糊,导致犯了一些错误,特发此文,以纠正之前的错误理解. arc()方法定义如下: arc() 方 ...
- React_Redux_Router
一.react_redux 比较好的blog: blog1, blog2, blog3 主要根据前两个blog总结如下: 1. React在组件内部(包括子组件)为单向数据流且自上向下通过props传 ...
- CSDN第一期总结之三:Thread的问题(转)
C#是一门支持多线程的语言,因此线程的使用也是比较常见的.由于线程的知识在Win32编程的时候已经说得过多,所以在.Net中很少介绍这部分(可能.Net不觉得这部分是它所特有的). 那么线程相关的问题 ...
- css3-calc用法
css3--calc()使用 css3新增的一个功能,可以计算元素的长度 例如说:一个百分百布局中,分左右两侧,中间需要一个分隔空间,使用padding或者margin则会超出100%,这时候使用ca ...
- 阿里妈妈-RAP项目的实践(1)
在同事的推荐下,去了解了一下http://thx.github.io/RAP/study.html#,它是发现在前后端分离开发的神器 下面我们来简单上一组代码,来简单了解一下rap <!DOCT ...
- (转)CentOS6.5安装Darwin Streaming Server搭建RTSP流媒体服务器
参考: 1,CentOS6.5安装Darwin Streaming Server搭建RTSP流媒体服务器 http://www.yimiju.com/articles/567.html
- 【智能无线小车系列十】通过USB摄像头实现网络监控功能
如果仅有静态图像可能还不足以满足我们的需求,我们可能会需要用到实时的监控功能.这里介绍一款小应用:motion.motion的功能可强大了,不仅可以将监控的画面通过视频传输,实时展现,更为强大的是,m ...
- Windows程序设计(0)——编程之前
Windows程序设计之前 1 做什么 2 解决什么问题 3 有哪些资源 在开始真正的编程之前,需要了解要做的事情是什么,要解决的解决的问题是什么,有哪些资源可以使用. 1 Windows程序设计之前 ...