@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
mapper接口:
@Repository//代表被spring接管
@Mapper//这个注解表示这是一个mybatis的mapper接口
//@MapperScan("com.moli.mapper")用来扫描包,发现mapper接口,用在主类上
public interface UserMapper {
int add(User user);
int delete(@Param("id")int id);
int update(User user);
List query();
User queryById(@Param("id") int id);
}
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping("/queryuser")
public List a(){
List query = userMapper.query();
return query;
}
@RequestMapping("/queryid/{id}")
public User byid(@PathVariable int id){
User user = userMapper.queryById(id);
return user;
}
@RequestMapping("/adduser")
public int adduser(){
int add = userMapper.add(new User(2,"哈哈哈","qwdfb"));
return add;
}
@RequestMapping("/updateuser")
public int updateuser(){
int update = userMapper.update(new User(7, "嗷嗷嗷", "wjs098987"));
return update;
}
@RequestMapping("/del")
public int del(){
int delete = userMapper.delete(9);
return delete;
}
}
4.SpringSecurity
4.1简介
在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的第一天就考虑进来。如果在应用开发的后期才考虑安全的问题,就可能陷入一个两难的境地:一方面,应用存在严重的安全漏洞,无法满足用户的要求,并可能造成用户的隐私数据被攻击者窃取;另一方面,应用的基本架构已经确定,要修复安全漏洞,可能需要对系统的架构做出比较重大的调整,影响应用的发布进程。
Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
@Controller
public class RouterController {
@RequestMapping({"/" ,"/index"})
public String toindex(){
return "index";
}
@RequestMapping("/level1/{id}")
public String l1(@PathVariable int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String l2(@PathVariable int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String l3(@PathVariable("id") int id){
return "views/level3/"+id;
}
@RequestMapping("/toLogin")
public String tologin(){
return "views/login";
}
}
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
SecurityUtils.setSecurityManager(securityManager);
//获得当前对象subject
Subject currentUser = SecurityUtils.getSubject();
//通过当前对象拿到session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
//Token令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);//记住我
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//粗粒度 test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//细粒度 a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
4.mapper接口
@Repository
@Mapper
public interface UserMapper {
public User queryByName(String name);
}
5.resource里的UserrMapper.xml
select * from mybatis.user where user.name=#{name}
6.service
public interface UserService {
public User queryByName(String name);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserrMapper userrMapper;
@Override
public User queryByName(String name) {
return userrMapper.queryByName(name);
}
}