JSP学习

JSP学习,第1张

JSP学习 JSP

JSP 本质上就是⼀个 Servlet,JSP 主要负责与⽤户交互,将最终的界⾯呈现给⽤户,
HTML+JS+CSS+Java 的混合⽂件。
当服务器接收到⼀个后缀是 jsp 的请求时,将该请求交给 JSP 引擎去处理,每⼀个 JSP ⻚⾯第⼀次被访
问的时候,JSP 引擎会将它翻译成⼀个 Servlet ⽂件,再由 Web 容器调⽤ Servlet 完成响应。
单纯从开发的⻆度看,JSP 就是在 HTML 中嵌⼊ Java 程序。

具体的嵌⼊⽅式有 3 种:
1、JSP 脚本,执⾏ Java 逻辑代码

<% Java代码 %>

2、JSP 声明:定义 Java ⽅法

<%!
 声明 Java ⽅法
%>

3、JSP 表达式:把 Java 对象直接输出到 HTML ⻚⾯中

<%=Java变量 %>
<%!
 public String test(){
 return "HelloWorld";
}
%>
<%
String str = test();
%>
<%=str%>

JSP内置对象 9 个

1、request:表示⼀次请求,HttpServletRequest。
2、response:表示⼀次响应,HttpServletResponse。
3、pageContext:⻚⾯上下⽂,获取⻚⾯信息,PageContext。
4、session:表示⼀次会话,保存⽤户信息,HttpSession。
5、application:表示当前 Web 应⽤,全局对象,保存所有⽤户共享信息,ServletContext。
6、config:当前 JSP 对应的 Servlet 的 ServletConfig 对象,获取当前 Servlet 的信息。
7、out:向浏览器输出数据,JspWriter。
8、page:当前 JSP 对应的 Servlet 对象,Servlet。
9、exception:表示 JSP ⻚⾯发⽣的异常,Exception。

常⽤的是 request、response、session、application、pageContext

request 常⽤⽅法:

1、String getParameter(String key) 获取客户端传来的参数。获取的String类型。

在窗口中传入参数:

http://localhost:8888/demo1/test?id=10&name=zhangsan

在doGet方法当中,获取参数,并进行输出:

@WebServlet("/test")
public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("GET");
        String str="Hello World";
        resp.getWriter().write(str);
        String id=req.getParameter("id");
        System.out.println(id);
        String name=req.getParameter("name");
        System.out.println(name);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("POST");
    }
}

控制台输出:

在jsp文件里面进行获取:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    测试


<%
    String id=request.getParameter("id");
    out.write(1);
    page.getClass();
    pageContext.getAttribute("id");
%>
<%=id%>


输入参数,并进行展示:

2、void setAttribute(String key,Object value) 通过键值对的形式保存数据。

3、Object getAttribute(String key) 通过 key 取出 value。

4、RequestDispatcher getRequestDispatcher(String path) 返回⼀个 RequestDispatcher 对象,该对
象的 forward ⽅法⽤于请求转发。
在浏览器和服务器之间传递参数是采用request.getParameter()方法获取,而在服务器内部的不同页面之间传递参数则是采用request.setAttribute();最后将test2.jsp页面返回给浏览器。

test.jsp页面代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    测试


<%
    String idStr=request.getParameter("id");
    Integer id=Integer.parseInt(idStr);
    id++;
    //将数据存入到request
    request.setAttribute("num",id);
    //将请求传递给test2.jsp
    request.getRequestDispatcher("test2.jsp").forward(request,response);
%>


test2.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    test2


test2

<%
    Integer num=(Integer)request.getAttribute("num");
%>
<%=num%>


在浏览器中输入参数id=10,在test.jsp中取出参数is=10,进行++ *** 作,然后再将参数传递给test2.jsp,在test2.jsp进行展示。

5、String[] getParameterValues() 获取客户端传来的多个同名参数。


<%
    String[] names=request.getParameterValues("name");
%>
<%=Arrays.toString(names)%>

显示数据:

6、void setCharacterEncoding(String charset) 指定每个请求的编码。

HTTP 请求状态码
200:正常

404:资源找不到

