Java Servlet的Java序列化类对象

时间:2017-05-05 21:14:00

标签: java tomcat servlets serialization

我目前有一个类项目,我需要在Tomcat上部署一个简单的银行Web应用程序。在打开应用程序时,我们应该带到一个HTML文件,其中包含一个表单,供用户提交用户名或让他们创建一个新帐户。这必须通过使用Java servlet完成,其中映射在web.xml中完成。

我遇到问题的部分是可序列化对象。在我的例子中,可序列化的对象类是Accounts。在servlet中,我需要知道如何操作它们(创建,存储,删除和检索)。

这是我引用的Account.java。 Account.java

//Class from which objects will be created 
//and then passed as arguments.

import java.io.Serializable;

public class Account implements Serializable
{
        private int acctNum;
        private String surname;
        private String firstNames;
        private double balance;

        public Account(int acctNo, String sname, String fnames, double bal)
        {
                acctNum = acctNo;
                surname = sname;
                firstNames = fnames;
                balance = bal;
        }

        public int getAcctNum()
        {
                return acctNum;
        }

        public String getName()
        {
                return (firstNames + " " + surname);
        }

        public double getBalance()
        {
                return balance;
        }

        public double withdraw(double amount)
        {
                if (amount <= balance)
                        return amount;
                else
                        return 0;
        }

        public void deposit(double amount)
        {
                if (amount > 0)
                        balance += amount;
        }
}

这是我将要使用的Java servlet的示例。 FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet
{
    public void doPost(HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException,ServletException
    {
        response.setContentType("text/HTML");

        String user = request.getParameter("usrname");
        PrintWriter out = response.getWriter();
        /*
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>Simple Servlet</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<BR><BR><BR>");
        out.println("<CENTER><H1> A Simple Servlet </H1></CENTER>");
        out.println("</BODY>");
        out.println("</HTML>");
        */
        out.print("<html><head><title>Simple Servlet</title></head><body><br><br><br><CENTER><H1> A Simple Servlet </H1><br><br>Username: "+ user +"</CENTER></body></html>");
        out.flush();
    }
}

0 个答案:

没有答案