上一篇我们搭建了一个简单的Web应用:http://www.cnblogs.com/lay2017/p/8468515.html
本文将基于上一篇搭建的应用,编写一些内容
- 编写Servlet类
- 编写JSP页面
首先我们添加目录结构如下:
这里在java类目录下添加了cn.lay目录,并创建了HelloServlet的Java文件
在webapp/WEB-INF目录下创建了jsp目录,并创建了hello.jsp文件
HelloServlet.java
package cn.lay;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;/** * 创建一个Servlet * Created by lay on 25/02/2018. *//** * 注解配置请求路径,对外发布Servlet服务 */@WebServlet("/hello")/** * 继承HttpServlet让它成为一个Servlet */public class HelloServlet extends HttpServlet { ???/** ????* 覆盖doGet方法,用于接收GET请求 ????* @param req ????* @param resp ????* @throws ServletException ????* @throws IOException ????*/ ???@Override ???protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ???????DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ???????// 获取系统时间 ???????String currentTime = dateFormat.format(new Date()); ???????// 放入request对象 ???????req.setAttribute("currentTime", currentTime); ???????// 转发到hello.jsp ???????req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req, resp); ???}}
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> ???<title>Hello</title></head><body><h1>Hello!</h1><%--使用JSTL表达式来获取从HelloServlet里传递过来的currentTime请求属性--%><h2>当前时间:${currentTime}</h2></body></html>
至此,我们编写完了代码,下一篇,我们将让这个Web应用跑起来
编写一个简单的Web应用
原文地址:https://www.cnblogs.com/lay2017/p/8468519.html