In the previous example you can see how to convert a bean into an XML persistence. Now we’ll do the opposite, converting the XML back to a bean. For the BeanToXML class use in this example please refer to How do I convert a bean to XML persistence? example.
package org.kodejava.bean;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.util.Objects;
public class XmlToBean {
public static void main(String[] args) {
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
Objects.requireNonNull(XmlToBean.class.getResourceAsStream("/Bean.xml"))));
// Reads the next object from the underlying input stream.
BeanToXML bean = (BeanToXML) decoder.readObject();
decoder.close();
System.out.println("ID = " + bean.getId());
System.out.println("Item Name = " + bean.getItemName());
System.out.println("Item Colour = " + bean.getItemColour());
System.out.println("Item Quantities = " + bean.getItemQuantities());
}
}
I have created a servlet based web application, and I want to used Spring beans in it. So how do I do this in my servlet. Well, it is simple enough to do this. First, I have to obtain the Spring’s WebApplicationContext, from where I can grab the required bean by my servlet.
Let’s see some lines of code on how to do it, here we go:
Inside the Java Servlet doGet() method above I get the ServletContext, next the WebApplicationContextUtils help me to get Spring’s WebApplicationContext. With this object in my hand I can get my UserDao implementation and do a query from database.
Spring Bean Servlet Example
Here are the supporting classes and the configurations.
UserDao.java
package org.kodejava.servlet.dao;
import org.kodejava.servlet.model.User;
public interface UserDao {
User getUser(Long userId);
}
UserDaoImpl.java
package org.kodejava.servlet.dao.impl;
import org.kodejava.servlet.dao.UserDao;
import org.kodejava.servlet.model.User;
public class UserDaoImpl implements UserDao {
@Override
public User getUser(Long userId) {
if (userId == 1L) {
return new User(1L, "jdoe", "John Doe");
}
return new User();
}
}
User.java
package org.kodejava.servlet.model;
import java.util.Objects;
public class User {
private Long id;
private String username;
private String realName;
public User() {
}
public User(Long id, String username, String realName) {
this.id = id;
this.username = username;
this.realName = realName;
}
// Getters and Setters
}