创建Java Web应用
Java Web应用种可以包含HTML文档 Servlet JSP和相关的Java类等。为了让Servlet容器能够顺利地找到Java Web应用中的各个组件,Servlet规范规定,Java Web应用必须采用固定的目录结构,每种类型的组件在Web应用中都有固定的存放目录。Java Web的配置信息需要放在web-INF/web.xml文件中。
假设有一个叫helloapp的Java Web应用。(浏览器不能直接访问WEB-INF目录下的文件)
helloapp应用的完整目录结构
HTML文件
<html>
<head>
<title>
hello
</title>
</head>
<body>
<form name="loginForm" method="post" action="dispatch">
username : <input type="text" name="username"><br/>
password : <input type="password" name="password"><br/>
<input type="submit" value="submit" name="submit">
<input type="reset" value="reset" name="reset">
</form>
</body>
</html>
Servlet类
public class DispacherServlet extends GenericServlet {
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
//获取属性
String username = servletRequest.getParameter("username");
String password = servletRequest.getParameter("password");
//添加属性
servletRequest.setAttribute("U",username);
servletRequest.setAttribute("P",password);
//转发
ServletContext servletContext = getServletContext();
servletContext.getRequestDispatcher("/hello.jsp").forward(servletRequest,servletResponse);
}
}
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_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>/login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>com.sea.DispacherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/dispatch</url-pattern>
</servlet-mapping>
</web-app>
JSP
<html>
<head>
<title>hello</title>
</head>
<body>
Hello <%= request.getAttribute("U")%><br/>
password ${P}
</body>
</html>