第75节:Java中的JSP,EL和JSTL

第75节:Java中的JSP,EL和JSTL

哭吧看不完的!!!

字数:5745

Cookie和`Session

请求转发和重定向的区别:

  1. 地址不一样
  2. 请求次数也不一样
  3. 数据无法传递 4.跳转范围有限制
  4. 效率

请求转发请求1次,只能对当前项目跳转,重定向请求2次.重定向是无法传递的,重定向对跳转范围没有限制.

Cookie是服务器发送给客户端,存储在客户端的小数据.发送cookie:

Cookie cookie = new Cookie("key", value");
response.addCookie(cookie);

服务器返回cookie给客户端
// 响应头
Set-Cookie: a=b

接收cookie

Cookie[] cookies =  request.getCookies();

客户端提交数据的cookie
// Cookie: a=b;c=d;

Cookie分会话cookie和持久cookie

关闭cookie,可以关闭浏览器.

持久的cookie,在一段时间内有效

Cookie cookie = new Cookie("a","b");
cookie.setMaxAge(); // 秒
response.addCookie(cookie);

cookie.setDomain(".dashucoding.com");
// 只有带上这个域名的时候,才会有cookie
// 例如:www.dashucoding.com

cookie..setPath("/Demo");
// 要进行访问上面的路径才会带cookie
http://localhost:8080/Demo

移除cookie

Cookie cookie = new Cookie("a","b");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);

// 获取以前cookie,设置有效期
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtil.findCookie(cookies,"a");
cookie.setMaxAge(0);
reponse.addCookie(cookie);

cookie是存在客户端的.

可以创建一个新的cookie去替换

Cookie cookie = new Cookie("a","dashu");
cookie.setMaxAge(0);
response.addCookie(cookie);

Session是基于Cookie的一种会话技术.cookie的安全隐患,是把数据存放在客户端,下次访问时,带上这个数据,服务端就知道客户端是谁.

Session的数据是存放在服务端.

session对应sessionid传递给客户端,是通过cookie传递的.只要有sessiondi,就可以获取以前的数据.

HttpSession session = request.getSession();
session.setAttribute();
sesssion.getAttribute();
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession();
        // 得到会话ID
        session.getId();
        // 存值
        //session.setAttribute(name, value);
        // 取值
        //session.getAttribute(name);
        // 移植
        //session.removeAttribute(name);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

session创建:

request.getSession

销毁

关闭服务器,或自动会话过期,默认时间为30分钟.

在进行访问浏览器时,再次重启是无法获取以前的数据的,因为sessionid是通过cookie来传递的,cookie没有设置有效期,关闭后,就cookie删除了,同时cookie带过来sessionid同样也没有了.

手动设置cookie

String id = request.getSession().getId();
Cookie cookie = new Cookie("JSESSIONID",id);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);

JSPELJSTL

什么是JSP

JSP就是一个网页而已,或者是一个Java类,继承了servlet,所以jsp是一个servlet.

jsp设计目的是因为html是显示静态内容,有时网页要一些动态数据.html是不支持java代码,jsp支持java代码.

写法

指令
<%@ %>
language
contentType内容类型
content-Type="text/html;charset=UTF-8"
pageEncoding jsp内容编码
extends="httpjspbase"
用于指定jsp翻译成java文件后,继承的父类是谁

import导包使用,一般不用手写
session
true or false

errorPage 错误的页面.
isErrorPage="true" 显示错误
errorPage="error.jsp" 呈现错误

errorPage 值需要给错误的页面路径

include
<%-- <%@ include file="other02.jsp"%> --%>
把另外一个页面的内容拿过来

<%--  <%@ taglib prefix=""  uri=""%>    --%>
url标签库的路径
prefix别名

includeforward

<%-- 
    <jsp:include page=""></jsp:include>
    <jsp:param value="" name=""/>
    <jsp:forward page=""></jsp:forward> --%>
    <%-- <jsp:include page="other02.jsp"></jsp:include> --%>
    
    <%-- <jsp:forward page="other02.jsp"></jsp:forward>
    等同于以下代码 --%>
    <% 
        //请求转发
        //request.getRequestDispatcher("other02.jsp").forward(request, response);
    %>  
    
    <jsp:forward page="other02.jsp">
        <jsp:param value="beijing" name="address"/>
    </jsp:forward>

效果

效果

jsp: param
<jsp:forward page="other02.jsp">
 <jsp:param value="beijing" name="address"/>
</jsp:forward>

<%= request.getParameter("address")%>

小结

什么是JSP 为什么会有JSP 三大指令集

page
有什么用,那么怎么用,有哪些常用的属性
include
有什么用,那么怎么用
taglib
有什么用,怎么用
JSP动作标签
jsp:forword
jsp:include
jsp:param

jsp的内置对象

四个作用域
pageContext
request
session
appiication

JSP内置对象

内置对象是在jsp页面中使用的这些对象,不用创建

pageContext
request
session
application

exception
out
page
config
response
application: ServletContext
config: ServletConfig
out: JspWriter
page: Object
pageContext: PageContext
request: HttpServletRequest
session: HttpSession
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
request, response

四个作用域

pageContext
request
session
application

作用域,就是这个对象可以在哪用,对象可以存值,取值范围限定. 作用的对象是不一样的

setAttribute
getAttribute
pageContext:作用域只能在当前页面,PageContext

request:作用域限于一次请求
只要服务器做出反应,域中的值就没有了HttpServletRequest

session:限于一次会话,第二次会话就没了,HttpSession

application:都有,都可以访问,只有服务器关闭后就不能访问了.->ServletContext
一个工程只能有一个
exception -> Throwable
config -> ServletConfig
page -> Object -> 当前类的实例

response  -> HttpServletResponse
out JSP -> JSPWriter

效果

out
response.getWriter

out对象输出的内容是放到response的缓冲区内的,先输出response本身的内容,然后才是out里面的内容.

exception -> Throwable
page -> Object -> 一般就是jsp翻译成java类的实例对象 -> this -> 当前实例类
config -> ServletConfig
out -> JspWriter
response -> HttpServletResponse
pageContext -> PageContext: 作用域当前页面

request -> HttpServletReques: 作用域限于一次请求

session -> HttpSession -> 作用域限于一次会话

application -> ServletContext

整个工程可以访问,服务器关闭后就不能进行访问了
pageContext 也可以获取其他8个内置对象

EL表达式:

是什么,怎么用,也有内置对象?

// 作用域
pageScope
requestScope
sessionScope
applicationScope
// 请求头
header
headerValues
参数
param
params

EL表达式

简化jspjava的代码.

${ 表达式 }

取值方式:

<%
String [] a = {"aa","bb","cc","dd"};
pageContext.setAttribute("array", a);
%>

<%
 User user = new User {"zhangsan",18};
 session.setAttribute("u", user);
%>

${u.name}, ${u.age}
<%@page import="com.dashucoding.domain.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    从域中取值。  得先存值。
    <%
        //pageContext.setAttribute("name", "zhangsan");
        session.setAttribute("name", "lisi...");
    %>
    
    <br>直接指定说了,到这个作用域里面去找这个name<br>
    ${ pageScope.name } 
    
    
    <br>//先从page里面找,没有去request找,去session,去application <br>
    ${ name }
    
    <br>指定从session中取值<br>
    ${ sessionScope.name } 

<br>---------------------------------------------<br>

    <%
        User user = new User("zhangsan",18);
        
        session.setAttribute("u", user);
    %>
    
    
    ${ u.name }  , ${ u.age } 
    
    ${ a > b}
    
    ${ a gt b }
    
    ${ empty u }
</body>
</html>
package com.dashucoding.domain;

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

}
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        pageContext.setAttribute("name", "page");
        request.setAttribute("name", "request");
        session.setAttribute("name", "session");
        application.setAttribute("name", "application");
    %>
    
    按普通手段取值<br>
    
    <%= pageContext.getAttribute("name")%>
    <%= request.getAttribute("name")%>
    <%= session.getAttribute("name")%>
    <%= application.getAttribute("name")%>
    
    <br>使用EL表达式取出作用域中的值<br>
    
    ${ pageScope.name }
    ${ requestScope.name }
    ${ sessionScope.name }
    ${ applicationScope.name }
    
    ${name }
    
    
    <br>-----------------------------<br>
    
    <%
        String [] a = {"aa","bb","cc","dd"};
        pageContext.setAttribute("array", a);
    %>
    
    使用EL表达式取出作用域中数组的值<br>
    
    ${array[0] } , ${array[1] },${array[2] },${array[3] }
    
    
        <br>-------------集合数据----------------<br>
    
    <%
        List list = new ArrayList();
        list.add("11");
        list.add("22");
        list.add("33");
        list.add("44");
        //pageContext.setAttribute("li", list);
        session.setAttribute("li", list);
    %>
    
    使用EL表达式取出作用域中集合的值<br>
    
    ${li[0] } , ${li[1] },${li[2] },${li[7] }
    
    <br>-------------Map数据----------------<br>
    <%
        Map map = new HashMap();
        map.put("name", "zhangsna");
        map.put("age",18);
        map.put("address","北京..");
        
        map.put("address.aa","深圳..");
        
    
        //pageContext.setAttribute("map", map);
        application.setAttribute("m", map);
    %>
    使用EL表达式取出作用域中Map的值<br>
    
    ${applicationScope.m.name } , ${m.age } , ${m.address }  , ${m["address.aa"] } 


</body>
</html>

EL表达式隐式对象

11个内置对象

${ }
pageCotext

pageScope
requestScope
sessionScope
applicationScope
请求参数
param
paramValues
请求头
header
headerValues
cookie
initParam初始化参数
pageContext是PageContext实例,其他都是Map类.

EL内置对象

// 作用域
pageScope
requestScope
sessionScope
applicationScope
// 请求头
header
headerValues
// 请求参数
param
params

cookie
全局初始化参数
initparam
pageContext

引入

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是el03页面

<jsp:forward page="el04.jsp">
    <jsp:param value="beijing...." name="address"/>
</jsp:forward>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是el04页面<br>

<%=request.getParameter("address") %>

<br>

使用EL表达式获取这个参数

<%-- response.addCookie(new Cookie("name","value"));

${cookie.name } --%>
${param.address }
</body>
</html>

小结案例

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<%-- <%@ include file="other02.jsp"%> --%>

<%--  <%@ taglib prefix=""  uri=""%>    --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- <jsp:include page="other02.jsp"></jsp:include> --%>

    这是other页面的内容.
</body>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <h3>这是other022222的内容</h3>
    
    <br>收到的参数是:<br>
    
    <%= request.getParameter("address")%>
    
    <%
        
    %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是other03的页面
<br>使用作用域来存储数据<br>

<%
    pageContext.setAttribute("name", "page");
    request.setAttribute("name", "request");
    session.setAttribute("name", "session");
    application.setAttribute("name", "application");
%>

取出四个作用域中的值<br>

<%=pageContext.getAttribute("name")%>
<%=request.getAttribute("name")%>
<%=session.getAttribute("name")%>
<%=application.getAttribute("name")%>

<!-- //跳转到下一个界面去了 -->

<%
    //请求转发. 一次请求
    //request.getRequestDispatcher("other04.jsp").forward(request, response);

    //重定向 2次请求
    response.sendRedirect("other04.jsp");
    
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h3>这是04的页面</h3><br>
    
    取出四个作用域中的值<br>

    <%=pageContext.getAttribute("name")%>
    <%=request.getAttribute("name")%>
    <%=session.getAttribute("name")%>
    <%=application.getAttribute("name")%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是other05的页面<br>

<%
    out.write("这是使用out对象输出的内容");
%>

<br>
<%
    response.getWriter().write("这是使用response对象输出的内容");
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- 
    <jsp:include page=""></jsp:include>
    <jsp:param value="" name=""/>
    <jsp:forward page=""></jsp:forward> --%>
        这是jsp_action的页面.
    <%-- <jsp:include page="other02.jsp"></jsp:include> --%>
    
    <%-- <jsp:forward page="other02.jsp"></jsp:forward>
    等同于以下代码 --%>
    <% 
        //请求转发
        //request.getRequestDispatcher("other02.jsp").forward(request, response);
    %>  
    
    <jsp:forward page="other02.jsp">
        <jsp:param value="beijing" name="address"/>
    </jsp:forward>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
服务器正在维护,请稍后访问..
<%-- <%=exception.toString() %> --%>
</body>
</html>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        pageContext.setAttribute("name", "page");
        request.setAttribute("name", "request");
        session.setAttribute("name", "session");
        application.setAttribute("name", "application");
    %>
    
    按普通手段取值<br>
    
    <%= pageContext.getAttribute("name")%>
    <%= request.getAttribute("name")%>
    <%= session.getAttribute("name")%>
    <%= application.getAttribute("name")%>
    
    <br>使用EL表达式取出作用域中的值<br>
    
    ${ pageScope.name }
    ${ requestScope.name }
    ${ sessionScope.name }
    ${ applicationScope.name }
    
    ${name }
    
    
    <br>-----------------------------<br>
    
    <%
        String [] a = {"aa","bb","cc","dd"};
        pageContext.setAttribute("array", a);
    %>
    
    使用EL表达式取出作用域中数组的值<br>
    
    ${array[0] } , ${array[1] },${array[2] },${array[3] }
    
    
        <br>-------------集合数据----------------<br>
    
    <%
        List list = new ArrayList();
        list.add("11");
        list.add("22");
        list.add("33");
        list.add("44");
        //pageContext.setAttribute("li", list);
        session.setAttribute("li", list);
    %>
    
    使用EL表达式取出作用域中集合的值<br>
    
    ${li[0] } , ${li[1] },${li[2] },${li[7] }
    
    <br>-------------Map数据----------------<br>
    <%
        Map map = new HashMap();
        map.put("name", "zhangsna");
        map.put("age",18);
        map.put("address","北京..");
        
        map.put("address.aa","深圳..");
        
    
        //pageContext.setAttribute("map", map);
        application.setAttribute("m", map);
    %>
    使用EL表达式取出作用域中Map的值<br>
    
    ${applicationScope.m.name } , ${m.age } , ${m.address }  , ${m["address.aa"] } 


</body>
</html>

JSTL介绍

jstl是什么,用来做什么.
el只能取值操作
jstl遍历的效果
jstl. jsp standard tag library jsp标签库
简化jsp,与el表达式配合
// 使用jstl
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

效果

效果

效果

<c:set var = "name" value="dashu"></c:set>
${name}
<c:set var = "name" value="dashu" scope="session"></c:set>
${sessionScope.name}
默认存储的是page

<c:set var = "age" value="12" ></c:set>
<c:if text="${age>10}">
 age大于10
</c:if>

<c:forEach begin="1" end="10" var="i" step="2">
 ${i}
</c:forEach>

效果

学生信息管理系统

login.jsp -> 一个页面
login_servlet -> 一个页面
基本操作页面 -> 查看学生列表
stu_list.jsp
获取信息
查询数据库
判断账号信息
正确前往下一页
错误,登录失败

案例:

效果

效果

package com.dashucoding.dao;

import java.util.List;

import com.dashucoding.domain.Student;

public interface StuDao {
    /**
     * 查询出来所有的学生信息
     * @return List集合
     */
    List<Student> findAll();
}
package com.dashucoding.dao;
/*
 * 定义
 * 该Dao定义了对用户表的访问规则
 * */
public interface UserDao {

    /**
     * 这里简单就返回一个Boolean类型, 成功或者失败即可。
     * 
     * 但是开发的时候,登录的方法,一旦成功。这里应该返回该用户的个人信息
     * @param userName 
     * @param password
     * 
     * @return true : 登录成功, false : 登录失败。
     */
    boolean login(String userName , String password);
}
package com.dashucoding.dao.impl;

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.dashucoding.dao.StuDao;
import com.dashucoding.domain.Student;
import com.dashucoding.util.JDBCUtil;

public class StuDaoImpl implements StuDao{

    @Override
    public List<Student> findAll() {
        
        List<Student> list = new ArrayList<Student>();
        
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs   = null;
        
        try {
            //1. 得到连接对象
            conn = JDBCUtil.getConn();
            
            String sql = "select * from t_stu";
            
            ps = conn.prepareStatement(sql);
            
            rs = ps.executeQuery();
            
            
            
            //数据多了,用对象装, 对象也多了呢? 用集合装。 
            while(rs.next()){ //10 次 ,10个学生
                
                Student stu = new Student();
                
                stu.setId(rs.getInt("id"));
                stu.setAge(rs.getInt("age"));
                stu.setName(rs.getString("name"));
                stu.setGender(rs.getString("gender"));
                stu.setAddress(rs.getString("address"));
                
                list.add(stu);
                
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.release(conn, ps, rs);
        }
        
        return list;
    }

}
package com.dashucoding.dao.impl;

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

import com.dashucoding.dao.UserDao;
import com.dashucoding.util.JDBCUtil;

public class UserDaoImpl implements UserDao {

    @Override
    public boolean login(String userName , String password) {
        
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs   = null;
        try {
            //1. 得到连接对象
            conn = JDBCUtil.getConn();
            
            String sql = "select * from t_user where username=? and password=?";
            
            //2. 创建ps对象
            ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            ps.setString(2, password);
            
            
            //3. 开始执行。
            rs = ps.executeQuery();
            
            //如果能够成功移到下一条记录,那么表明有这个用户。 
            return rs.next();
            
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.release(conn, ps, rs);
        }
        return false;
    }

}
package com.dashucoding.domain;

public class Student {
    private int id ; 
    private String name;
    private int age ;
    private String gender;
    private String address;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}
package com.dashucoding.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashucoding.dao.StuDao;
import com.dashucoding.dao.UserDao;
import com.dashucoding.dao.impl.StuDaoImpl;
import com.dashucoding.dao.impl.UserDaoImpl;
import com.dashucoding.domain.Student;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 提交的数据有可能有中文
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取客户端提交的信息
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        // 去访问dao , 看看是否满足登录
        UserDao dao = new UserDaoImpl();
        boolean isSuccess = dao.login(userName, password);

        if (isSuccess) {
//          response.getWriter().write("登录成功.");
            // 请求转发
            // 查询所有的学生信息
            StuDao stuDao = new StuDaoImpl();
            List<Student> list = stuDao.findAll();
            
            // 先把这个集合存到作用域
            request.getSession().setAttribute("list", list);
            
            
            
            
            
            // 重定向
            response.sendRedirect("stu_list.jsp");
        } else {
            response.getWriter().write("用户名或者密码错误!");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
package com.dashucoding.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
    
    static String driverClass = null;
    static String url = null;
    static String name = null;
    static String password= null;
    
    static{
        try {
            //1. 创建一个属性配置对象
            Properties properties = new Properties();
//          InputStream is = new FileInputStream("jdbc.properties");
            
            
            //使用类加载器,去读取src底下的资源文件。 后面在servlet
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //导入输入流。
            properties.load(is);
            
            //读取属性
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            name = properties.getProperty("name");
            password = properties.getProperty("password");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取连接对象
     * @return
     */
    public static Connection getConn(){
        Connection conn = null;
        try {
            Class.forName(driverClass);
            //静态代码块 ---> 类加载了,就执行。 java.sql.DriverManager.registerDriver(new Driver());
            //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb");
            //2. 建立连接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。
            conn = DriverManager.getConnection(url, name, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    /**
     * 释放资源
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn , Statement st , ResultSet rs){
        closeRs(rs);
        closeSt(st);
        closeConn(conn);
    }
    public static void release(Connection conn , Statement st){
        closeSt(st);
        closeConn(conn);
    }

    
    private static void closeRs(ResultSet rs){
        try {
            if(rs != null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            rs = null;
        }
    }
    
    private static void closeSt(Statement st){
        try {
            if(st != null){
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            st = null;
        }
    }
    
    private static void closeConn(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            conn = null;
        }
    }
}

效果

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>欢迎学生管理系统</h2>
    
    <form action="LoginServlet" method="post">
        账号: <input type="text" name="username" /><br>
        密码: <input type="password" name="password" /><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息管理系统</title>
</head>
<body>
<br>学生列表<br>
    <table border="1" width="700">
        <tr align="center">
            <td>编号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
            <td>住址</td>
            <td>操作</td>
        </tr>
        
        <c:forEach items="${list}" var="stu">
        
            <c:if test=""></c:if>
            
            <tr align="center">
                <td>${stu.id }</td>
                <td>${stu.name }</td>
                <td>${stu.age }</td>
                <td>${stu.gender }</td>
                <td>${stu.address }</td>
                <td><a href="#">更新</a>   <a href="#">删除</a></td>
            </tr>
        </c:forEach>
        
    </table>
</body>
</html>

分析

login.jsp -> LoginServlet -> 获取登录信息
创建用户表, 
创建UserDao
创建UserDaoImple
LoginServlet里面访问UserDao,判断登录,
创建stu_list.jsp,让登录进入
创建学生表
定义Dao,StuDao
StuDao, StuDaoImpl

数据库

效果

效果

小结

效果

jsp

效果

JSP -> 九个内置对象
page
include
taglib
<jsp:include>
<jsp:forward>
<jsp:param>


EL -> 11个内置对象

${ 表达式 }
取4个作用域中的值
    pageContext

    pageScope
    requestScope
    sessionScope
    applicationScope
    
    header
    headerValues
    
    param
    paramValues
    
    cookie
    initParam

JSTL

<c:set>
<c:if>
<c:forEach>

如果看了觉得不错

点赞!转发!

达叔小生:往后余生,唯独有你 You and me, we are family ! 90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通 简书博客: 达叔小生 https://www.jianshu.com/u/c785ece603d1

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券