servelt相关的一些例子

总的项目结构图如下:

servelt相关的一些例子

配置文件web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	
	
	<!-- 配置servlet -->
	<servlet>
	<!--servlet名称,必须唯一-->
		<servlet-name>Firstservlet</servlet-name>
		<!--对应的servlet类-->
		<servlet-class>firstservlet.FirstServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>Firstservlet</servlet-name>
		<!--访问的URL地址: http://localhost:8080/servlet/firstservlet-->
		<!-- 对应index.jsp中的表单动作<form action="firstservlet">  -->
		<url-pattern>/firstservlet</url-pattern>
	</servlet-mapping>

	<!-- 配置servlet -->
	<servlet>
		<servlet-name>testservlet</servlet-name>
		<servlet-class>servletAPI.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>testservlet</servlet-name>
		<url-pattern>/testservlet</url-pattern>
	</servlet-mapping>
	
	<!-- 配置servlet -->
	<servlet>
		<description>
			This is the description of my J2EE component
		</description>
		<display-name>
			This is the display name of my J2EE component
		</display-name>
		<servlet-name>initservlet</servlet-name>
		<servlet-class>servletAPI.InitServlet</servlet-class>
		<!-- 连接数据库的初始化参数 -->
		<init-param>
			<param-name>driver</param-name>
			<param-value>
				com.microsoft.jdbc.sqlserver.SQLServerDriver
			</param-value>
		</init-param>
		<init-param>
			<param-name>URL</param-name>
			<param-value>
				jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login
			</param-value>
		</init-param>
		<init-param>
			<param-name>username</param-name>
			<param-value>sa</param-value>
		</init-param>
		<init-param>
			<param-name>password</param-name>
			<param-value>sa</param-value>
		</init-param>
	</servlet>
 
 <!-- 建立servlet自动生成的 -->
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShowCart</servlet-name>
    <servlet-class>shoppingCart.ShowCart</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShortMessage</servlet-name>
    <servlet-class>ch05shortmessage.ShortMessage</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ProductList</servlet-name>
    <servlet-class>ch06servletJDBC.ProductList</servlet-class>
  </servlet>
	<servlet-mapping>
		<servlet-name>initservlet</servlet-name>
		<url-pattern>/initservlet</url-pattern>
	</servlet-mapping>
  <servlet-mapping>
  
    <servlet-name>ShowCart</servlet-name>
    <url-pattern>/ShowCart</url-pattern>
    
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShortMessage</servlet-name>
    <url-pattern>/shortmessage</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ProductList</servlet-name>
    <url-pattern>/productlist</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
  	<welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>


1,第一个servlet例子
package firstservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FirstServlet extends HttpServlet {
	
	private int stringtoint(String str)throws NumberFormatException{
		int i = Integer.parseInt(str);
		return i;
	}

	//覆盖父类的方法doGet,doPost,  doPost不会显示传递的参数
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		
		String str;
		int inputNum;
		String outputstring;
		
		
		response.setContentType("text/html;charset=gb2312");
		PrintWriter out = response.getWriter();
		
		
		Cookie cookies[]=request.getCookies();
		
		//输出网页
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println("<h1>servlet例子</h1>");
		
		if((cookies==null)||(cookies.length==0)){
			out.println("没有Cookies!");
		}
		else{
			out.println("<center><h1>响应消息中的Cookies的信息</h1>");
			out.println("<table border=2>");
			out.println("<tr><th>Name</th><th>value</th><th>comment</th><th>max age</th></tr>");//表头
			for(int i=0;i<cookies.length;i++){
				Cookie c = cookies[i];
				out.println("<tr><td>"+c.getName()+"</td><td>"+c.getValue()+"</td><td>"+c.getComment()+"</td><td>"+c.getMaxAge()+"</td><td>");
			}//maxage为cookie的过期时间,过期的cookie就不会往服务器端发送了
			
			out.println("</table></center>");
		}
		
		out.println("<h1>httpsession接口</h1>");
		HttpSession session = request.getSession();
		long time = session.getCreationTime();
		Date createDate = new Date(time);
		out.println("seesion创建的时间:"+createDate+"<br>");
		out.println("seesion的ID:"+session.getId()+"<br>");
		
		//第一次执行为null,后面的为12,重启Tomcat后为null,或者关闭浏览器重启为null
		
		out.println("session的getValue:"+session.getValue("item1")+"<br>"); 
		Integer sessionItem = new Integer(12);
		session.putValue("item1", sessionItem); //保存到session中
		
		
		str = request.getParameter("txtInputNum"); //取得请求参数,txtInputNum为index.jsp中设置的参数名称
		
		try {
			inputNum = stringtoint(str);
			outputstring = "你输入的数字为:"+inputNum;
		} catch (NumberFormatException e) {
			outputstring = "对不起,输入不是数字";
		
		}
		out.println("<h1>表单传递参数</h1>");
		out.println(outputstring);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
		
		
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		doGet(request,response);
	}
}


