jsp入门:

如何在jsp中插入java脚本:

<% java代码%>:方法体里面可以有什么这里面就能放什么。(常用)

<%=变量%>:sysout();输出语句中可以放什么,这里面就能放什么,常用来显示变量(常用)

<%! %>:类里面可以放什么这里面就能放什么,但是不准使用,(过时了)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
/*java 代码片段
*/
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%--JSP是由HTML+JAVA代码+标签(命令)组成的,
实现了Servlet接口的一个Servlet体系类,由服务器编译创
建对象,调用service()方法,其本质就是一个Servlet;
JSP是用来发送超链接或者表单请求的页面,servlet处理数据
,同时将结果转发回JSP页面 --%>
<!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>
   <h3>计算器网页版:</h3><br>
   <form action="/day_11/AddServlet"method="post">
       <table  align="center" width="60%">
   <%
   int x=0;
   for(int i =x;i<3;i++){
   %>
       <tr>
       <%
       int y = 0;
       for(int j =x;j<x+3;j++){
       %>
       <td><input type="button" value="<%=j %>" name="num_<%=j %>"></td>
       <% 
       y=j;}x=y+1;
       %>
       </tr>
       <%
   } 
       %>
       <tr><td><input type="button" value="9"/></td></tr>
       </table>
       <br/><hr/>
       <input type="button" value="+" name="add"/>
       <input type="button" value="-" name="sub"/>
       <input type="button" value="*" name="mul"/>
       <input type="button" value="/" name="div"/>
       <input type="submit" value="=" />
       <br/><hr/>
       result:<input type="text" name="value"/>
       <hr/>
   </form>
  </body>
</html>

使用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 'add.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>
    This is my JSP page. <br>
    <form action="/day_11/AddServlet" method="post">
        数字A:<input type="text" name="num1" value="123"/><br/>
        数字B:<input type="text" name="num2" value="456"/><br/>
        <input type="submit" value="提交"/>
    </form>
  </body>
</html>
package cn.Jsp.wyx;

import java.io.IOException;
import java.util.Enumeration;

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

public class AddServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            String value1 = request.getParameter("num1");
            String value2 = request.getParameter("num2");
            int A = Integer.parseInt(value1);
            int B = Integer.parseInt(value2);
            request.setAttribute("result", A+B);
            request.getRequestDispatcher("/result.jsp").forward(request, response);
    }

}
<%@ 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 'result.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>
    This is my JSP page. <br>
    <% 
    Integer result = (Integer)request.getAttribute("result");
    %>
    <input type="text" name="result" value="<%=result %>"/>
  </body>
</html>

jsp页面提供了表单,servlet拿到表单数据进行处理并将处理后的结果发送给另一个显示结果的jsp页面;

Cookie介绍:

package cn.Cookie.wyx;

import java.io.IOException;

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

public class ACookieServlet extends HttpServlet {

    /**
     * Cookie 三大元素:
     * 1、生命周期:setMaxAge(60*60*24)通过此方法设置
     * 2、路径:可以通过浏览器安全选项查看,也可以设置setPath(uri),
     * JSESSIONID默认保存在项目路径下,浏览器通过判断访问者的URL是否
     * 包含cookie路径,来判断给服务端发送哪些cookie。
     * (只有包含cookie路径的URL客户端才会发送这个cookie给服务端)
     * 3、cookie保存机制:保存于客户端
     */
    private static final long serialVersionUID = 1L;
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            Cookie cookie = new Cookie("aaa", "AAA");
            cookie.setPath("/day_11/");//uri路径
            cookie.setMaxAge(60*60*24);//24小时
            response.addCookie(cookie);//向客户端发送一个Cookie
    }

}
package cn.Cookie.wyx;

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

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

public class BCookieServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            Cookie[] cookies = request.getCookies();
            if(cookies!=null){
                for (int i = 0; i < cookies.length; i++) {
                    String name = cookies[i].getName();
                    String value = cookies[i].getValue();
                    System.out.println("cookieName:"+name+"cookieValue:"+value);
                }
            }
    }

}
<%@page import="java.net.CookieStore"%>
<%@ 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 'cookie.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>
    This is my JSP page. <br>
    <%
    /*
        jsp中九大内置对象,默认初始化了HttpSession对象,当调用getSeesion()时,就会创建一个叫JSESSIONID的Cookie;
    */
    Cookie[]cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie c:cookies){
                String value = c.getValue();
                out.print(value+"<br/>");
            }
        }
    %>
  
  </body>
