英文:
How to write Springboot application logs to a postgresql database
问题
如何在数据库中实现事务,比如记录日志?例如,用户登录后,立即将其记录到表中。
英文:
How you can implement transactions in the database, like logging? For example, the user is logged in and this is immediately written to the table.
答案1
得分: 1
我的实施计划示例。
- 
创建登录页面(登录、密码),使用URL映射
/login。当用户输入凭据时,控制器将他从/login重定向到/success-login页面。 - 
创建控制器,使用GET映射
/success-login。当用户到达此页面时,表示他已登录。因此,在这里您可以编写一个针对PostgreSQL表的SQL查询,类似于id="1",user="user1",event="log in"。 
模型:
@Entity
public class Log {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    String user;
    String event;
// getters, setters, equals, hashcode ...
}
存储库:
public interface LogRepository extends CrudRepository<Log, Long> {
}
控制器:
@Controller
public class LoginController {
    @Autowired
    LogRepository logRepository;
    @GetMapping("/login-success")
    public String loginSuccess() {
        Log log = new Log();
        log.setUser("user1");
        log.setEvent("log in");
        logRepository.save(log);
        return "login-success";
    }
}
英文:
My plan of implementing your example.
- 
Create login page (login, password) with url mapping
/login. When user writes his credentials, a controller redirects him from/loginto/success-loginpage. - 
Create controller with get mapping
/success-login. When user gets to this page, it means that he is logged in. So here you can write an sql query to postgres table, something likeid="1", user="user1", event="log in" 
Model:
@Entity
public class Log {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    String user;
    String event;
// getters, setters, equals, hashcode ...
}
Repository:
public interface LogRepository extends CrudRepository<Log, Long> {
}
Controller:
@Controller
public class LoginController {
    @Autowired
    LogRepository logRepository;
    @GetMapping("/login-success")
    public String loginSuccess() {
        Log log = new Log();
        log.setUser("user1");
        log.setEvent("log in");
        logRepository.save(log);
        return "login-success";
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论