index.jsp

<%@ page language="java" contentType = "text/html;charset=gb2312"%>
<%
//String path = request.getContextPath();
//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <!--   <base href="<%//=basePath
   %>">  -->
    
    <title>servlet处理异常</title>
  </head>
  <body>
   <form action="firstservlet"> 
			请输入一个数字: 
			<input type="text" name="txtInputNum" />
			<input type="submit" value="submit" />
		</form> 
  </body>
</html>

执行结果:



servelt相关的一些例子


如果输入不是数字,最后一行显示:        对不起,输入不是数字

2,购物车的例子,用session保存信息
package shoppingCart;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShowCart extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

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

		response.setContentType("text/html;charset=gb2312"); // 设置返回的MIME类型,只能设置一次,为纯html文件
		PrintWriter out = response.getWriter();
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>购物车实例</TITLE></HEAD>");
		out.println("  <BODY>");

		String[] items = { "电视机", "电冰箱", "电脑" };
		HttpSession session = request.getSession();     //取得会话
		Integer itemCount = (Integer) session.getValue("itemCount");
		if (itemCount == null) {
			itemCount = new Integer(0);
		}

		String[] itemSelected;
		String itemName;
		itemSelected = request.getParameterValues("item");// 取得表单中的checkbox的值
		if (itemSelected != null) {
			for (int i = 0; i < itemSelected.length; i++) {
				itemName = itemSelected[i]; // 对应于checkbox的value
				itemCount = new Integer(itemCount.intValue() + 1);
				session.putValue("Item" + itemCount, itemName); // 商品名称为ItemX
				session.putValue("itemCount", itemCount); // 商品数量保存到session中
			}
		}

		out.println("<h3>购物篮中的物品:</h3>");
		for (int i = 1; i <= itemCount.intValue(); i++) {
			String item = (String) session.getValue("Item" + i); // 取出商品名称在checkbox对应的数值
			out.println(items[Integer.parseInt(item)]);
			out.println("<br>");
		}
		out.println("<hr>");

		out.println("<a href='showcart.jsp'>继续购物</a>");

		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}


showcart.jsp
<%@ page language="java" contentType = "text/html;charset=gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <title>购物车</title>
  </head>
  <body>
   <form action="ShowCart" method="post"> 
			选购商品:<br> 
			<input type="checkbox" name="item"  value="0" />
			第一种:电视机<br>
			<input type="checkbox" name="item"  value="1" />
			第二种:电冰箱<br>
			<input type="checkbox" name="item"  value="2" />
			第三种:电脑<br>
			<hr>
			<input type="submit" name ="addtocart" value="加入购物篮" />
		</form> 
  </body>
</html>

执行结果:

servelt相关的一些例子
选择后点击“加入购物篮”

servelt相关的一些例子
如果点击链接“继续购物”,返回showcart.jsp页面,选择“电脑”加入购物车

servelt相关的一些例子

