0726/0727 JSP (Tomcat) Login.jsp/DoLogin.jsp/Main.jsp(導入jadc/User/UserDao/DBUtils) 查詢Emp

Tomcat的安裝與使用     創建動態web工程

什麼是JSP?
    Java Server Page -- java 服務器頁面

jsp的基本組成
jsp指令
html/css/js
jsp表達式(java代碼)

jsp的運行過程
  .jsp--> .java -->.class-->向客戶端輸出html
  jsp的本質是一個Servlet

jsp表達式
<%%>
<%= %>

jsp隱式對象
  輸入輸出對
   out
   request
   response
 
  作用域對象
   pageContext
   request
   session 
   application

  page
  config

  exception

轉發與重定向
   轉發:一次請求,兩個web組件,可在request作用域中綁定數據
   重定向:兩次請求,兩個web組件,不能在request作用域中綁定數據
   
登錄案例
員工管理系統

<!-- 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>
     <h1 style="color:red">你好,世界</h1>
     <%
          String s = "hello world";
          s += " hello marry";   
          out.print("<h2 style='color:green'>"+s+"</h2>");
     %>
     <br/>
     <h3 style='color:pink'>
     <%=s %>
     </h3>
     <script type="text/javascript">
         //alert("you can you up");
     </script>
</body>
</html>

 

t_User表

create table t_User(
       uid int primary key  identity NOT NULL,
	  username varchar(20) DEFAULT NULL,
	  password varchar(20) DEFAULT NULL,
	  name varchar(20) DEFAULT NULL,
	  email varchar(30) DEFAULT NULL,
	  telephone varchar(20) DEFAULT NULL,
	  birthday date DEFAULT NULL,
	  sex varchar(10) DEFAULT NULL
)

insert into t_User values('zs','123','張芳','[email protected]','18274834196','1992-10-10','女'),
('ls','456','李天星','[email protected]','18274834197','1988-10-10','男')

select * from [User]

 導入的文件:jdbc / User / UserDao / DBUtils

    jdbc ---  WebContent.WEB-INF.lib

      src.com.hj.bean

package com.hj.bean;

import java.sql.Date;

//`uid` int primary key  NOT NULL,
//`username` varchar(20) DEFAULT NULL,
//`password` varchar(20) DEFAULT NULL,
//`name` varchar(20) DEFAULT NULL,
//`email` varchar(30) DEFAULT NULL,
//`telephone` varchar(20) DEFAULT NULL,
//`birthday` date DEFAULT NULL,
//`sex` varchar(10) DEFAULT NULL,
public class User {
	private Integer uid;
	private String username;
	private String password;
	private String name;
	private String email;
	private String telephone;
	private Date birthday;
	private String sex;

	public User() {
		super();
	}

	public User(Integer uid, String username, String password, String name, String email, String telephone,
			Date birthday, String sex) {
		super();
		this.uid = uid;
		this.username = username;
		this.password = password;
		this.name = name;
		this.email = email;
		this.telephone = telephone;
		this.birthday = birthday;
		this.sex = sex;
	}

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

}

    src.com.hj.dao

package com.hj.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hj.bean.User;
import com.hj.utils.DBUtils;

public class UserDao {
    
	  public User queryUserByNameAndPwd(String username,String password) throws SQLException{
		    //聲明三個核心接口
		   Connection conn = null;
		   PreparedStatement prep = null;
		   ResultSet rs = null;
		   //sql
		   String sql = "select * from t_user where username=? and password=?";
		   User user = null;
		   
		   try {
				//獲得連接
				conn = DBUtils.getConnection();
				//獲得預編譯對象
				prep = conn.prepareStatement(sql);
				//設置參數
				prep.setString(1, username);
				prep.setString(2, password);
				//發送預編譯文件,執行sql
				//獲得結果集
				rs = prep.executeQuery();
				//遍歷結果集,用結果中的數據封裝User對象
				while(rs.next()){
					  user = new User();
					  user.setUid(rs.getInt("uid"));
					  user.setUsername(rs.getString("username"));
					  user.setName(rs.getString("name"));
					  user.setSex(rs.getString("sex"));
					  user.setPassword(rs.getString("password"));
					  user.setEmail(rs.getString("email"));
					  user.setTelephone(rs.getString("telephone"));
					  user.setBirthday(rs.getDate("birthday"));
				}
				return user;
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;
			}finally{
				  //關閉資源
				DBUtils.closeAll(rs, prep, conn);
			}
		   
	  }
}

      src.com.hj.utils

