第一个JSP+Servlet+JavaBean+JDBC示例程序
运行环境
Apache Tomcat 8.0.33
JDK 1.8.0_92
IntelliJ IDEA 2016.1.1
MySql 5.7.12
UbuntuKylin 16.04
一、在MYSQL中新建表并插入测试数据
create database test_jsp;
use test_jsp;
create table dbuser(
userId int auto_increment primary key,
userName varchar(50),
userPasswd varchar(50)
);
insert into dbuser values(1,'admin','admin');
二、在idea中创建web项目,并建立带包结构。
三、编写首页登陆界面
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>第一个JSP+Servlet+JavaBean+JDBC程序示例</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("请输入用户名");
//将输入焦点定位到没有输入的地方
document.forms.form1.username.focus();
//返回错误
return false;
}
if(document.forms.form1.password.value==""){
alert("请输入密码");
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></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>
四、编写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;
}
}
五、编写工具类DBConn
package utils;
import java.sql.*;
public class DBConn {
public static String driver;//定义驱动
public static String url;//定义URL
public static String server;
public static String dbname;
public static String user;
public static String pass;
public static String port;
public static Connection conn;//定义连接
public static Statement stmt;//定义STMT
public ResultSet rs;//定义结果集
//设置CONN
static{
try {
driver="com.mysql.jdbc.Driver";
dbname="test_jsp";
server="localhost";
user="root";
pass="root";
port="3306";
url="jdbc:mysql://"+server+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
Class.forName(driver);
conn = DriverManager.getConnection(url);
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);
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;
}
}
}
六、编写JavaBean CheckUser
package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DBConn;
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 dbuser where userName='"+user.getUsername()+"' && userPasswd='"+user.getPassword()+"'");
try {
if(rs.next()){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
}
七、编写Servlet,LoginServlet.java
package servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import model.CheckUser;
import beans.UserBean;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置HTTP响应的文档类型,此处为Text/html,如果更改为application\msword则设置为word文档格式
response.setContentType("text/html;charset=UTF-8");
//设置响应所采用的编码方式
response.setCharacterEncoding("UTF-8");
//取得参数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);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
八、在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 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<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-app>
九、编写错误页面及成功登陆页面
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆错误页面</title>
</head>
<body>
Sorry!你的登陆信息不正确!系统无法让你登陆!<a href="index.jsp">点击返回</a>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="beans.UserBean" scope="request"/>
<jsp:setProperty name="user" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆成功页面</title>
</head>
<body>
<%
session.setAttribute("user",user);
String username=user.getUsername();
%>
<%=username %>,欢迎您!<br>
您的IP是:<%=request.getRemoteAddr() %><br>
你的主机是:<%=request.getRemoteHost() %><br>
你使用的协议是:<%=request.getProtocol() %><br>
你目前的地址是:<%=request.getRealPath("/") %><br>
你的主机端口是:<%=request.getRemotePort() %>
</body>
</html>
此文章根据http://jzgl-javaeye.iteye.com/blog/647946实践并自行修改