helloapp的实践操作
1:下载JDK (安装啥都不需要改)
- 百度jdk下载
- jdk包括了jre所以jdk要好些,
- 安装过程一直确定即可
- 添加JAVA_HOME,指向JDK目录
- 添加PATH,指向JDK的bin目录
2:下载TOMCAT
- 下载zip然后解压即可
- 添加CATALINA_HOME,指向安装目录
3:在TOMCAT的webapps里面建立helloapp目录,里面具体包括
- /src/mypack/DispatcherServlet.java
- /WEB-INF/web.xml
- /WEB-INF/classes/mypack/DispatcherServlet.class
- /hello.jsp
- /login.htm
4 : 为避免有的小伙伴没有代码,贴上代码
//DispatcherServlet.java 文件
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
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);
}
}
hello.jsp文件如下:
<html>
<head>
<title>helloapp</title>
</head>
<body>
<b>Hello: <%=request.getAttribute("USER") %></b>
</body>
</html>
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>
web.xml
<web-app 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_4_0.xsd"
version="4.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<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>
</web-app>
5: 前面提到的DispatcherServlet.class是由DispatcherServlet.java编译而成。cmd转到helloapp的目录
javac -classpatch servlet-api.jar的位置 -sourcepath src -d WEB-INF\classes src\mypack\DispatcherServerlet.java
其中servlet-api.jar的位置在tomcat安装目录的lib里面
最后进行测试
tomcat的启动:点击bin下面的startup.bat
浏览器访问:http:localhost:8080/helloapp/login.htm
输入任意用户名kkkk“kkkk”与密码点击submit
如果出现hello:kkkk就代表成功了。