2.JavaWeb复习 之servlet和jsp之间传值问题

本文详细介绍了在JavaWeb中如何通过Servlet接收并传递参数到JSP页面,包括使用RequestParam获取GET/POST参数,通过setAttribute在请求范围内传递数据,以及在JSP页面中使用EL表达式或脚本let取出并显示这些值。
继上次的servlet访问,,,现在来说说servlet和jsp(或html)页面的交互(不明白纯servle(不引用任何第三方jar包)访问如何实现可以查看  JavaWeb 复习之servlet  或者自行百度 )
1.servlet接收参数:
   在doGet或者doPost 方法里面利用response 对象来获取对应的传递的参数值

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             String name = req.getParameter( "name" );
             String pwd = req.getParameter( "pwd" );
             System. out.println(name);
             System. out .println(pwd);
          }

这样就可以在控制台打印出通过getpost传递过来的值了

2.servlet跳转到指定的html页面,,并将指定的值传递到jsp页面
传值的话只需要将你要传递的值添加到resp对象中就行了,,在相对应的jsp页面中显示

protected void doGet(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
             String name = req.getParameter( "name" );
             String pwd = req.getParameter( "pwd" );
             System. out .println(name);
             System. out .println(pwd);
             req.setAttribute( "name" , name);
             req.setAttribute( "pwd" , pwd);
             ServletContext sc = getServletContext();
             RequestDispatcher rd = sc.getRequestDispatcher( "/index.jsp" ); // 跳转到WebRoot 下的index.jsp页面
             rd.forward(req, resp);
       }




3.servlet传出的name和pwd值在html中显示
(当然将servlet传入值并不是真的将值传入html中,而是传入到一个模版中,在这个模版中将传入的值在合适的位置显示出来后再讲整个html代码出入到前台页面,这就完成的servlet参数值的传出显示)
显示参数方法一:
用Java获取参数的方法,先获取参数值 :  <%String   pwd   =(String)request.getAttribute( "pwd");%>
         然后在合适的位置显示出来:<%=pwd %>
方法二:
利用el表达式来显示参数,,,(el表达式语法可以自行查找)
首先在页面的头部加上引用el表达式的标签:    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
然后利用el表达式语法直接获取值:   ${name  }

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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>
    This is my JSP page. <br>
<% String   pwd   =(String)request.getAttribute( "pwd"); %>
姓名:${name  }<br>
密码:<%=pwd %>  
</body>
</html>




===待续===


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值