续day170704:

day170704中简单的提到了servlet,其实jsp页面也是servlet:

JSP

  • JSP介绍: JSP全称Java Server Pages,是一种动态网页开发技术。它使用JSP标签在HTML网页中插入Java代码。标签通常以<%开头以%>结束。

  • JSP是一种Java servlet,主要用于实现Java web应用程序的用户界面部分。网页开发者们通过结合HTML代码、XHTML代码、XML元素以及嵌入JSP操作和命令来编写JSP。

  • JSP通过网页表单获取用户输入数据、访问数据库及其他数据源,然后动态地创建网页。

  • JSP标签有多种功能,比如访问数据库、记录用户选择信息、访问JavaBeans组件等,还可以在不同的网页中传递控制信息和共享信息。

JSP生命周期

  • 编译阶段:
    • servlet容器编译servlet源文件,生成servlet类
  • 初始化阶段:
    • 加载与JSP对应的servlet类,创建其实例,并调用它的初始化方法
  • 执行阶段:
    • 调用与JSP对应的servlet实例的服务方法
  • 销毁阶段:
    • 调用与JSP对应的servlet实例的销毁方法,然后销毁servlet实例
/*容器载入JSP文件后,它会在为请求提供任何服务前调用jspInit()方法。如果您需要执行自定义的JSP初始化任务,复写jspInit()方法就行了*/
public void Init(){
  // 初始化代码
}
/*当JSP网页完成初始化后,JSP引擎将会调用_jspService()方法*/
void _jspService(HttpServletRequest request,
                 HttpServletResponse response)
{
   // 服务端处理代码
}
/*jspDestroy()方法在JSP中等价于servlet中的销毁方法。当您需要执行任何清理工作时复写jspDestroy()方法,比如释放数据库连接或者关闭文件夹等等*/
public void Destroy()
{
   // 清理代码
}

JSP是一种脚本语言:

  • 脚本程序可以包含任意量的Java语句、变量、方法或表达式,只要它们在脚本语言中是有效的。
/*变量的声明*/
<% int num=5 %>
<%= num %>//输出变量在页面

examp:

<html>
    <head><title>Hello World</title></head>
    <body>
        Hello World!<br/>
    <%
        String str="欢迎来到小M开发"; 
        out.println(str);
     %>
    </body>
</html>

运行结果(tomcat服务器上运行):

这里写图片描述

JSP 页面重定向

  • 当需要将文档移动到一个新的位置时,就需要使用JSP重定向了。
    最简单的重定向方式就是使用response对象的sendRedirect()方法
/*我们这个里举一个例子,我们建立一个Servlet验证用户表单输入,如果成功我们跳转到successful,jsp,失败就跳转到百度*/
/*ChangeServlet类*/
package com.yy.servlet.web.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 com.yy.servlet.dao.UserDao;
import com.yy.servlet.po.User;

