Java 使用MyEclipse创建一个简单的Servlet demo

一、使用MyEclipse创建一个Web项目

File ---- New ---- Web Project

Java 使用MyEclipse创建一个简单的Servlet demo_第1张图片

创建完成后,目录结构如下:

Java 使用MyEclipse创建一个简单的Servlet demo_第2张图片

二、在src(源码)目录下创建一个package

Java 使用MyEclipse创建一个简单的Servlet demo_第3张图片

三、在创建的这个package下创建Servlet

鼠标右键点击这个package --- new --- Servlet

Java 使用MyEclipse创建一个简单的Servlet demo_第4张图片

Java 使用MyEclipse创建一个简单的Servlet demo_第5张图片

打开这个创建的Servlet文件:MyServlet.java,可以看到里面生成的Servlet常见的方法

package MyFirstServlet;

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;

public class MyServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public MyServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" A Servlet"); out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" "); out.println(""); out.flush(); out.close(); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" A Servlet"); out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" "); out.println(""); out.flush(); out.close(); } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }

这里只需要doGet()和doPost()方法,所以,最后代码为:

package MyFirstServlet;

import java.io.IOException;

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

public class MyServlet extends HttpServlet {


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


	}


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


	}



}

四、配置Servlet配置文件(web.xml)

在创建的web工程下(Web6)---- WebRoot ---- web.xml

Java 使用MyEclipse创建一个简单的Servlet demo_第6张图片

Servlet一个大致的数据流程是:首先客户在浏览器输入一串地址 ---- 然后根据地址找到web.xml中配置的url-pattern --- 然后根据servlet-nam 找到 servlet-class。

五、创建一个login.html页面

在WebRoot下创建一个login.html文件,代码如下:



    用户登录


登录

账号:
密码:

 

Java 使用MyEclipse创建一个简单的Servlet demo_第7张图片

六、导入相关的jar包

因为这个demo是模拟用户登录,首先需要用户输入用户名和密码,然后再和数据库里的用户名和密码进行比较,相同就可以登录,不相同就登录失败。所以,这里需要用到mysql数据库,因此,需要导入mysql数据库相关的包。

c3p0-0.9.1.2.jar   mysql-connector-java-5.1.39-bin.jar  commons-dbutils-1.4.jar

将已准备号的jar包复制 --- 粘贴到 Web6 --- WebRoot --- WEB-INF --- lib下,然后鼠标右键点击这几个包 --- Build Path --- Add to Build Path 。

 

七、导入已封装好的DataSourceUtils.java工具类

在工程(Web6) --- src --- 创建package:utils ---- 将拷贝的DataSourceUtils.java粘贴在package中。内容如下:

package utils;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

	private static DataSource dataSource = new ComboPooledDataSource();

	private static ThreadLocal tl = new ThreadLocal();

	// 直接可以获取一个连接池
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}

	// 获取连接对象
	public static Connection getCurrentConnection() throws SQLException {

		Connection con = tl.get();
		if (con == null) {
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}

	// 开启事务
	public static void startTransaction() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.setAutoCommit(false);
		}
	}

	// 事务回滚
	public static void rollback() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.rollback();
		}
	}

	// 提交并且 关闭资源及从ThreadLocall中释放
	public static void commitAndRelease() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.commit(); // 事务提交
			con.close();// 关闭资源
			tl.remove();// 从线程绑定中移除
		}
	}

	// 关闭资源方法
	public static void closeConnection() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.close();
		}
	}

	public static void closeStatement(Statement st) throws SQLException {
		if (st != null) {
			st.close();
		}
	}

	public static void closeResultSet(ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
	}

}

八、导入c3p0-config.xml文件

在src的根目录下导入c3p0-config.xml文件,并修改文件,修改后内容如下:



	
		root
		root
		com.mysql.jdbc.Driver
		jdbc:mysql:///web?useSSL=false
	 
 

九、创建数据库实体模型

在src下创建一个包:domain --- 创建类:Test.java(创建数据表实体模型)  ,并生成set和get方法,另外生成toString方法内容如下:

package domain;

public class Test {
	private int id;
	private String username;
	private String password;
	private String email;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "Test [id=" + id + ", username=" + username + ", password="
				+ password + ", email=" + email + "]";
	}

}

 

十、重写MyServlet.java中的方法

package MyFirstServlet;

import java.io.IOException;
import java.sql.SQLException;

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

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import domain.Test;


import utils.DataSourceUtils;



public class MyServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//1、获得用户名和密码
		//username = zhangsan&password=123
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//2、从数据库中验证该用户名和密码是否正确
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		//执行SQL语句
		String sql = "select * from test where username = ? and password = ?";//传递可变参数username和password
		Test test = null;
		try {
			test = runner.query(sql, new BeanHandler(Test.class), username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//3、根据返回的结果给用户不同的显示信息
		if(test!=null){
			//用户登录成功
			response.getWriter().write(test.toString());
			response.getWriter().write(test.toString());
			//System.out.println("xxxxxx");
		}else{
			//用户登录失败
			response.getWriter().write("Login False!");
		}


	}


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


	}



}

十一、测试结果

启动Tomcat服务,浏览器输入:http://localhost:8080/Web6/login.html 然后输入用户名/密码登录,成功获取到toString方法的返回值。

 

 

你可能感兴趣的:(Java 使用MyEclipse创建一个简单的Servlet demo)