Servlet3.0 serlvet ,annotiation

package com.lee;

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

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

@WebServlet(name="paramServlet"
		,urlPatterns="/paramServlet"
		,initParams={
		  @WebInitParam(name="driver",value="com.mysql.jdbc.Driver"),
		  @WebInitParam(name="url",value="jdbc:mysql://127.0.0.1:3306/mysql"),
		  @WebInitParam(name="user",value="root"),
		  @WebInitParam(name="pass",value="123456"),
		}
		)
public class ParamServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		Connection conn=null;
		ResultSet rs=null;
		try {
			ServletConfig config=getServletConfig();
			String driver=config.getInitParameter("driver");
			String url=config.getInitParameter("url");
			String user=config.getInitParameter("user");
			String pass=config.getInitParameter("password");
			
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			Statement stmt=conn.createStatement();
			rs=stmt.executeQuery("select * from my_test");
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null)
					rs.close();
				if(conn!=null)
					conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			
		}
		
		
		
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
	}

	
	
}


package com.lee;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;


/*
 *web.xml
 * <servlet>
 		<servlet-name>timerServlet</servlet-name>
 		<servlet-class>com.lee.TimerServlet</servlet-class>
 		<load-on-startup>1</load-on-startup>
  </servlet>
 * 
 */
@WebServlet(loadOnStartup=1)
public class TimerSerlvet extends HttpServlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		
		Timer t=new Timer();
		t.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println(new Date());
			}
		}, 1000);
		
	}

	
}

你可能感兴趣的:(servlet)