JAVA:后端框架-将servlet+jsp改为springboot+jsp需要做什么

发布于:2024-04-29 ⋅ 阅读:(37) ⋅ 点赞:(0)

目录

POJO(作为实体): 添加注释@Entity @Id

 DAO(作为存储库):使用Spring Boot时,不需要具体的DAO实现或JdbcUtils

COMMON(应用配置):JdbcUtils 与 JdbcTemplate bean(放入config包)

exception(自定义异常)

sercurity

servlet :换为controller


操作                         servlet                          springboot
改包名(可改可不改) common config
添加注解 pojo pojo
添加注解 service service
添加注解 exception exception
替换 servlet controller
添加注解 dao dao
添加注解 sercurity sercurity

POJO(作为实体): 添加注释@Entity @Id

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class EasUser {
    @Id
    private Long id;
    private String username;
    private String password; // 考虑使用散列存储密码以提高安全性

    // getters 和 setters
}

 DAO(作为存储库):使用Spring Boot时,不需要具体的DAO实现JdbcUtils

在Spring Boot中使用Spring Data JPA时,你通常不需要像传统方式那样实现数据访问对象(DAO)的具体实现类,例如你提到的`EasUserDaoImpl`。Spring Data JPA通过使用接口继承`JpaRepository`或`CrudRepository`来自动化许多常见的数据访问模式,从而使得手动实现DAO层变得多余。下面我将介绍如何用Spring Data JPA接口替代`EasUserDaoImpl`的实现。

### 步骤 1: 创建接口继承JpaRepository

(DAO包)你首先需要创建一个接口,这个接口将继承`JpaRepository`,该接口提供了丰富的数据访问方法,包括基本的CRUD操作和分页支持。

import org.springframework.data.jpa.repository.JpaRepository;

public interface EasUserDao extends JpaRepository<EasUser, Long> {
    // 在这里可以添加自定义的查询方法
}

### 步骤 2: 定义实体类

POJO包:确保你的`EasUser`类使用了JPA注解,正确映射到数据库表。

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "eas_user")
public class EasUser {
    @Id
    private Long id;
    private String username;
    private String password;

    // getters 和 setters
}

### 步骤 3: 使用Repository

(Service包)一旦你定义了`EasUserDao`接口,你可以在服务层直接自动注入这个接口,并使用它来进行数据库操作,而无需编写任何实现代码。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EasUserService {

    @Autowired
    private EasUserDao easUserDao;

    public EasUser findUserById(Long id) {
        return easUserDao.findById(id).orElse(null);
    }

    public EasUser saveUser(EasUser user) {
        return easUserDao.save(user);
    }

    // 其他业务逻辑方法
}

这样,你就可以删除原有的`EasUserDaoImpl`类,因为所有的数据访问逻辑现在都通过Spring Data JPA自动处理了。这种方式简化了代码,减少了错误,并提高了开发效率。

### 步骤 4: 配置数据源

最后,确保在你的Spring Boot应用程序中配置了合适的数据源和JPA属性,通常这些配置在`application.properties`或`application.yml`文件中设置。

spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabase
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

这样,你的Spring Boot应用就会使用Spring Data JPA来管理`EasUser`的数据访问逻辑,无需手动实现任何DAO层的代码。如果有任何特定的查询需求,可以在`EasUserDao`接口中定义自定义查询方法。

COMMON(应用配置):JdbcUtils 与 JdbcTemplate bean(放入config包)

JpaRepository处理了大多数常见的数据访问模式,如果需要针对JDBC的特定配置或工具,可以在配置中配置一个JdbcTemplate bean(一般不需要,可以不用增加)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
public class JdbcConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/yourDatabase");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

exception(自定义异常)

要将一个自定义异常,如`EasUserNotFoundException`,整合到你的Spring Boot应用程序中,你可以在服务层或控制器层使用它来处理特定的异常情况。例如,在用户查询中,如果找不到指定的用户,可以抛出这个异常。这种方法可以帮助你的应用程序更清晰地处理错误和异常情况。

### 步骤 1: 定义自定义异常类

(exception包)假设你已经有一个名为`EasUserNotFoundException`的异常类。这个类应该是`RuntimeException`的子类,并且可以包含一个接受错误信息的构造函数。例如:

public class EasUserNotFoundException extends RuntimeException {
    public EasUserNotFoundException(String message) {
        super(message);
    }
}

### 步骤 2: 在服务层使用异常

在你的服务层,特别是在需要抛出异常的地方,你可以使用这个自定义异常。例如,在查找用户时,如果用户不存在,则抛出`EasUserNotFoundException`。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EasUserService {

    @Autowired
    private EasUserDao easUserDao;

    public EasUser findUserById(Long id) {
        return easUserDao.findById(id).orElseThrow(() -> 
            new EasUserNotFoundException("User with ID " + id + " not found."));
    }
}

### 步骤 3: 异常处理

在Spring Boot中,你可以使用`@ControllerAdvice`或`@RestControllerAdvice`来创建一个全局异常处理器。这个处理器可以捕获`EasUserNotFoundException`并返回适当的响应。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EasUserNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String userNotFoundExceptionHandler(EasUserNotFoundException ex) {
        return ex.getMessage();
    }
}

