JSP+Servlet的简单示例

时间:2022-02-10 17:18:06

1. 在Eclipse新建一个Dynamic Web Project项目。

2. 编写Servlet,并用Annotation配置。

需要注意,用Annotation配置Servlet,在web.xml中要将根元素<web-app ...>中的metadata-complete属性设置成false,或是不配置web.xml文件。

package com.huey.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Annotation 配置Servlet
// name指定了Servlet的名字
// urlPatterns指定了Servlet处理的URL
@WebServlet(name="helloServlet", urlPatterns="hello")
public class HelloServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = -6861972655291111434L;

public HelloServlet() {
super();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

String name = request.getParameter("name");
if (name.equals("huey")) {
// 请求转发,使用getRequestDispatcher(path)方法时,path必须是以/开头
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
} else {
// 请求重定向
response.sendRedirect("sorry.jsp");
}

}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

}

}

3. 也可以在web.xml中配置Servlet

<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.huey.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

4. 编写jsp文件,一下文件都放在WebContent目录下

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello</title>
</head>
<body>
<form action="hello" method="post">
Name: <input type="text" name="name"/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
welcome.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
Hello, ${param.name}!<br/>
</body>
</html>
sorry.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sorry</title>
</head>
<body>
Sorry!
</body>
</html>