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]

猜你喜欢

转载自blog.csdn.net/Fern2018/article/details/81259785