package com.hj.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
    //jdbc的四個重要參數作爲工具類的常量
	//驅動字符串
	public static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	//連接字符串
	public static final String URL = "jdbc:sqlserver://localhost:1433;dataBaseName=db02";
	//用戶名
	public static final String USER = "sa";
	//密碼
	public static final String PASSWORD = "123";
	
	//在靜態塊中加載驅動類
	//在類加載的時候,執行的代碼
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//獲得連接對象的方法
	public static Connection getConnection() throws SQLException {
		 return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
	//關閉資源的方法
	public static void closeAll(ResultSet rs, PreparedStatement prep,Connection conn) throws SQLException{
		    try {
				if(rs!=null){
					  rs.close();
				}
				if(prep!=null){
					 prep.close();
				}
				if(conn!=null){
					 conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;//將異常信息繼續往上拋,通知調用者
			}
		    
		    
	}
	//測試
	 public static void main(String[] args) throws SQLException {
		     Connection conn = getConnection();
		     System.out.println(conn);
	}
}

 

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>
    <%
         //取出錯誤消息
         String error_msg = (String)request.getAttribute("error_msg");
    %>
    <h3 style='color:red'><%=error_msg==null?"":error_msg %></h3>
     <form action="DoLogin.jsp"  method="post">
        用戶:<input name="username"/> <br/>
        密碼:<input type="password"  name="password"/> <br/>
        <input type="submit"  value="登錄"/>
     </form>
</body>
</html>

DoLogin.jsp

<%@page import="com.hj.bean.User"%>
<%@page import="com.hj.dao.UserDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 
    正確的用戶名和密碼: zs  123
 -->   
 <%
       //設置解碼方式
         request.setCharacterEncoding("UTF-8");
       //獲得Login.jsp傳來的參數
       String username  = request.getParameter("username");
       String password = request.getParameter("password");
       //創建Dao對象
        UserDao dao = new UserDao();
        User user = dao.queryUserByNameAndPwd(username, password);
       
       //out.print(username+","+password);
       //判斷用戶名和密碼是否正確
       if(user!=null){
    	   //out.print("登錄成功");
    	   //跳轉到主頁面 Main.jsp
    	    //轉發--將請求轉交給另外一個jsp頁面
    	    //綁定用戶名
    	    //request.setAttribute("username",username);
    	     session.setAttribute("user", user);
    	     // request.setAttribute("user", user); --錯誤
    	     //request.getRequestDispatcher("Main.jsp").forward(request, response);    	  
    	     //使用重定向
    	     response.sendRedirect("Main.jsp");
       }else{
    	   //out.print("用戶名或密碼錯誤");
    	   //綁定錯誤消息
    	   request.setAttribute("error_msg", "用戶名或密碼錯誤");   	   
    	   //轉發回Login.jsp
    	   request.getRequestDispatcher("Login.jsp").forward(request, response);  
       }
       
 %>   

Main.jsp 

<%@page import="com.hj.bean.User"%>
<%@ 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>
     <%
            //String username = (String)request.getAttribute("username");
            User user =  (User)session.getAttribute("user");
            // User user =  (User)request.getAttribute("user"); --錯誤

     %>
      <h1>歡迎你,<%=user.getName() %></h1>
</body>
</html>

 

查詢Emp表中10條記錄

 建表
  部門表
    刪除表
    drop table Dept
	drop table Emp

     create table Dept(
	    deptno int primary key, --部門編號
		dname varchar(200) not null,--部門名稱
		location varchar(400) not null -- 部門地址
	 )

  員工表
    create table Emp(
	     empno int primary key identity,--員工編號
		 ename varchar(50) not null,--姓名
		 sex char(3)  check(sex in('男','女')) default '男',--性別
		 age int check(age between 18 and 60),--年齡
		 sal float check(sal>=3000) default 3000,--薪資
		 deptno int  references Dept(deptno)
	)

	select * from dept
	select * from emp

	添加
	insert into dept values(10,'java開發部','北京'),(20,'市場','上海'),
	(30,'企劃部','長沙')

	select * from dept

	insert into emp values('熊大','男',25,12000,10),('熊二','男',23,11000,10),
('張三','女',21,9000,10),('李四','女',26,15000,20),('王五','男',27,16000,20),
('趙六','女',20,6000,20),('孫七','男',21,10000,30),('吳八','女',23,13000,30),
('鄧九','男',20,9000,30),('常十','女',21,8000,30);

	select * from emp

	刪除表中所有的記錄,如果再添加記錄標識列,會重新開始
truncate table emp
package com.hj.bean;

public class Emp {
	//與數據表結構一致
    private Integer empno;
    private String ename;
    private String sex;
    private Integer age;
    private Float sal;
    private Integer deptno;
	public Emp() {
		super();
		// TODO Auto-generated constructor stub
	}
   
	public Emp(Integer empno, String ename, String sex, Integer age, Float sal, Integer deptno) {
		super();
		this.empno = empno;
		this.ename = ename;
		this.sex = sex;
		this.age = age;
		this.sal = sal;
		this.deptno = deptno;
	}

	public Integer getEmpno() {
		return empno;
	}

	public void setEmpno(Integer empno) {
		this.empno = empno;
	}

	public String getEname() {
		return ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Float getSal() {
		return sal;
	}

	public void setSal(Float sal) {
		this.sal = sal;
	}

	public Integer getDeptno() {
		return deptno;
	}

	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}

	
   @Override
   public String toString() {
	return empno+"\t"+ename+"\t"+sex+"\t"+age+"\t"+sal+"\t"+deptno;
   }
    
}
package com.hj.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hj.bean.Emp;
import com.hj.utils.DBUtils;

public class EmpDao {
   //封裝基礎業務邏輯
	//增
	public int save(Emp emp) throws SQLException{
		  //聲明2個核心接口
		   Connection conn = null;
		   PreparedStatement prep = null;
		   String sql = "insert into emp values(?,?,?,?,?)";
		   try {
			   //獲得連接對象
			conn = DBUtils.getConnection();
			  //獲得預編譯對象
		     prep = conn.prepareStatement(sql);
			 //設置參數
			 prep.setString(1,emp.getEname());
			 prep.setString(2, emp.getSex());
			 prep.setInt(3, emp.getAge());
			 prep.setFloat(4, emp.getSal());
			 prep.setInt(5, emp.getDeptno());
			 //prep.setDate(x, dd);
			 //發送預編譯文件,執行sql
			 return prep.executeUpdate();		 
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}finally{
			  //關閉資源
			  DBUtils.closeAll(null, prep, conn);
		}
	}
	//刪,依據主鍵刪除
	public int delete(int empno) throws SQLException{
		  //聲明2個核心接口
		   Connection conn = null;
		   PreparedStatement prep = null;
		   String sql = "delete from emp where empno=?";
		   try {
			   //獲得連接對象
			conn = DBUtils.getConnection();
			  //獲得預編譯對象
		     prep = conn.prepareStatement(sql);
			 //設置參數
			 prep.setInt(1,empno);
			 //發送預編譯文件,執行sql
			 return prep.executeUpdate();		 
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}finally{
			  //關閉資源
			  DBUtils.closeAll(null, prep, conn);
		}
	}
	//改
	//只能修改數據庫存在的記錄
	//修改的前提是查詢
	//修改應該能夠修改除主鍵以外所有的字段
	//應該依據主鍵去修改
	//參數emp對象是數據庫存在的記錄,所以它是查詢方法
	//查詢出來的
	public int modify(Emp emp) throws SQLException{
		  //聲明2個核心接口
		  Connection conn = null;
		  PreparedStatement prep = null;
		  //sql
		  String sql = "update emp set ename=?,sex=?,age=?,sal=?,deptno=? where empno=?";
		  try {
			//獲得連接對象
			  conn = DBUtils.getConnection();
			//獲得預編譯對象
			  prep = conn.prepareStatement(sql);
			  //設置參數
			  prep.setString(1, emp.getEname());
			  prep.setString(2, emp.getSex());
			  prep.setInt(3, emp.getAge());
			  prep.setFloat(4, emp.getSal());
			  prep.setInt(5, emp.getDeptno());
			  prep.setInt(6, emp.getEmpno());
			  //發送預編譯文件,執行sql
			  return prep.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}finally{
			 //關閉資源
			DBUtils.closeAll(null, prep, conn);
		}
	}
	
	//查(最複雜)
	//只查詢一條記錄,依據員工編號查詢
	public Emp queryForId(int empno) throws SQLException{
		  //聲明3個核心接口
		 Connection conn = null;
		 PreparedStatement prep = null;
		 ResultSet rs = null;
		 Emp emp = null;
		 //sql
		 String sql = "select * from emp where empno=?";
		 try {
			//獲得連接對象
			 conn = DBUtils.getConnection();
			//獲得預編譯對象
			 prep = conn.prepareStatement(sql);
			 //設置參數
			 prep.setInt(1,empno);
			 //發送預編譯文件,執行sql
			 //獲得結果集對象
			 rs = prep.executeQuery();
			 //遍歷結果集,用結果集中的數據
			 //封裝對象
			 while(rs.next()){
				  emp = new Emp();
				  emp.setEmpno(rs.getInt("empno"));
				  emp.setEname(rs.getString("ename"));
				  emp.setSex(rs.getString("sex"));
				  emp.setAge(rs.getInt("age"));
				  emp.setSal(rs.getFloat("sal"));
				  emp.setDeptno(rs.getInt("deptno"));
			 }
			 return emp;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}finally{
			   //關閉資源
			DBUtils.closeAll(rs, prep, conn);
		}
	}
	//查詢所有的記錄
	public List<Emp> queryAll() throws SQLException{
		  //聲明3個核心接口
		 Connection conn = null;
		 PreparedStatement prep = null;
		 ResultSet rs = null;
		 List<Emp> emps = null;
		 //sql
		 String sql = "select * from emp";
		 try {
			//獲得連接對象
			 conn = DBUtils.getConnection();
			//獲得預編譯對象
			 prep = conn.prepareStatement(sql);
			 //發送預編譯文件,執行sql
			 //獲得結果集對象
			 rs = prep.executeQuery();
			 //遍歷結果集,用結果集中的數據
			 //封裝對象
			 while(rs.next()){
				  if(emps==null){
					  //循環第一次,實例化集合對象
					  emps = new ArrayList<Emp>();
				  }
				  //實例化一個員工對象
				  Emp emp = new Emp();
				  emp.setEmpno(rs.getInt("empno"));
				  emp.setEname(rs.getString("ename"));
				  emp.setSex(rs.getString("sex"));
				  emp.setAge(rs.getInt("age"));
				  emp.setSal(rs.getFloat("sal"));
				  emp.setDeptno(rs.getInt("deptno"));
				  emps.add(emp);
			 }
			 return emps;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}finally{
			   //關閉資源
			DBUtils.closeAll(rs, prep, conn);
		}
	}
}
package com.hj.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
    //jdbc的四個重要參數作爲工具類的常量
	//驅動字符串
	public static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	//連接字符串
	public static final String URL = "jdbc:sqlserver://localhost:1433;dataBaseName=db01";
	//用戶名
	public static final String USER = "sa";
	//密碼
	public static final String PASSWORD = "123";
	
	//在靜態塊中加載驅動類
	//在類加載的時候,執行的代碼
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//獲得連接對象的方法
	public static Connection getConnection() throws SQLException {
		 return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
	//關閉資源的方法
	public static void closeAll(ResultSet rs, PreparedStatement prep,Connection conn) throws SQLException{
		    try {
				if(rs!=null){
					  rs.close();
				}
				if(prep!=null){
					 prep.close();
				}
				if(conn!=null){
					 conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;//將異常信息繼續往上拋,通知調用者
			}
		    
		    
	}
	//測試
	 public static void main(String[] args) throws SQLException {
		     Connection conn = getConnection();
		     System.out.println(conn);
	}
}

ListEmp.jsp

<%@page import="com.hj.bean.Emp"%>
<%@page import="java.util.List"%>
<%@page import="com.hj.dao.EmpDao"%>
<%@ 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>
<style type="text/css">
     table{
        width:600px;
        border:3px solid #ccc;
        border-collapse: collapse;   //去掉中間的間隔
        margin:auto;
     }
     
     table th,table td{
          border:1px solid #ccc;
          
     }
     
     h3,p{
       text-align: center;
     }
     
     
</style>
</head>
<body>
   <!-- 
      從數據庫獲得數據,渲染到頁面
    -->
     <%
         EmpDao dao = new EmpDao();
          //查詢出所有10條記錄
          List<Emp> es =  dao.queryAll();   
          //將數據渲染到一個table
     %>
        <h3>員工管理系統</h3>
      <table>
           <tr>
              <th>編號</th>
              <th>姓名</th>
              <th>性別</th>
              <th>年齡</th>
              <th>薪資</th>
              <th>部門</th>
              <th>操作</th>
           </tr>
           <%
               for(int i=0;i<es.size();i++){
            	     //從集合中取出一個員工數據
            	     Emp e = es.get(i);
            	     //將e的數據填充爲表格的一行
            	   %>  
             <tr>
              <td><%=e.getEmpno() %></td>
              <td><%=e.getEname() %></td>
              <td><%=e.getSex() %></td>
              <td><%=e.getAge() %></td>
              <td><%=e.getSal() %></td>
              <td><%=e.getDeptno() %></td>
              <td>
                   <a href="#">刪除</a>
                   <a href="#">修改</a>
              </td>
           </tr>
            	   <% 
               }
           %>
      </table>
     <p>
        <a href="#">添加員工</a>
     </p>
</body>
</html>
create table [User](
       uid int primary key  identity NOT NULL,
	  username varchar(20) DEFAULT NULL,
	  password varchar(20) DEFAULT NULL,
	  name varchar(20) DEFAULT NULL,
	  email varchar(30) DEFAULT NULL,
	  telephone varchar(20) DEFAULT NULL,
	  birthday date DEFAULT NULL,
	  sex varchar(10) DEFAULT NULL
)

insert into [User] values('zs','123','張芳','[email protected]','18274834196','1992-10-10','女'),
('ls','456','李天星','[email protected]','18274834197','1988-10-10','男')

select * from [User]

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章