JavaWeb——JSP调用数据库、JavaBean、MVC模式

JSP访问数据库

JSP就是在html中嵌套的java代码,因此 java代码可以写在jsp中(<%  ... %>)

导包操作:

  • java项目 :1 Jar复制到工程中 2.右键该Jar :build path ->add to build Path
  • Web项目:jar复制到WEB-INF/lib

核心:就是将 java中的JDBC代码,复制到 JSP中的<% ... %>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="check.jsp" method="post">
		用户名:<input type="text" name="uname" /><br/>
		密码:<input type="password" name="upwd" /><br/>
		<input type="submit"  value="登录" /><br/>
	</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    
    <title>My JSP 'check.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
       <%
       	String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
		String USERNAME = "MANAGER";
		String PWD = "manager";
       
       	Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null ; 
		try {
			// a.导入驱动,加载具体的驱动类
			Class.forName("oracle.jdbc.OracleDriver");// 加载具体的驱动类
			// b.与数据库建立连接
			connection = DriverManager.getConnection(URL, USERNAME, PWD);
			// c.发送sql,执行(增删改、【查】)
			stmt = connection.createStatement();
//			String sql = "select stuno,stuname from student";
			Scanner input= new Scanner(System.in);
			String name = request.getParameter("uname");
			String pwd = request.getParameter("upwd");
			String sql = "select count(*) from table_user where username='"+name+"' and password ='"+pwd+"' " ;
//			String sql = "select * from student where stuname like '%"+name+"%'";
			// 执行SQL(增删改executeUpdate(),查询executeQuery())
			rs = stmt.executeQuery(sql); // 返回值表示 增删改 几条数据
			// d.处理结果
			int count = -1;
			if(rs.next()) {
				count = rs.getInt(1) ;
			}
			if(count>0) {
				System.out.println("登陆成功!");
			}else {
				System.out.println("登陆失败!");
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if(rs!=null) rs.close(); 
				 if(stmt!=null) stmt.close();// 对象.方法
				 if(connection!=null)connection.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
        %>
  </body>
</html>

注意:如果jsp出现错误:The import Xxx cannot be resolved
    
尝试解决步骤:
    a.(可能是Jdk、tomcat版本问题) 右键项目->build path,将其中 报错的 libary或Lib 删除后 重新导入
    b.清空各种缓存:右键项目->Clean tomcat... clean  (Project -clean或者 进tomcat目录 删除里面work的子目录)
    c.删除之前的tomcat,重新解压缩、配置tomcat,重启计算机
    d.如果类之前没有包,则将该类加入包中

DAO  

起类名是加dao意思是操作数据库的类,即将<%.....%>中的java

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="check.jsp" method="post">
		用户名:<input type="text" name="uname" /><br/>
		密码:<input type="password" name="upwd" /><br/>
		<input type="submit"  value="登录" /><br/>
	</form>
</body>
</html>

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<%@ page import="LOGIN.*" %>
<!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=UTF-8">
		<title>Insert title here</title>
	</head>
<body>		
		<%
		
			String name = request.getParameter("uname") ;
			String pwd = request.getParameter("upwd") ;
			Login login = new Login(name,pwd) ;
			
			
			LoginDao dao = new LoginDao();
			
			int result = dao.login(login) ;
			if(result >0){
				out.print("登录成功!");
			}else if(result==0){
				out.print("用户名或密码有误!!");
			}else{
				out.print("系统异常!!");
			}
		
		%>
</body>
</html>

Login.java

package LOGIN;

public class Login {
	 
	private String name;
	private String pwd ;
	
	public Login() {
	}
	public Login(int id, String name, String pwd) {
		this.name = name;
		this.pwd = pwd;
	}
	public Login( String name, String pwd) {
		this.name = name;
		this.pwd = pwd;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	} 
	
}

LoginDao.java

package LOGIN;


import java.sql.*;



public class LoginDao {
//	public int login(String name,String pwd)//1:登录成功   0:登录失败(用户名或密码有误)  -1:系统异常
	public int login(Login login)//1:登录成功   0:登录失败(用户名或密码有误)  -1:系统异常
	{
		String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
		String USERNAME = "MANAGER";
		String PWD = "manager";
		Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null ; 
		try {
			// a.导入驱动,加载具体的驱动类
			Class.forName("oracle.jdbc.OracleDriver");// 加载具体的驱动类
			// b.与数据库建立连接
			connection = DriverManager.getConnection(URL, USERNAME, PWD);
			// c.发送sql,执行(【查】)
			stmt = connection.createStatement();
			
		//	String name = request.getParameter("uname") ;
		//	String pwd = request.getParameter("upwd") ;
			
			String sql = "select count(*) from table_user where username='"+login.getName()+"' and password ='"+login.getPwd()+"' " ;
			rs = stmt.executeQuery(sql); // 返回值表示 增删改 几条数据
			// d.处理结果
			int count = -1;
			if(rs.next()) {
				count = rs.getInt(1) ;
			}
//			if(count>0) {
//				out.println("登陆成功!");
//			}else {
//				out.println("登陆失败!");
//			}
			return count ;

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return -1 ;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1 ;
		} catch(Exception e) {
			e.printStackTrace();
			return -1 ;
		}
		finally {
			try {
				if(rs!=null) rs.close(); 
				 if(stmt!=null) stmt.close();// 对象.方法
				 if(connection!=null)connection.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

JavaBean

dao  就是一个javabean

刚才我们将 jsp中 登录操作的代码  转移到了LoginDao.java;其中LoginDao类 就称之为JavaBean。
JavaBean的作用:a.减轻的jsp复杂度  b.提高代码复用(以后任何地方的 登录操作,都可以通过调用LoginDao实现)

JavaBean(就是一个Java类)的定义:满足一下2点 ,就可以称为JavaBean

  •     a.public 修饰的类  ,public 无参构造
  •     b.所有属性(如果有) 都是private,并且提供set/get   (如果boolean 则get 可以替换成is)

使用层面Java分为2大类:

a.封装业务逻辑的JavaBean (LoginDao.java封装了登录逻辑)            逻辑
    可以将jsp中的JDBC代码,封装到Login.java类中 (Login.java)

b.封装数据的JavaBean   (实体类,Student.java  Person.java  )        数据 
    对应于数据库中的一张表
    Login login = new Login(uname,upwd) ;//即用Login对象 封装了2个数据(用户名 和密码)

封装数据的JavaBean 对应于数据库中的一张表   (Login(name,pwd))
封装业务逻辑的JavaBean 用于操作 一个封装数据的JavaBean  

可以发现

JavaBean可以简化 代码(jsp->jsp+java)、提供代码复用(LoginDao.java)

public  void sleep(String name,String place, int time)
{

}

public  void sleep(Person per)
{
    per.getName()
    per.getPlace()
    ...
}

MVC设计模式:


M:Model,模型  :一个功能。用JavaBean实现。

V:View,视图: 用于展示、以及与用户交互。使用html  js  css jsp jquery等前端技术实现 。

C:Controller,控制器 :接受请求,将请求跳转到模型进行处理;模型处理完毕后,再将处理的结果
            返回给 请求处 。 可以用jsp实现,  但是一般建议使用 Servlet实现控制器。

Jsp->Java(Servlet)->JSP

MVC设计模式:

猜你喜欢

转载自blog.csdn.net/Qmilumilu/article/details/86480356