如何在springMVC中获取bean类的数据?

时间:2016-05-09 09:28:32

标签: java spring-mvc

如何从springMVC中的beanclass获取数据? 我正在尝试,但我收到了一个错误。

在Spring MVC中,我没有从bean类中获取数据

这是我的bean类

    public class EmailBean
    {
        private Long id;
        private String from;
        private String to;
        private String subject;
        private String content;
        private String status;

        //getter and setter
    }

这是我的电子邮件发件人

    public class EmailSender extends Thread
    {
        private EmailBean eb;

        public EmailBean getEb()
        {
            return eb;
        }

        public void setEb(EmailBean eb)
        {
            this.eb = eb;
        }

        public void run()
        {
            sendSingleEmail(eb);
        }

        public static void sendSingleEmail(EmailBean eb)
        {

            System.out.println(eb.getTo());
            System.out.println(eb.getSubject());
            System.out.println(eb.getContent());

        }
    }

这是我的主要课程

    public class TestMail {

        public static void main(String[] args)
        {

            try
            {
                EmailBean eb=new EmailBean();
                eb.setFrom("xxx@gmail.com");
                eb.setTo("yyyyy@gmail.com");
                eb.setSubject("Testing Email Subject");
                eb.setContent("Testing Email Content");
                eb.setId(1L);
                eb.setStatus("100");

                EmailSender es=new EmailSender();

                es.start();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }   
    }

当我运行这个TestMail时,为什么不工作?我发错了

    Exception in thread "Thread-0" java.lang.NullPointerException
        at com.candidjava.springmvc.service.EmailSender.sendSingleEmail(EmailSender.java:36)
        at com.candidjava.springmvc.service.EmailSender.run(EmailSender.java:30)

1 个答案:

答案 0 :(得分:0)

你在main方法中犯了一个简单的错误,在启动线程之前只需调用setter方法来设置EmailBean信息,找到下面正确的代码

 public class TestMail {

    public static void main(String[] args)
    {

        try
        {
            EmailBean eb=new EmailBean();
            eb.setFrom("xxx@gmail.com");
            eb.setTo("yyyyy@gmail.com");
            eb.setSubject("Testing Email Subject");
            eb.setContent("Testing Email Content");
            **eb.setId(1L);**
            eb.setStatus("100");

            EmailSender es=new EmailSender();
            es.setEb(eb);
            es.start();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }   
}

如果您是初次使用spring mvc,请尝试使用一些简单的spring hello world example来理解基本的