400:请求类型不匹配

500:Java 程序抛出异常

response 常⽤⽅法:
1、sendRedirect(String path) 重定向,⻚⾯之间的跳转。

转发 getRequestDispatcher 和重定向 sendRedirect 的区别:
转发是将同⼀个请求传给下⼀个⻚⾯,重定向是创建⼀个新的请求传给下⼀个⻚⾯,之前的请求结束⽣命周期。
转发:同⼀个请求在服务器之间传递,地址栏不变,也叫服务器跳转。
重定向:由客户端发送⼀次新的请求来访问跳转后的⽬标资源,地址栏改变,也叫客户端跳转。

如果两个⻚⾯之间需要通过 request 来传值,则必须使⽤转发,不能使⽤重定向。
⽤户登录,如果⽤户名和密码正确,则跳转到⾸⻚(转发),并且展示⽤户名,否则重新回到登陆⻚⾯
(重定向)
login.jsp


    

check.jsp


    <%
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        if(username.equals("admin")&&password.equals("123456")){
            //登录成功
            //必须用转发
            request.setAttribute("name",username);
            request.getRequestDispatcher("welcome.jsp").forward(request,response);
        }else{
            //登录失败,回到登录界面
            //既可以用转发,又可以用重定向
            response.sendRedirect("login.jsp");
        }
    %>

welcom.jsp

<%
    String name=(String)request.getAttribute("name");
%>
<%=name%>
Session

⽤户会话
服务器⽆法识别每⼀次 HTTP 请求的出处(不知道来⾃于哪个终端),它只会接受到⼀个请求信号,所
以就存在⼀个问题:将⽤户的响应发送给其他⼈,必须有⼀种技术来让服务器知道请求来⾃哪,这就是
会话技术。

会话:就是客户端和服务器之间发⽣的⼀系列连续的请求和响应的过程,打开浏览器进⾏ *** 作到关闭浏
览器的过程。
会话状态:指服务器和浏览器在会话过程中产⽣的状态信息,借助于会话状态,服务器能够把属于同⼀
次会话的⼀系列请求和响应关联起来。

实现会话有两种⽅式:
session
cookie
属于同⼀次会话的请求都有⼀个相同的标识符,sessionID.

session 常⽤的⽅法:

String getId() 获取 sessionID
void setMaxInactiveInterval(int interval) 设置 session 的失效时间,单位为秒
int getMaxInactiveInterval() 获取当前 session 的失效时间
void invalidate() 设置 session ⽴即失效
void setAttribute(String key,Object value) 通过键值对的形式来存储数据
Object getAttribute(String key) 通过键获取对应的数据
void removeAttribute(String key) 通过键删除对应的数据

只要浏览器不关闭,session都是同一个。
登录案例:

public class LoginServlet extends HttpServlet{
    String myusername;
    String mypassword;
//获取web.xml页面中配置的初始化密码和名字
    @Override
    public void init(ServletConfig config) throws ServletException {
        myusername=config.getInitParameter("username");
        mypassword=config.getInitParameter("password");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username.equals(myusername)&password.equals(mypassword)){
            HttpSession session=req.getSession();
            session.setAttribute("username",username);
            req.getRequestDispatcher("welcome.jsp").forward(req,resp);
        }else
            resp.sendRedirect("login.jsp");
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    login






<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


欢迎回来<%=session.getAttribute("username")%>




    
        login
        com.y.servlet.LoginServlet
        
            username
            admin
        
        
            password
            123456
        

    
    
        login

        /login
    

cookie

cookie 是服务端在 HTTP 响应中附带传给浏览器的⼀个⼩⽂本⽂件,⼀旦浏览器保存了某个 cookie,在之后的请求和响应过程中,会将此 cookie 来回传递,这样就可以通过 cookie 这个载体完成客户端和服务端的数据交互。

cookie是客户端存储,session是服务端存储的。当服务器关闭再重启,客户端的cookie是不会改变的。
在服务器端设置cookie:
cookie.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    cookie测试


<%
    cookie cookie=new cookie("name","zhangsan");//在服务端创建cookie对象,
    response.addcookie(cookie);//传递cookie

%>


执行login页面,观察此时请求中的cookie码:

再进入cookie.jsp页面进行,产生cookie:

再次进入login.jsp:

cookie是保留在浏览器中,服务器可以拿到cookie.

如何创建cookie?

