Jaxb accepts xml with extra parameters for unmarshalling


This Content is from Stack Overflow. Question asked by Overdrowsed

I have a servlet which accepts a rectangle xml and adds it to existing xml database. It works fine except it accepts such an xml with any amount of extra parameters as well:


despite the xml being the wrong format servlet returns 200 OK and adds a new rectangle to database but only taking the width and height parameters and omitting extra ones. How can I make sure that only rectangles with two parameters: width and height are accepted?

Rectangle class:

import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;

@XmlType(propOrder = {"width", "height"})
public class Rectangle{
    private int width, height;
    public Rectangle(){}

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;

    public int getWidth() {
        return width;

    public int getHeight() {
        return height;

    public void setWidth(int width) {
        this.width = width;

    public void setHeight(int height) {
        this.height = height;

    public int getDiagonal(){
        return (int)Math.sqrt(width * width + height * height);

    public int getPerimeter(){
        return 2 * (width + height);

    public int getArea(){
        return width * height;

    public boolean validate(){
        return width > 0 && height > 0;

    public String toString() {
        return "Rectangle [" + width + ", " + height + "]";

Unmarshalling code:

//Servlet passes request.getInputStream() as input arguement
public static Rectangle streamToRectangle(InputStream input) throws UnmarshalException, JAXBException{
        JAXBContext context = JAXBContext.newInstance(Rectangle.class);

        Rectangle rectangle = (Rectangle) context.createUnmarshaller().unmarshal(input);

        return rectangle;


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?