JavaWeb四种属性范围(作用域)

四种属性范围

举例说明

写一个Servlet项目

文档结构

HelloServlet类

package fdw;

import java.io.IOException;

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

//使用注解进行Servlet注册
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
    //注意线程安全
	private UserService userservice = new UserService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.获得请求参数
		String name = req.getParameter("name");
		//2.调用业务方法
		boolean b = userservice.valid(name);
		//3.根据业务方法返回值决定跳转页面
		if(b) {
			//跳转到成功页面,使用服务器端跳转
			req.setAttribute("name", name);
			req.getRequestDispatcher("/succ.jsp").forward(req, resp);
			
		}else {
			//跳转到失败页面,使用客户端跳转
		req.getSession().setAttribute("name", name);
			resp.sendRedirect(req.getContextPath()+"/fail.jsp");
			
		}
	}

	
}

UserService类

package fdw;

public class UserService {

	public boolean valid(String name) {
		return "admin".equals(name);
	}
}

fail.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
     账号不正确,${name}
</body>
</html>

succ.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> 
                               欢迎您,${name}
</body> 
</html>

启动tomcat,在浏览器中访问http://localhost:8080/web1115/hello?name=admin

这是服务器端跳转

若访问http://localhost:8080/web1115/hello?name=abc

客户端跳转,要跑两趟

这种方式是错的,客户端跳转(不能使用request对象传递数据),要用Session对象 

这种是对的,用Session

这样就能得到数据abc了,原因是因为作用域不同。

 

 

jsp中两种方式


三种作用域测试(分别在服务器端和客户端跳转)

访问hello?name=admin

访问hello?name=admin123

虽然session好,但负担重,尽量不要用

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThatMonth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值