运行环境:
引用
JDK1.5
Tomcat5.5
MyEclips5.5.1 GA
SqlServer2000
windows2003
1.在SqlServer下的查询分析器中新建表:create table dbuser(
userId int identity(1,1) primary key not null,
userName varchar(50),
userPasswd varchar(50))
2.在MyEclipse中新建Web工程,并创建包结构。
3.编写登陆界面。
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
<style type="text/css">
body{
color : #000 ;
font-size : 12px ;
margin : 0px auto ;
}
</style>
<script type="text/javascript">
function check(form){
//document.forms.form1.username.value取得form1中Username的值 并判断是否为空
if(document.forms.form1.username.value==""){
//如果 为""则弹出提示
alert("pls input username");
//将输入焦点定位到没有输入的地方
document.forms.form1.username.focus();
//返回错误
return false;
}
if(document.forms.form1.password.value==""){
alert("pls input password");
document.forms.form1.password.focus();
return false;
}
}
</script>
</head>
<body>
<form action="LoginServlet" method="post" name="form1">
<table border="1" cellspacing="1" cellpadding="1" bordercolor="silver" align="center">
<tr>
<td colspan="2" align="center" bgcolor="#e8e8e8">用户登陆</td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td><a href="rsg.jsp" >新用户注册</a></td>
<!-- onclick="return check(this) 调用上面的Script进行验证 -->
<td><input type="submit" name="submit" onclick="return check(this);"/><input type="reset" name="reset"/></td>
</tr>
</table>
</form>
</body>
</html>
3.编写工具类DBConn。
package utils;
import java.io.*;
import java.sql.*;
public class DBConn {
public static String driver;//定义驱动
public static String url;//定义URL
public static String user;//定义用户名
public static String password;//定义密码
public static Connection conn;//定义连接
public static Statement stmt;//定义STMT
public ResultSet rs;//定义结果集
//设置CONN
static{
try {
driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=qtliu";
user="sa";
password="sa";
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
System.out.println("-------连接成功------");
} catch(ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
System.err.println("db: " + classnotfoundexception.getMessage());
} catch(SQLException sqlexception) {
System.err.println("db.getconn(): " + sqlexception.getMessage());
}
}
//构造函数,默认加裁配置文件为jdbc.driver
public DBConn(){
this.conn=this.getConn();
}
//返回Conn
public Connection getConn(){
return this.conn;
}
//执行插入
public void doInsert(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeInset:" + sqlexception.getMessage());
}finally{
}
}
//执行删除
public void doDelete(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeDelete:" + sqlexception.getMessage());
}
}
//执行更新
public void doUpdate(String sql) {
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeUpdate:" + sqlexception.getMessage());
}
}
//查询结果集
public ResultSet doSelect(String sql) {
try {
conn=DriverManager.getConnection(url,user,password);
stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
System.out.println("取得结果集");
} catch(SQLException sqlexception) {
System.err.println("db.executeQuery: " + sqlexception.getMessage());
}
return rs;
}
/**
*关闭数据库结果集,数据库操作对象,数据库链接
@Function: Close all the statement and conn int this instance and close the parameter ResultSet
@Param: ResultSet
@Exception: SQLException,Exception
**/
public void close(ResultSet rs) throws SQLException, Exception {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
/**
*关闭数据库操作对象,数据库连接对象
* Close all the statement and conn int this instance
* @throws SQLException
* @throws Exception
*/
public void close() throws SQLException, Exception {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
//测试类
// public static void main(String []args){
// DBConn db=new DBConn();
// db.getConn();
// ResultSet rs=db.doSelect("select * from db_user where userName='admin'");
// try {
// while(rs.next()){
// System.out.println(rs.getInt(1));
// System.out.println(rs.getString(3));
//
// }
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
4.编写Servlet,LoginServlet.java。
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.CheckUser;
import beans.UserBean;
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7381169134016556647L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置HTTP响应的文档类型,此处为Text/html,如果更改为application\msword则设置为word文档格式
response.setContentType("text/html");
//设置响应所采用的编码方式
response.setCharacterEncoding("GB18030");
//取得参数username的值
String uname=request.getParameter("username");
String passwd=request.getParameter("password");
UserBean user=new UserBean();
user.setUsername(uname);
user.setPassword(passwd);
CheckUser cku=new CheckUser();
boolean bool=cku.checkUsre(user);
String forward;
if(bool){
forward="success.jsp";
}else{
forward="error.jsp";
}
RequestDispatcher rd=request.getRequestDispatcher(forward);
rd.forward(request,response);
}
}
5.在web.xml中配置Servlet。
引用
配置关键代码
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
本机上的整个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">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5.编写userBean。
package beans;
public class UserBean {
public String username;
public String password;
public UserBean() {
super();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
6.编写JavaBean CheckUser。
package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DBConn;
import utils.DBUtils;
import beans.UserBean;
public class CheckUser {
public boolean checkUsre(UserBean user){
if(user.username.equals("")||user.username!=null){
ResultSet rs=null;
DBConn db=new DBConn();
rs=db.doSelect("select * from db_user where userName='"+user.getUsername()+"'");
try {
if(rs.next()){
if(user.password.equals("")||user.password!=null){
rs=db.doSelect("select * from db_user where userPasswd="+user.password);
return true;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
}
7.编写错误页面及成功登陆页面。
error.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
Sorry!你的登陆信息不正确!系统无法让你登陆!<a href="login.jsp">点击返回</a>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<jsp:useBean id="user" class="beans.UserBean" scope="request"/>
<jsp:setProperty name="user" property="*"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<%
session.setAttribute("user",user);
String username=user.getUsername();
%>
<%=username %>,欢迎您来到FUCK网!<br>
您的IP是:<%=request.getRemoteAddr() %><br>
你的主机是:<%=request.getRemoteHost() %><br>
你使用的协议是:<%=request.getProtocol() %><br>
你目前的地址是:<%=request.getRealPath("/") %>
你的主机端口是:<%=request.getRemotePort() %>
</body>
</html>
=====================================================================
页面流向图
所涉知识点:
*JDBC连接的数据库的写法
*在Web.xml中配置Servlet
*在JSP中使用JavaBean
<jsp:useBean>与<jsp:setProperty>
<jsp:useBean>与<jsp:setProperty>是联系在一起的,在<jsp:setProperty>中的name值应当和<jsp:useBean>中的ID值相同。
<jsp:useBean id="user" class="beans.UserBean" scope="request"/>
<jsp:setProperty name="user" property="*"/>
*js验证的写法,及在页面中的触发
<script type="text/javascript">
function check(form){
if(document.forms.form1.username.value==""){
alert("pls input username");
document.forms.form1.username.focus();
return false;
}
if(document.forms.form1.password.value==""){
alert("pls input password");
document.forms.form1.password.focus();
return false;
}
}
</script>
<input type="submit" name="submit" onclick="return check(this);"/>
*request、response的常见用法
request常用方法
取得相关信息:
您的IP是:<%=request.getRemoteAddr() %><br>
你的主机是:<%=request.getRemoteHost() %><br>
你使用的协议是:<%=request.getProtocol() %><br>
你目前的地址是:<%=request.getRealPath("/") %>
接收请求内容:
通过:Request.getParemeter(“username”) 接收请求内容:代码如下所示:
String name = request.getParameter("uname") ;
取得文本框提交的信息
String name = request.getParameter("uname") ;
取得按钮的名字:
String name = request.getParameter("submit") ;
设置浏览器的输出文件类型,及编码标准
<%@page contentType="text/html;charset=gb2312"%>
两秒后自动跳转到新页面:
<%response.setHeader("refresh","3;URL=login.jsp");%>
//设置HTTP响应的文档类型,此处为Text/html,如果更改为application\msword则设置为word文档格式
response.setContentType("text/html");
//设置响应所采用的编码方式
response.setCharacterEncoding("GB18030");
*转发和重定向的区别
转向页面:
重定向(redirect):以前的request中存放的变量全部失效,并进入一个新的request作用域。
转发(Forward):以前的request中存放的变量不会失效,就像把两个页面拼到了一起。
<jsp:forward page="login_success.jsp"/>
(注:只要使用了服务器端跳转<jsp:forward>,则请求内容可以在跳转之后的页面继续得到)
Response.sendRedirect(“URL”);//重定向
request.getRequestDispatcher("apage.jsp").forward(request, response);//转发到apage.jsp
<jsp:forward page="d.jsp"/> //转发到d.jsp 在JSP中使用
response.sendRedirect("apage.jsp");//重定向到apage.jsp