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

2024-04-29 07:52

本文主要是介绍JAVA:后端框架-将servlet+jsp改为springboot+jsp需要做什么,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

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

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

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

exception(自定义异常)

sercurity

servlet :换为controller


操作                         servlet                          springboot
改包名(可改可不改)commonconfig
添加注解pojopojo
添加注解serviceservice
添加注解exceptionexception
替换servletcontroller
添加注解daodao
添加注解sercuritysercurity

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

import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class EasUser {@Idprivate 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 {@Idprivate 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 {@Autowiredprivate 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.Driverspring.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 {@Beanpublic 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;}@Beanpublic 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 {@Autowiredprivate 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 {@Beanpublic SecurityManager securityManager(MyCustomRealm myCustomRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(myCustomRealm);return securityManager;}@Beanpublic 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 {@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {// 实现用户授权逻辑return null;}@Overrideprotected 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 {@Autowiredprivate 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();}}
}

这篇关于JAVA:后端框架-将servlet+jsp改为springboot+jsp需要做什么的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/945515

相关文章

Spring MapFactoryBean应用详解

在我们工作中,尤其是电商系统中,一个庞大的电商平台不是一个封闭的平台,往往还伴生着一个开放平台,用以接入各个企业,以实现一种共赢的局面,一般来讲,针对于这种业务场景,首先浮现在开发人员脑海中的往往是工厂模式,但普通的工厂模式使用起来相对比较麻烦,而Spring则给我们提供了一种使用配置方式来扩展工厂,大大简化了我们开发的工作量,同时也做到了不同合作媒体之间的解耦。 下面我们就以一个实际的

从零开始使用Docker构建Java Web开发运行环境

概述 前面我们讲了关于Docker的一些基本概念和操作,今天我们以一个简单的Java Web例子来说一下Docker在日常工作中的应用,本篇主要讲如下几部分内容:创建jdk镜像、创建resin镜像、启动web项目。因为本篇中的内容都是基于Dockerfile来创建的,针对于不是很熟悉Dockerfile的读者来说可以先熟悉一下Dockerfile的相关知识:https://docs.docker

java.lang.ExceptionInInitializerError异常分析

今天在项目开发时遇到一个问题,整个项目是使用Spring等框架搭建起来的在运行项目时不报任何的异常信息,就是找不到某个类信息,各方查找该类确实是存在的,最后通过断点跟踪时在异常栈内发现java.lang.ExceptionInInitializerError这个异常信息,但这个异常信息没有在控制台或者日志系统中抛出来,查明原因之后就对症下药最终解决了该问题。查找该问题也着实费了一翻功夫,正好趁此机

mule 异步方式是一种单向调用,调用者不需要获得响应。

异步方式通过inbound和outbound endpoint的exchange-pattern=”one-way”实现。 使用基本的Stdio Transport验证,通过标准输入传输字符串,将其原样传递给标准输出进行显示。相应配置如下: stdio-asynchronous-single.xml Java代码   1.      <?xml version="1.0" encoding

Java proxy HTTP ftp socket

public class ProxySelectorTest{//测试本地JVM的网络默认配置public void setLocalProxy(){Properties prop = System.getProperties();//设置HTTP访问要使用的代理服务器的地址prop.setProperty("http.proxyHost", "10.10.0.96");//设置HTTP访问要使用

八股Day5 框架篇

Day5 框架 1.Spring框架的bean是单例的吗 2.Spring框架的bean是线程安全的吗 3.什么是AOP 4.项目使用AOP了吗 5.Spring的事务如何实现 6.Spring中事务失效的场景有哪些 7.Spring的Bean的生命周期 8.Spring的循环利用 9.具体解决流程 10.构造方法出现循环依赖怎么办 11.SpringMvc执行流程 12.SpringBoot自

spring 声明 hibernate 的 事物的几种用法

以下两个bean的配置是下面要用到的。<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/

java 泛型的使用

<pre name="code" class="plain">写法一般都会在基类中看到,而且是使用了JAVA泛型的,比如我们J2EE中的BaseDAO什么的,请看代码,其实简写了,分开写就明了了。基类: import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;public abstract class S

基于 Spring Boot 博客系统开发(八)

基于 Spring Boot 博客系统开发(八) 本系统是简易的个人博客系统开发,为了更加熟练地掌握 SprIng Boot 框架及相关技术的使用。🌿🌿🌿 基于 Spring Boot 博客系统开发(七)👈👈 仪表盘实现效果 显示文章总数、评论总数、最新文章和最新留言。实现步骤,首先后端获取文章评论相关数据,然后前端使用thymeleaf获取后端model中的数据进行渲染。 后

java jersey restful 详解

前言 在短信平台一期工作中,为便于移动平台的开发,使用了Java Jersey框架开发RESTFul风格的Web Service接口。在使用的过程中发现了一些问题并积累了一些经验。因此,做下总结备忘,同时也希望对有需要的同仁有好的借鉴和帮助。 简介 Jersey是JAX-RS(JSR311)开源参考实现用于构建RESTful Web service,它包含三个部分: 核心服务器(Co