日期:2014-05-16  浏览次数:20359 次

jsp+Servlet学习(一)简单实例

现在以实现功能效果为目的,至于里面的原理,底层的细节暂不考虑,先学会咋么使用。细节,理论方面的在以后慢慢领悟。

直接上代码。这是一个jsp+servlet的简单实例。项目结构如下:

①开发工具eclipse,新建一个动态web项目,配置服务器。

②创建自定义的servlet类,这里创建TestServlet,代码如下:

public class TestServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("get into testServlet doPost method.");
		String name = req.getParameter("name");
		String[] sports = req.getParameterValues("sport");
		System.out.println("name:"+name);
		System.out.print("sport:");
		for(String s : sports){
			System.out.print(s+" ");
		}
		System.out.println();
		System.out.println("---------------");
		
	}
}

③配置web.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
	<servlet>
		<servlet-name>testServlet</servlet-name>
		<servlet-class>com.zhongqian.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>testServlet</servlet-name>
		<url-pattern>/testServlet.do</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

④创建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>fristPage</title>
</head>
<body>
<form method="post" action="testServlet.do">
	name:<input type="text" name="name"/><br/>
	favorite sport:<input type="checkbox" name="sport" value="basketball"/>basketball
	               <input type="checkbox" name="sport" value="football"/>football
	              <br/>
	<input type="submit" value="submit"/>
</form>
</body>
</html>

运行效果如下:

点击提交后,在控制台打印:

ok,第一个实例运行成功。~