0 votes
1 view
in Java by (9.2k points)

Below is my servlets code snippet to submit a simple form: 

@WebServlet("/Main")

public class Main extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**

     * @see HttpServlet#HttpServlet()

     */

    public Main() {

        super();

        // TODO Auto-generated constructor stub

    }

    public String date;

    public String getDate() {

        return date;

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        // response.getWriter().append("Served at: ").append(request.getContextPath());

        System.out.println("\n-----------------------------------------\nBegin doGet");

        System.out.println("Date " + date);

        HttpSession session = request.getSession();

        // Date - Get today date to fill the welcome form

        Date dNow = new Date();

        SimpleDateFormat ft = new SimpleDateFormat("dd MMMM yyyy");

        date = (String) ft.format(dNow);

        session.setAttribute("date", date);

        // Go to main page

        this.getServletContext().getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);

        System.out.println("\nEnd doGet\n-----------------------------------------");

    }

    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        System.out.println("\n-----------------------------------------\nBegin Post Session");

        System.out.println("Date " + date);

        HttpSession session = request.getSession();

        this.getServletContext().getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);

        System.out.println("\nEnd doPost\n-----------------------------------------");

    }

}

I don’t know how to display today's date in the form. When I tried the below code, 

<p>${date}</p>

I get a blank paragraph and this code ‘<%= session.getAttribute("date");%>’ throws an execution error on the server side. Can anyone tell me what I’m doing wrong? 

1 Answer

0 votes
by (19k points)

If you want to access access session attributes in JSP pages, you have to implement the below code: 

Use ${sessionScope.date} instead of ${date} in <p> tag.

Check if JSP allows session access by this command ‘<%@ page session="true" %>’ at the top of the page.

Interested in Java? Check out this Java tutorial by Intellipaat.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...