首页 > 代码库 > Servlet实战(一)---账户登录

Servlet实战(一)---账户登录

Servlet学习入门的第一个例子

环境 MyEclipse10.0+Tomcat7.0+Postgresql9.1


效果

                           

代码:

LoginServlet.java

<pre name="code" class="java">import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
/*
 * Servlet for Login
 * @zm   2014-7-31
 */
@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet{
private String url;
private String user;
private String password;
	public void init()throws ServletException{
		String driverClass = "org.postgresql.Driver";
		url = "jdbc:postgresql://localhost:5432/student";
		user = "postgres";            //默认用户名
		password = "******";          //数据库密码
		try{
			Class.forName(driverClass);
		}
		catch(ClassNotFoundException ce){
		    throw new UnavailableException("加载数据库驱动失败!");
		}
	}
	public void doGet(HttpServletRequest req,HttpServletResponse resp){
		resp.setContentType("text/html;charset=gb2312");
		String name = req.getParameter("name");
		String id = req.getParameter("id");
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
			String sql = "select * from students where id = "+"'"+id+"'"+"and name ="+"'"+name+"'";
			rs = stmt.executeQuery(sql);
			if(rs.next()){
				PrintWriter out = resp.getWriter();
				out.println("Welcome : "+name);
			}else{PrintWriter out = resp.getWriter();
			      out.println("姓名或id输入错误!");}
		}catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(stmt!=null){
				try{stmt.close();}
				catch(SQLException se){se.printStackTrace();}
				stmt = null;
			}
			if(conn!=null){
				try{conn.close();}
				catch(SQLException se){se.printStackTrace();}
				conn = null;
			}
		}
	}

	public void doPost(HttpServletRequest req,HttpServletResponse resp){
		doGet(req,resp);
	}
}


SignUp.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/*
 * Servlet for 用户注册
 * @zm  2014-7-31
 */
@SuppressWarnings("serial")
public class SignUpServlet extends HttpServlet{
private String url;
private String user;
private String password;
//加载数据库
	public void init()throws ServletException{
		String driverClass = "org.postgresql.Driver";
		url = "jdbc:postgresql://localhost:5432/student";
		user = "postgres";
		password = "*******";
		try{
			Class.forName(driverClass);
		}
		catch(ClassNotFoundException ce){
		    throw new UnavailableException("加载数据库驱动失败!");
		}
	}
	public void doGet(HttpServletRequest req,HttpServletResponse resp){
		resp.setContentType("text/html;charset=gb2312");
		String name = req.getParameter("name");
		String id = req.getParameter("id");
		Connection conn = null;
		Statement stmt = null;
		try{
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
			String sql = "insert into students (id,name) values ('"+id+"','"+name+"')";
			stmt.executeUpdate(sql);
			resp.sendRedirect("Login.html");
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		finally{
			if(stmt!=null){
				try{stmt.close();}
				catch(SQLException se){se.printStackTrace();}
				stmt = null;
			}
			if(conn!=null){
				try{conn.close();}
				catch(SQLException se){se.printStackTrace();}
				conn = null;
			}
		}
	}

	public void doPost(HttpServletRequest req,HttpServletResponse resp){
		doGet(req,resp);
	}
}

登陆界面Login.html

<html>
  <head>
    <title>ZM的登陆网页!</title>
  </head>
  
  <body>
    <form action="Login" method="post"> 
  <table>
  <tr>
     <td>请输入id: </td>
     <td><input type="password" name="id"></td>
  </tr> 
  <tr>
     <td>请输入用户名: </td>
     <td><input type="text" name="name"></td>
  </tr>  
  <tr>
     <td><input type="reset" name="重填"> </td>
     <td><input type="submit" name="登录"></td>
     <td><input type="button" value=http://www.mamicode.com/"注册" onclick="javascrtpt:window.location.href='SignUp.html'">>
注册界面SignUp.html

<html>
  <head>
    <title>用户注册</title>
  </head>
  
  <body>
    <form action="SignUp" method="post"> 
  <table>
  <tr>
     <td>请输入id: </td>
     <td><input type="password" name="id"></td>
  </tr> 
  <tr>
     <td>请输入用户名: </td>
     <td><input type="text" name="name"></td>
  </tr>  
  <tr>
     <td><input type="reset" name="重填"> </td>
     <td><input type="submit" name="注册"></td>
  </tr> 
  </table>
    </form>
  </body>
</html>

部署文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <servlet>
      <servlet-name>ZM</servlet-name>
      <servlet-class>LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ZM</servlet-name>
      <url-pattern>/Login</url-pattern>
  </servlet-mapping>
  <servlet>
      <servlet-name>ZM1</servlet-name>
      <servlet-class>SignUpServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ZM1</servlet-name>
      <url-pattern>/SignUp</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

1.访问数据库注意加载JDBC驱动程序  postgresql-9.1-901-1.jdbc4.jar

2.数据库创建连接Connection conn = DriverManager.getConnection(url, user, password);

  URL=协议名+IP地址(域名)+端口+数据库的名称

  jdbc:postgresql://localhost:5432/student
  用户名和密码是指登陆数据库时所使用的用户名和密码。

3.数据库注意打开服务。

4.入门不宜直接使用myEclipse部署,自己手动部署了解过程才好。