</html>

当用户访问第一个servlet时,response对象会向客户端发送一个Cookie,并保存在本地磁盘24小时;访问第二个servlet时取出Cookie;因为cookie.jsp路径包含Cookie的路径,

所以在访问cookie.jsp时,也会带着上一次保存的cookie,同时jsp内置session对象,一定调用了request.getSession()方法,没有发现JSESSIONID,同时创建这个cookie;

第二次访问cookie.jsp的时候,就会读取到两个cookie;

 

HttpSession:

package cn.HttpSession.wyx;

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;

public class HttpSessionTest extends HttpServlet {

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

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * 获取session,
         * session原理:
         * session底层依赖Cookie或者URL重写,当调用request.getSession(),服务器会进行判断;
         * 首先会去拿一个叫JSESSIONID的Cookie;没有这个Cookie,会去URL中拿一个JSESSIONID的参数;
         * 如果拿到,会去服务器中找是否有对应的session信息,
         * 如果没有会创建一个新的session,并将JSESSIONID保存到cookie中。
         * 如果有会直接得到session,不创建;
         * 
         * */
            HttpSession session = request.getSession();
            //获取JSESSIONID
            String JSESSIONID = session.getId();
            //向session中保存数据,session域在一个会话中;
            session.setAttribute("sessionValue","hello");
    }

}
package cn.HttpSession.wyx;

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;

public class HttpSessionTest2 extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            HttpSession session = request.getSession();
            /*
             * 取出session域中数据;
             * Servlet中三大域:
             * request(作用域为一个请求内)
             * session(作用域为一个会话内)
             * ServletContext(作用域为整个项目,只要不关闭TOMCAT,它就一直在)
             * */
            String sessionValue = (String)session.getAttribute("sessionValue");
            System.out.println(sessionValue);
    }

}
<%@ 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 'EncodeURL.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>
    <a href="/day_11/HttpSessionTest;JSESSIONID=<%=session.getId()%>">URL重写测试</a>
    <%
    //他会查看cookie是否存在,如果不存在,在指定的url后添加JSESSIONID参数,如果存在,它就不会添加;
    //在每个url后面都加上这段代码response.encodeURL("uri路径"),就自动实现了url重写;
    out.print(response.encodeURL("/day_11/HttpSessionTest"));
    %>
  </body>
</html>

登录>servlet校验>登录成功:

这个功能可以熟练应用request、session、Cookie;

HttpSession  request.getSession(); 从request对象中得到session

Cookie[]  request.getCookies(); 从request对象中得到cookie

response.addCookie(Cookie cookie); 向客户端保存一个cookie

1、提供登录页面,form,错误信息收集及显示;

<%@ 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 'Login.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>
    This is my JSP page. <br>
    <%
//为了避免第一次访问网页出现显示null的现象,所以创建这个变量;
String errormsg =""; %> <% String msg = (String)request.getAttribute("msg"); if(msg!=null){ errormsg=msg; } %> <% /* 获取cookie中的值; */ String uname = ""; Cookie[]cookies=request.getCookies(); for(Cookie c:cookies){ if(c.getName().equalsIgnoreCase("username")){ uname=c.getValue(); } } %> <font color="red"><b><%=errormsg %></b></font> <form action="/day_11/LoginServlet" method="post"> 用户名:<input type="text" name="username"value = "<%=uname %>"/><br> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> </body> </html>

2、创建servlet处理数据,重定向和转发请求(业务逻辑)

package cn.login.wyx;

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

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

public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("UTF-8");
            String username = request.getParameter("username");
            //将username保存到Cookie中
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60*60*24);
            //发送Cookie给客户端
            response.addCookie(cookie); 
            //request.getParameter("password");
            if(!username.equals("wangyinxu")){
                //获取session
                HttpSession session = request.getSession();
                //将用户名存储到session域
                session.setAttribute("username", username);
                //重定向到成功页面
                response.sendRedirect("/day_11/succ1.jsp");
            }else {
                //保存错误信息到request
                request.setAttribute("msg", "用户名不存在");
                //转发到login.jsp
                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            }
    }

}

3、登录成功页面

<%@ 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 'succ1.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 username = (String)session.getAttribute("username");
   if(username==null){
       request.setAttribute("msg", "请先登录");
       request.getRequestDispatcher("/Login.jsp").forward(request, response);
       return;
   }
   %>
   <font color="gray">欢迎-<%=username %>-登录:</font>
  </body>
</html>