JAX-RX服务中多次POST后HashMap仅存单条记录的解决方法
解决JAX-RS中HashMap无法保存多次POST请求数据的问题
问题原因
JAX-RS规范中,资源类(比如你的StudentModel)默认是请求作用域——每次HTTP请求到来时,容器都会创建一个新的资源类实例。你声明的studentMap和studentCreated是实例变量,每次POST请求都会使用新实例的集合,之前请求的数据自然丢失,最终GET到的只是最后一次请求对应实例里的Map内容。
解决方案
1. 将资源类设置为单例作用域
添加@Singleton注解,让容器只创建一个StudentModel实例,所有请求共享这个实例的集合,实现数据累积。
2. 替换为线程安全的集合实现
HashMap和HashSet不是线程安全的,多并发请求下可能出现数据不一致、异常问题。需要换成线程安全的实现:
- 用
ConcurrentHashMap替代HashMap - 用
CopyOnWriteArraySet或ConcurrentSkipListSet替代HashSet
3. 检查Student类的getName()返回值
确保每次POST请求的student.getName()返回唯一值(比如Student1、Student2...),如果name重复,put方法会覆盖旧值,也会导致Map中只有最新的一条记录。
修改后的完整代码
@Path("/entity/") @Singleton // 关键:设置为单例作用域 public class StudentModel { // 使用线程安全的集合 public Map<String, Integer> studentMap = new ConcurrentHashMap<>(); public Set<String> studentCreated = new CopyOnWriteArraySet<>(); @Path("{id}/student") @POST @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public Response createRecord(Student student) { studentCreated.add(student.getName()); studentMap.put(student.getName(), student.getPort()); System.out.println("studentName is "+student.getName()+" ID is "+student.getID()); return Response.status(201).entity("{}").build(); } @Path("{id}/student/") @GET @Produces(MediaType.APPLICATION_JSON) public Response getStudentandID(){ return Response.ok().entity(studentMap).build(); } }
内容的提问来源于stack exchange,提问作者data01
相关产品推荐
相关产品推荐

