Gary Travers carried out the assault on Sheriff John Rafferty from his cell door inside Airdrie Sheriff Court.
The 38-year-old had earlier refused to appear in the dock.
Travers appeared at the High Court in Glasgow yesterday after admitting to the attack.
It is believed to be the first time in Scotland someone has been convicted for assaulting a sheriff or judge within a court building.
Lord Pentland yesterday told Travers he was guilty of "outrageous conduct" and that he had "no respect for the law or other people".
He added: "This was a disgraceful assault on a member of the judiciary in the course of his judicial business."
Travers was sentenced to four years for the assault, but that will only begin after he has served 140 days from a previous jail term.
He will also be supervised for a further three years on his release.
The court earlier heard how Travers had been due to appear before Sheriff Rafferty on April 9, but had refused to leave his cell.
Sheriff Rafferty later decided to convene the court in the cell area so a hearing could take place.
He was joined by others, including a fiscal, a security guard and two police officers.
Travers's door was kept locked and communication was made through an open hatch.
Prosecutor Murdoch MacTaggart told how Sheriff Rafferty informed Travers that his application for bail was being refused.
Mr MacTaggart added: "Upon hearing this, the accused - who had a white polystyrene cup in his hand - deliberately threw the contents through the open hatch."
The urine in the container went over the sheriff's face and clothes. It also struck some of the others who had gathered for the hearing.
Travers - who was described as "unruly and aggressive" - was then hauled out of cell by police and arrested.
Mr MacTaggart said Sheriff Rafferty was "naturally disgusted" at what he was subjected to.
He sought medical advice after the incident, but there was found to be no adverse effect.
However, the high court was told that the fiscal who witnessed the attack remains shaken.
Tony Graham, defending, said it was accepted that what had happened to the sheriff was "utterly despicable".