在早期还没提出MVC架构理念,工程师们只是单纯为了使代码的逻辑结构看上去清晰,以及为了编写的效率,引入了JSP文件,JSP的本质依旧是将JSP文件编译为Servlet类,然后再动态加载程序代码。
接下来的代码都采用servlet规范来写,将不再模拟servlet类。
创建第一个JavaWeb应用
servlet规范规定,JavaWeb应用必须采用固定的目录结构
先不使用IDE自己手动编写一个简单的JavaWeb应用
以下是一个最简单的JavaWeb目录结构:
1.新建一个login.htm文件:
<html>
<head>
<title>helloapp</title>
</head>
<body>
<form name="loginForm" method="POST" action="dispatcher">
<table>
<tr>
<td><div align="right">User Name:</div></td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><div align="right">Password:</div></td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
<td><input type="reset" name="reset" value="reset"></td>
</tr>
</table>
</form>
</body>
</html>
文件中表单通过action="dispatcher"指定将要跳转到的uri地址:http://182.61.35.14:8000/helloapp/dispatcher
2.新建一个DispatcherServlet类:
package mypack;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class DispatcherServlet extends GenericServlet {
private String target = "/hello.jsp";
//响应客户端请求
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
request.setAttribute("USER", username);
request.setAttribute("PASSWORD", password);
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(target);
dispatcher.forward(request, response);
}
}
通过RequestDispatcher dispatcher = context.getRequestDispatcher("/hello.jsp");将请求转交给hello.jsp文件处理
//编译命令为
javac -classpath /usr/local/tomcat/lib/servlet-api.jar -sourcepath src -d WEB-INF/classes/ src/mypack/DispatcherServlet.java
4.新建web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>mypack.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/dispatcher</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.htm</welcome-file>
</welcome-file-list>
</web-app>
在web.xml中配置DispatcherServlet类与uri的映射,让客户端能够找到它。
4.新建hello.jsp文件:
<html>
<head>
<title>helloapp</title>
</head>
<body>
<b>Hello: <%= request.getAttribute("USER") %></b>
</body>
</html>
通过内嵌的java语句request.getAttribute("USER");获得动态数据,并返回到浏览器显示。
//编译命令为
忘了,网上找一下