3,servlet通过jdbc链接数据库
package ch06servletJDBC;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class ProductList extends HttpServlet {

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

	private boolean query(String driverName, String connectionURL, Properties pro,
			String sql, PrintWriter out) {

		boolean rc = true;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		long startMS = System.currentTimeMillis();
		int rowCount = 0;

		try {
			System.out.println("begin to load class");
			
			Class.forName(driverName).newInstance();
			conn = DriverManager.getConnection(connectionURL, pro);
			System.out.println(conn==null);
			
			stmt = conn.createStatement();
			
			System.out.println(stmt==null);
			rs = stmt.executeQuery(sql);

			rowCount = formatTable(rs, out);
			

		} catch (Exception e) {
			e.printStackTrace();
			rc = false;
			return false;
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {

			}
		}

		if (rc) {
			long elapsed = System.currentTimeMillis() - startMS;
			out.println("<br>共" + rowCount + "记录,耗时" + elapsed + "毫秒!");
			
		}
		return true;
	}

	private int formatTable(ResultSet rs, PrintWriter out) throws SQLException {
		int rowCount = 0;
		out.println("<center><table border=2>");

		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		out.println("<tr>");

		for (int i = 0; i < columnCount; i++) {
			out.println("<th>" + rsmd.getColumnLabel(i + 1) + "</th>");// 字段名作为表头
		}
		out.println("</tr>");
		
		while(rs.next()){
			rowCount++;
			out.println("<tr>");
			for (int i = 0; i < columnCount; i++) {
				out.println("<td>" + rs.getString(i+1) + "</td>");// 字段名作为表头
			}
			
			
			out.println("</tr>");
		}
		
		
		out.println("</table></center>");

		return rowCount;
	}
	
	public void init(ServletConfig cfg) throws ServletException{
		super.init(cfg);
	}
	
	public void destroy(){
		super.destroy();
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException{
		response.setContentType("text/html;charset=gb2312");
//		PrintWriter out = response.getWriter();
		
		PrintWriter out = new PrintWriter(response.getOutputStream());
		
		
		Properties pro = new Properties(); // 用属性的数据结构存储用户名和密码
		pro.put("user", "sa");
		pro.put("password", "sa");
		String sql;
		sql = "select * from productlist"; //数据库中的productlist表格
		String connectionURL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login";

		out.println("<HTML>");
		out.println("  <HEAD><TITLE>产品列表</TITLE></HEAD>");
		out.println("<h1>产品信息列表</h1>");
		out.println("  <BODY>");
//		需要有mssql的三个数据库驱动jar包
		boolean r = query("com.microsoft.jdbc.sqlserver.SQLServerDriver", connectionURL,
				pro, sql, out);
		out.println("查询结果:"+r);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	
}

结果:
servelt相关的一些例子
4,把链接数据库的参数配置在web.xml中的servlet初始参数中,见web.xml
package servletAPI;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

public class InitServlet extends HttpServlet {

	private String driver = "";
	private String URL = "";
	private String username = "";
	private String password = "";

//	获取web.xml中的init-param参数
	public void init() throws ServletException { //自动执行
		driver = getInitParameter("driver"); //参数"driver" 为param-name,返回的是param-value
		URL = getInitParameter("URL");
		username = getInitParameter("username");
		password = getInitParameter("password");
	}
//获得数据库连接的方法
	public Connection getConnection() {
		Connection con = null;
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(URL, username, password);
			return con;
		} catch (Exception e) {
		}
		return con;
	}
//通过doGet()方法实现数据查询功能
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=gb2312");
		PrintWriter out = response.getWriter();
		Connection con = this.getConnection();
		try {
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select * from Loginuser");
			while (rs.next()) {
				out.print(rs.getString("username"));
				out.print("&nbsp;&nbsp;&nbsp;&nbsp;");
				out.print(rs.getString("password"));
				out.print("&nbsp;&nbsp;&nbsp;&nbsp;");
				out.print(rs.getString("gender"));
				out.print("&nbsp;&nbsp;&nbsp;&nbsp;");
				out.print(rs.getInt("age"));
				out.print("&nbsp;&nbsp;&nbsp;&nbsp;");
				out.print(rs.getDate("logintime"));
				out.print("<br>");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

结果就是显示数据库中Loginuser表格的内容

源码见附件

你可能感兴趣的:(java,sql,jsp,jdbc,servlet)