User user=dao.findUserByCode(code);

本文介绍了一个基于Java的用户注册、激活及登录服务的具体实现细节。包括使用UUID作为用户ID,通过DAO层操作数据库完成用户的注册、激活状态更新及登录验证等功能。
package com.itheima.tfy.service.impl;


import java.util.UUID;


import com.itheima.tfy.dao.UserDao;
import com.itheima.tfy.dao.impl.UserDaoImpl;
import com.itheima.tfy.domain.User;


public class UserServiceImpl {
private UserDao dao=new UserDaoImpl();
//激活码由上一层传过来
public void regist(User user){
if(user.getCode()!=null &&user.getCode().equals("")){
throw new RuntimeException("激活码没有传过来");
}
user.setId(UUID.randomUUID().toString());
dao.addUser(user);

}
public void actived(String code){
User user=dao.findUserByCode(code);
if(user==null)
throw new RuntimeException("激活码有误");
user.setActived(true);
dao.update(user);
}
/**
* 登录
* @param username
* @param password
* @return 用户名或密码错误 或没有激活码都返回null
*/
public User login(String username,String password){
User user=dao.findUser(username, password);
//判断是否激活
if(user!=null){
if(!user.isActived()){
user=null;
}
}
return user;
}
}
package dao.impl; import dao.BaseDao; import dao.UserDao; import pojo.Cake; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class CakeDaoImpl extends BaseDao implements UserDao { PreparedStatement ps; ResultSet rs; Cake cake; List<Cake> list=new ArrayList<>(); int i; @Override public List<Cake> findList(){ try { String sql="select * from smbms_user"; rs=super.select(sql,null); while(rs.next()){ cake=new Cake(); cake.setId(rs.getInt("id")); list.add(cake); } } catch (Exception e) { e.printStackTrace(); }finally { super.b(); } return list; } @Override public int insert(Cake cake) { try { String sql="insert into smbms_user(id,userCode,userName)values(?,?,?)"; Object[] o={cake.getId(),cake.getBillCode(),cake.getProductName()}; i=super.iud(sql,o); } catch (Exception e) { e.printStackTrace(); }finally { super.b(); } return i; } @Override public Cake login(String userName, String userPassword) { try{ String sql="select * from smbms_user where userName=? and userPassword=?"; Object[] objects={userName,userPassword}; rs=select(sql,objects); while(rs.next()){ cake=new Cake(); cake.setProductName(rs.getString("userName")); cake.setBillCode(rs.getString("userPassword")); } }catch(Exception e){ e.getStackTrace(); }finally { b(); } return cake; } } package dao; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class BaseDao { public Connection conn=a(); public PreparedStatement ps=null; public ResultSet rs=null; public static String driver; public static String url; public static String name; public static String pwd; int i; static{ InputStream is =BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties=new Properties(); try { properties.load(is); driver= properties.getProperty("jdbc.driver"); url= properties.getProperty("jdbc.url"); name= properties.getProperty("jdbc.name"); pwd= properties.getProperty("jdbc.pwd"); } catch (IOException e) { e.printStackTrace(); } } public Connection a(){ try { Class.forName(driver); conn= DriverManager.getConnection(url,name,pwd); } catch (Exception e) { e.printStackTrace(); } return conn; } public ResultSet select(String sql,Object... obj){ if(a()!=null) { try { ps=conn.prepareStatement(sql); if(obj!=null&&obj.length!=0){ for(int j=0;j<obj.length;j++){ ps.setObject(j+1,obj[j]); } } rs=ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } } return rs; } public int iud(String sql,Object[] obj){ if(a()!=null){ try { ps=conn.prepareStatement(sql); if(obj!=null&&obj.length!=0){ for(int j=0;j<obj.length;j++){ ps.setObject(j+1,obj[j]); } } i=ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } return i; } public void b(){ try { if(conn!=null) { conn.close(); } if(ps!=null){ ps.close(); } if(rs!=null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } } package dao; import pojo.Cake; import java.util.List; public interface UserDao { public List<Cake> findList() ; public int insert(Cake cake); public Cake login(String userName, String userPassword); } 还有jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/smbms jdbc.name=root jdbc.pwd=123456
最新发布
11-19
@Slf4j @Service @Profile("mysql") public class AdminServiceImpl implements AdminService{ @Autowired private UserRepository userRepository; @Autowired private PasswordUtil passwordUtil; @Value("${app.max-users}") private long maxUserCount; @Override public OperationResponse<UserRegisterSuccessDTO> addUser(UserRegisterDTO userRegisterDTO) { if (!userRegisterDTO.getEmail().contains("@")) { return OperationResponse.failure(ErrorCode.INVALID_EMAIL); } if (userRegisterDTO.getPassword().length() < 6) { return OperationResponse.failure(ErrorCode.PASSWORD_TOO_SHORT); } // 检查是否达到最大用户数 long currentCount = userRepository.count(); if(currentCount >= maxUserCount) { log.error("Maximum user limit reached"); return OperationResponse.failure(ErrorCode.MAX_USER_LIMIT); } // 检查邮箱是否重复 if (userRepository.existsByEmail(userRegisterDTO.getEmail())) { log.error("Email already exists"); return OperationResponse.failure(ErrorCode.EMAIL_EXISTS); } // 创建用户 UserInfo user = new UserInfo(); user.setUsername(userRegisterDTO.getUsername()); // 密码加密处理 String encodedPwd = passwordUtil.encodePassword(userRegisterDTO.getPassword()); user.setPassword(encodedPwd); user.setEmail(userRegisterDTO.getEmail()); user.setAddress(userRegisterDTO.getAddress()); userRepository.save(user); return OperationResponse.success(new UserRegisterSuccessDTO("User added", user.getId())); } @Transactional @Override public OperationResponse<ResponseDTO> deleteUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); return OperationResponse.failure(ErrorCode.USER_NOT_FOUND); } UserInfo user = userRepository.findByEmail(email).get(); userRepository.deleteByEmail(email); return OperationResponse.success(new ResponseDTO(user.getUsername(), user.getEmail(), user.getAddress())); } @Override public OperationResponse<ResponseDTO> updateUser(UserDTO userDTO) { Optional<UserInfo> userOpt = userRepository.findByEmail(userDTO.getEmail()); UserInfo user = userOpt.get(); if (userDTO.getUsername() != null && !userDTO.getUsername().trim().isEmpty()) { user.setUsername(userDTO.getUsername()); } if (userDTO.getPassword() != null && !userDTO.getPassword().trim().isEmpty()) { String encodedPwd = passwordUtil.encodePassword(userDTO.getPassword()); user.setPassword(encodedPwd); } if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) { user.setEmail(userDTO.getEmail()); } if (userDTO.getAddress() != null && !userDTO.getAddress().trim().isEmpty()) { user.setAddress(userDTO.getAddress()); } userRepository.save(user); return OperationResponse.success(new ResponseDTO(user.getUsername(), user.getEmail(), user.getAddress())); } @Override public OperationResponse<ResponseDTO> getUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); return OperationResponse.failure(ErrorCode.USER_NOT_FOUND); } UserInfo user = userRepository.findByEmail(email).get(); return OperationResponse.success(new ResponseDTO(user.getUsername(), user.getEmail(), user.getAddress())); } } 生成相应的测试代码
09-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值