第一个JSP+Servlet+JavaBean+JDBC示例程序

[size=medium][b]运行环境:[/b][quote]JDK1.5[/size]
Tomcat5.5
MyEclips5.5.1 GA
SqlServer2000
windows2003[/quote]

[size=medium][b]1.在SqlServer下的查询分析器中新建表:[/b][/size]
create table dbuser(
userId int identity(1,1) primary key not null,
userName varchar(50),
userPasswd varchar(50))


[size=medium][b]2.在MyEclipse中新建Web工程,并创建包结构。[/b][/size]

[img]http://dl.iteye.com/upload/attachment/236941/23bec9ce-3fdc-34db-b87f-13e634458974.png[/img]


[size=medium][b]3.编写登陆界面。[/b][/size]
<%@ 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>


[img]http://dl.iteye.com/upload/attachment/236943/d77f44c2-e3ba-3ef5-8be8-cd4e3f4e801a.png[/img]

[size=medium][b]3.编写工具类DBConn。[/b][/size]
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();
// }
// }
}


[size=medium][b]4.编写Servlet,LoginServlet.java。[/b][/size]
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);
}


}

[size=medium][b]5.在web.xml中配置Servlet。[/b][/size]
[quote]
配置关键代码
 <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>


[/quote]

[size=medium][b]5.编写userBean。[/b][/size]
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;
}

}


[size=medium][b]6.编写JavaBean CheckUser。[/b][/size]

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;

}

}


[size=medium][b]7.编写错误页面及成功登陆页面。[/b][/size]

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>


=====================================================================
页面流向图


[img]http://dl.iteye.com/upload/attachment/236946/8bc98e17-1413-3959-b033-88860d7f5fe6.png[/img]


所涉知识点:
[b]*JDBC连接的数据库的写法[/b]

[b]*在Web.xml中配置Servlet[/b]

[img]http://dl.iteye.com/upload/attachment/236948/1cb19fc3-9f34-3a11-88ee-07cef2efbf58.png[/img]

[b]*在JSP中使用JavaBean[/b]


<jsp:useBean>与<jsp:setProperty>
[b]<jsp:useBean>与<jsp:setProperty>是联系在一起的,在<jsp:setProperty>中的name值应当和<jsp:useBean>中的ID值相同。[/b]

<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);"/>


[b]*request、response的常见用法[/b]


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");


[b]*转发和重定向的区别[/b]

转向页面:
重定向(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
基于JSP+JAVABEAN+JDBC图书管理系统摘 要 .........................................................1目 录 .........................................................2第一章 绪论 .....................................................3 1.1 引言 .....................................................31.2 JSP的基础知识 ................................................31.3 图书管理系统 .................................................41.4 本系统的开发模式 ..............................................5第二章 系统分析阶段 ..............................................62.1 需求分析 .....................................................62.2系统功能模块 ...............................................72.2.1 功能的实现 ..............................................72.2.2 模块框架图 ...............................................82.3系统数据分析 .................................................82.4数据流图 .................................................9第三章 数据库设计.................................................113.1数据库的引入 ................................................113.1.1数据库概论及SQL、ACCESS2000简介 ...........................123.2系统数据库设计.................................................133.4数据库的完整性和安全性.........................................163.4.1数据库的完整性................................................163.4.2数据库的安全性................................................16第四章 程序设计 .................................................174.1 程序设计思想 .................................................174.2 程序设计语言...................................... ...........184.3 数据库连接的建立 ............................................194.4 各个子系统程序设计............................................194.2.1“系统管理”模块设计..........................................194.4.2“基本资料维护”模块设计.....................................214.4.3查询模块设计................................................21总结与展望.......................................................23结束语 .... ..................................................23致谢 .......................................................24参考文献 ..................................................24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值