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

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

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

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

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

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

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

打开这个创建的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. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @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

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

五、创建一个login.html页面

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

<html>
<head>
    <title>用户登录</title>
</head>
<body>
<h2 style="color: red">登录</h2>
<form action="/Web6/myServlet" method="post">
    账号:<input type="text"  name="name"><br/>
    密码:<input type="password"  name="pwd"><br/>
    <input type="submit" value="登陆"><br/>
</form>
</body>
</html>

 

六、导入相关的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<Connection> tl = new ThreadLocal<Connection>();

	// 直接可以获取一个连接池
	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文件,并修改文件,修改后内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">root</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///web?useSSL=false</property>
	</default-config> 
</c3p0-config> 

九、创建数据库实体模型

在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>(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方法的返回值。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值