public class ChangeServlet  extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

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

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        /*设置接受请求和响应的字符集*/
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        /*是设置响应类型为text/html,获得out对象,就是PrintWriter打印流,向html页面输入内容*/
        response.setContentType("text/html");
        /*接受页面提交来的数据*/
        String username=request.getParameter("username");
        String userpwd=request.getParameter("userpwd");

        /*设置编码集*/
        username=new String(username.getBytes("ISO-8859-1"), "UTF-8");
        userpwd=new String(userpwd.getBytes("ISO-8859-1"), "UTF-8");
        /*想html页面输入内容*/
    //  PrintWriter out= new PrintWriter(response.getWriter());
        /*创建数据库的连接并调用查询方法*/
        User user=UserDao.getInstance().isLogin(username, userpwd);

        if(user!=null){
            response.sendRedirect("/ServletForWord/successful.jsp");
            return;
        }else{
            /**网页重定项 url会变成对应的url*/
            response.sendRedirect("http://www.baidu.com");
            return;
        }



    }

}
<!--这个是login_test.jsp-->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
    <base href="<%=basePath%>">

    <title>My JSP 'index.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">
    -->
    <script>
    var password=0;
        function  showName(){ /*判断用户输入的名字是否为空*/

                var name=document.getElementById("name").value;
                //name=trim(name);
                if(name==""){

                    document.getElementById("nameFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>你输入的名字为空</div>";
                }else{
                    document.getElementById("nameFont").innerHTML="<img src ='image/right.jpg'/>";
                }
        }

            function  showPwd(){ /*判断用户输入的密码是否为空*/

                var pwd=document.getElementById("pwd").value;
                //name=trim(name);
                if(pwd==""){

                    document.getElementById("pwdFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>你输入的密码为空</div>";
                }else if(pwd.lenght>8&&pwd.lenght<16){
                    document.getElementById("pwdFont").innerHTML="<img src ='image/wrong.jpg' style='margin-top:0px;'/><div style='color:red;margin-top:-19px;font-size:10px;margin-left:30px;'>密码需要在8-16位</div>";
                }else{
                    document.getElementById("pwdFont").innerHTML="<img src ='image/right.jpg'/>";

                }
        }

    </script>  
  </head>

  <body> 
    <center>
    <h1 style ="color:red;font-size:60px">用户登录</h1>
    </center>
    <hr></hr>
   <!--提交给change-->
    <form action="change" method="get">
    <table cellpadding="5">
        <tr>
            <td><span>NAME:</span></td>
            <td ><input style="width:200px" type="text" value="youe name" name="username" id="name" onfocus="showName()"  onblur="showName()"/></td>
            <td id="nameFont"></td>
         </tr>

            <td><span>PWD:</span></td>
            <td><input style="width:200px" type="password" value="888"  name="userpwd" id="pwd" onfocus="showPwd()"  onblur="showPwd()"/></td>
            <td id="pwdFont"></td>
        </tr>       
        <tr>
            <td>
                <input type="submit" value="登录" />
            </td>
            <td>
            </td>   
        </tr>

    </table>
     <hr></hr>
    </form>
  </body>
</html>

<!--web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.yy.servlet.web.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <!--配置验证用户登录逻辑判断的LoginServlet类-->
    <servlet>
        <servlet-name>ChangeServlet</servlet-name>
        <servlet-class>com.yy.servlet.web.servlet.ChangeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ChangeServlet</servlet-name>
        <url-pattern>/change</url-pattern>
    </servlet-mapping>
  <welcome-file-list>
    <welcome-file>fail.jsp</welcome-file>
  </welcome-file-list>
</web-app>
/*这个是successful.jsp*/
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
    <base href="<%=basePath%>">

    <title>My JSP 'index.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>
    <span style="font-size:55px;color:red">${username} 登录成功!</span>
  </body>
</html>

运行结果(tomcat服务器上运行):
login_test.jsp
login_test.jsp

登陆成功

登陆成功

登录失败(跳转到百度)

这里写图片描述


request.getRequestDispatcher(“url”).forward(request, response)跳转

现在我们把ChangeServlet类换成LoginServlet ,把login_test.jsp的action=”login” ,successful.jsp不变

/*这个是LoginServlet 类 */
package com.yy.servlet.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.yy.servlet.dao.UserDao;
import com.yy.servlet.po.User;

public class LoginServlet  extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            /*设置接受请求和响应的字符集*/
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            /*是设置响应类型为text/html,获得out对象,就是PrintWriter打印流,向html页面输入内容*/
            response.setContentType("text/html");
            /*接受页面提交来的数据*/
            String username=request.getParameter("username");
            String userpwd=request.getParameter("userpwd");

            /*设置编码集*/
            username=new String(username.getBytes("ISO-8859-1"), "UTF-8");
            userpwd=new String(userpwd.getBytes("ISO-8859-1"), "UTF-8");
            /*想html页面输入内容*/
        //  PrintWriter out= new PrintWriter(response.getWriter());
            /*创建数据库的连接并调用查询方法*/
            User user=UserDao.getInstance().isLogin(username, userpwd);

            if(user!=null){
                request.setAttribute("username", username);
                request.getRequestDispatcher("/successful.jsp").forward(request, response);
                return;
            }else{
                /**指定跳转到regist.jsp的页面(内部跳转,不能跳转到其他外部网址)*/
                request.setAttribute("username", username);
                request.getRequestDispatcher("/fail.jsp").forward(request, response);
                return;
            }

    }

}
/*这里我们在加一个fail.jsp*/
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
    <base href="<%=basePath%>">

    <title>My JSP 'index.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>
      <span style="font-size:55px;color:red">${username}登录失败!</span>

  </body>
</html>

运行结果(tomcat服务器上运行):
login_test.jsp
login_test.jsp

登录成功

登录成功

登录失败
登录失败


注意:

  • response.sendRedirect(“url”):url会变成对应的跳转去的url,可以跳转到项目外的网页
  • request.getRequestDispatcher(“url”).forward(request, response):指定跳转到某个的页面,但是url会显示为跳转页面的Servlet类url(内部跳转,不能跳转到其他外部网址)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