这样,每当`EasUserNotFoundException`被抛出时,你的Spring Boot应用将会捕获这个异常并返回一个HTTP 404状态码,以及一个描述性的错误消息。

### 步骤 4: 配置和测试

确保你的Spring Boot应用程序配置正确,并进行适当的测试,以验证当用户不存在时,异常能够被正确地捕获和处理。

通过这种方式,你可以将`EasUserNotFoundException`有效地整合进你的Spring Boot应用程序中,增强错误处理的清晰度和效率。

sercurity

在Spring Boot中整合Apache Shiro安全框架,以下是一个使用Spring Boot和Shiro的示例配置。

### 1. Shiro配置类(ShiroConfig.java)增加注解@Configuration @Bean

(config包)这个配置类负责设置Shiro的核心组件,如安全管理器、会话管理器和自定义Realm。

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroWebConfiguration;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public SecurityManager securityManager(MyCustomRealm myCustomRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myCustomRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        ShiroFilterChainDefinition filterChainDefinition = new DefaultShiroFilterChainDefinition();
        filterChainDefinition.addPathDefinition("/logout", "logout");
        filterChainDefinition.addPathDefinition("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinition.getFilterChainMap());
        return shiroFilterFactoryBean;
    }
}

### 2. 自定义Realm类(MyCustomRealm.java)增加注解@Component

(sercurity包)这个类是Shiro进行身份验证和授权的核心。你需要继承`AuthorizingRealm`并实现相应的方法来进行用户的身份验证和授权。

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

@Component
public class MyCustomRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 实现用户授权逻辑
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 实现用户身份验证逻辑
        String username = (String) token.getPrincipal();
        // 从数据库或其他地方获取用户信息
        if ("known-user".equals(username)) {
            return new SimpleAuthenticationInfo(username, "password", getName());
        }
        throw new AuthenticationException("User not found");
    }
}

servlet :换为controller

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public ResponseEntity<?> loginUser(@RequestParam String username, @RequestParam String password) {
        EasUser user = userService.loginUser(username, password);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
}

service:加密

如果你的项目中没有使用 `PasswordEncoder`,也就是说没有引入 Spring Security 或其他库来处理密码加密,那么你将需要手动处理密码验证。不过,强烈建议为了保证安全性,使用某种形式的密码加密。

下面我将说明如何在没有 `PasswordEncoder` 的情况下处理密码验证,并给出如何引入基本的密码加密机制的建议。

### 不使用 `PasswordEncoder` 的密码验证

在这种情况下,我们假设密码存储在数据库中是明文的(这是不推荐的做法,因为这样做非常不安全)。这里的示例仍然放在 `EasUserService` 中,该类位于 `service` 文件夹中。

#### 实现 `EasUserLogin` 方法(无加密)`

package com.moumou.jiaoyvne.service;

import com.moumou.jiaoyvne.dao.EasUserDao;
import com.moumou.jiaoyvne.model.EasUser;
import com.moumou.jiaoyvne.exception.EasUserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EasUserService {

    @Autowired
    private EasUserDao userDao;

    public EasUser EasUserLogin(String username, String password) throws EasUserNotFoundException {
        EasUser user = userDao.findByUsername(username);
        if (user == null) {
            throw new EasUserNotFoundException("用户不存在");
        }
        if (!user.getPassword().equals(password)) {
            throw new EasUserNotFoundException("密码错误");
        }
        return user;
    }
}


### 引入基本密码加密

如果你考虑将来引入密码加密,你可以使用 Java 的内置库来实现。例如,使用 `java.security` 包中的 `MessageDigest` 类来进行简单的 SHA-256 加密。虽然这不如专业的密码处理库(如 BCrypt)安全,但它比明文存储安全得多。

#### 修改 `EasUserService` 添加简单的 SHA-256 加密

package com.moumou.jiaoyvne.service;

import com.moumou.jiaoyvne.dao.EasUserDao;
import com.moumou.jiaoyvne.model.EasUser;
import com.moumou.jiaoyvne.exception.EasUserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

@Service
public class EasUserService {

    @Autowired
    private EasUserDao userDao;

    private String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
        return DatatypeConverter.printHexBinary(md.digest()).toUpperCase();
    }

    public EasUser EasUserLogin(String username, String password) throws EasUserNotFoundException, NoSuchAlgorithmException {
        EasUser user = userDao.findByUsername(username);
        if (user == null) {
            throw new EasUserNotFoundException("用户不存在");
        }
        String hashedPassword = hashPassword(password);
        if (!user.getPassword().equals(hashedPassword)) {
            throw new EasUserNotFoundException("密码错误");
        }
        return user;
    }
}


### 注意事项
- **安全性**:使用任何加密方法时,考虑添加盐(salt)来提高安全性。
- **依赖性**:确保你的项目能处理额外的异常,如 `NoSuchAlgorithmException`。

通过以上步骤,你可以在不使用 `PasswordEncoder` 的情况下实现密码验证,同时留有空间逐步引入更安全的密码处理方法。


网站公告

今日签到

点亮在社区的每一天
去签到