 cookie cookie=new cookie("name","zhangsan");//在服务端创建cookie对象,
 response.addcookie(cookie);//传递cookie

注意response必须要写,才能将cookie(新的)响应给浏览器。

如何读取cookie?

 //读取cookie
    cookie[] cookies=request.getcookies();
    for(cookie cookie:cookies){ out.write(cookie.getName()+"
"); }

cookie 常⽤的⽅法
void setMaxAge(int age) 设置 cookie 的有效时间,单位为秒
int getMaxAge() 获取 cookie 的有效时间
String getName() 获取 cookie 的 name
String getValue() 获取 cookie 的 value

Session 和 cookie 的区别

session:
保存在服务器
保存的数据是 Object
会随着会话的结束⽽销毁
保存重要信息

cookie:
保存在浏览器
保存的数据是 String
可以⻓期保存在浏览器中,与会话⽆关
保存不重要信息

存储⽤户信息:
session:setAttribute(“name”,“admin”) 存
getAttribute(“name”) 取
⽣命周期:服务端:只要 WEB 应⽤重启就销毁,客户端:只要浏览器关闭就销毁。
退出登录:session.invalidate()

cookie:response.addcookie(new cookie(name,“admin”)) 存

cookie[] cookies = request.getcookies();
for (cookie cookie:cookies){
  if(cookie.getName().equals("name")){
  out.write("欢迎回来"+cookie.getValue());
  }
}


⽣命周期:不随服务端的重启⽽销毁,客户端:默认是只要关闭浏览器就销毁,我们通过 setMaxAge()⽅法设置有效期,⼀旦设置了有效期,则不随浏览器的关闭⽽销毁,⽽是由设置的时间来决定。
退出登录:setMaxAge(0)

使用cookie实现登录和退出:

@WebServlet("/cookielogin")
public class cookieServlet extends HttpServlet {
    String myusername="admin";
    String mypassword="123456";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username.equals(myusername)&password.equals(mypassword)){
            cookie cookie=new cookie("name",username);
            cookie.setMaxAge(7*24*60*60);//设置七天免登录
            resp.addcookie(cookie);
//            req.getRequestDispatcher("welcome.jsp").forward(req,resp);
            resp.sendRedirect("cookie_welcome.jsp");//已将数据存入session中,不需要在使用request
        }else
            resp.sendRedirect("cookie_login.jsp");
    }

}

登录界面:


welcome界面:

<%
    //读取cookie
    cookie[] cookies=request.getcookies();
    for(cookie cookie:cookies){
        if(cookie.getName().equals("name")) {
            out.write("欢迎回来"+cookie.getValue());
        }
    }

%>
退出登录

退出逻辑:

@WebServlet("/cookielogout")
public class cookielogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        cookie[] cookies=req.getcookies();
        for(cookie cookie:cookies){
            if(cookie.getName().equals("name")){
                cookie.setMaxAge(0);
                resp.addcookie(cookie);
                resp.sendRedirect("cookie_login.jsp");
            }
        }
    }
}
JSP 内置对象作⽤域

4个
page、request、session、application
setAttribute、getAttribute
page 作⽤域:对应的内置对象是 pageContext。
request 作⽤域:对应的内置对象是 request。
session 作⽤域:对应的内置对象是 session。
application 作⽤域:对应的内置对象是 application。
page < request < session < application
page 只在当前⻚⾯有效。
request 在⼀次请求内有效。
session 在⼀次会话内有效。
application 对应整个 WEB 应⽤的。

网站访问统计量:

<%
    Integer count = (Integer) application.getAttribute("count");
    if(count == null){
        count = 1;
        application.setAttribute("count",count);
    }else{
        count++;
        application.setAttribute("count",count);
    }
%>
您当前是第<%=count%>位访客

上述写法,在服务器关闭后,再打开服务器,count就会变0.如果想要count正常,可以将该值存放到数据库。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5712875.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存