读取web.xml参数,jsp动作指令,jsp页面发布xml或者pdf数据

读取web.xml参数
(1) 后台读取
import java.io.IOException;

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


public class TestServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("进入servlet");
		String servletName = this.getInitParameter("servletName");
		System.out.println(this.getServletContext().getInitParameter("userName"));
		System.out.println(servletName);
		resp.sendRedirect("index.jsp");
	}
}
import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


public class TestListner implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		String userName = arg0.getServletContext().getInitParameter("userName");
		arg0.getServletContext().setAttribute("Name", userName);
		System.out.println(userName);
		try {
			System.out.println(new InitialContext().lookup("java:comp/env/upload-path"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
(2) 页面读取包括el表达式读取
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="cn.bean.User"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%String path2 = application.getRealPath(
				"/imgs"); %>
<!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>
<%
List al = new ArrayList();
al.add("session1");
al.add("session2");
al.add("session3");
application.setAttribute("list",al);

User u = new User();
u.setUserName("tom");
application.setAttribute("user",u);

 %>
 <%
 List a = (List)application.getAttribute("list");
 a.add("session4");
 User u2 = (User)application.getAttribute("user");
 u2.setUserName("marray");
  %>
	<body>
		el:${initParam.userName}
		<br/>
		el:${initParam.servletName}
		<br />
		application:
		<%=application.getAttribute("Name")%><br />
		el、application:${applicationScope.Name }
		<br />
		<%=((List)application.getAttribute("list")).size() %>
		<br/>
		<%=((User)application.getAttribute("user")).getUserName() %>
	</body>
</html>
(3) web配置
<?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">


	<env-entry>
		<env-entry-name>datasourceJndiName</env-entry-name>
		<env-entry-type>java.lang.String</env-entry-type>
		<env-entry-value>qqt_datasource</env-entry-value>
		<!--
			injection-target>
			<injection-target-class>qqt.interfaces.MyDB</injection-target-class>
			<injection-target-name>datasourceJndiName</injection-target-name>
			</injection-target
		-->
	</env-entry>

	<context-param>
		<description>test</description>
		<param-name>userName</param-name>
		<param-value>admin</param-value>
	</context-param>
	<listener>
		<listener-class>TestListner</listener-class>
	</listener>
	<servlet>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>TestServlet</servlet-class>
		<init-param>
			<param-name>servletName</param-name>
			<param-value>TestServlet</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/Servlet</url-pattern>
	</servlet-mapping>


	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<login-config>
		<auth-method>BASIC</auth-method>
	</login-config>
</web-app>

jsp动作指令以及jstl核心标签的循环
(1) 页面实例
<%@ 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 οnlοad="a()">
     <!-- jsp动作指令所描述的bean必须是要有无参构造 -->
     <jsp:useBean id="user1"  class="com.bean.User" scope="page"></jsp:useBean>
     <jsp:setProperty property="uname" name="user1" value="marry"/>
     <jsp:setProperty property="uid" name="user1" value="1"/>
    
     <jsp:useBean id="user2"  class="com.bean.User" scope="session"></jsp:useBean>
     <jsp:useBean id="user3"  class="com.bean.User" scope="request"></jsp:useBean>
     <jsp:setProperty property="uname" name="user3" value="tom"/>
     <jsp:useBean id="user4"  class="com.bean.User" scope="application"></jsp:useBean>
     <jsp:setProperty property="uname" name="user4" value="marry"/>
    page:<%=pageContext.getAttribute("user1") %><br/>
    uname:<jsp:getProperty property="uname" name="user1"/><br/>
    <hr/>
    session:<%=session.getAttribute("user2") %><br/>
    request:<%=request.getAttribute("user3") %><br/>
    <%--<jsp:forward page="view01.jsp"></jsp:forward>--> --%>
   <%String username ="<jsp:getProperty property='uname' name='user1'/>";%>
          标签赋值java代码:<%="<jsp:getProperty property='uname' name='user1'/>"%>
   
   <script type="text/javascript">
   function a(){
   var param = '<%=pageContext.getAttribute("user1") %>';
   var param2 = '<jsp:getProperty property="uname" name="user1"/>';
   <%if(1==1){%>
   alert(param2);
   <%
   }%>
   }
   </script>
  </body>
</html>
(2) 页面实例
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.bean.User"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="cc" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsf/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'view01.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>
  <%@include file="/view02.jsp" %>
  <br/>
  <body>
  <cc:set  scope="application" value="user4" var="user4"></cc:set>
  <br>
   <!-- userBean 定义两个相同的bean,意思为有就使用,没有就创建 -->
   <jsp:useBean id="user3" class="com.bean.User" scope="request"></jsp:useBean>
   <jsp:getProperty property="uname" name="user3"/><br/>
   
   <cc:set var="abc" value="2" ></cc:set>
   <cc:choose>
   <cc:when test="${abc==1}">1</cc:when>
   <cc:when test="${abc==2}">2</cc:when>
   </cc:choose>
   <br/>
   <cc:forEach begin="1" end="10" step="2" varStatus="id" var="cc">
   <input type="submit" value="${cc }"/>
   </cc:forEach>
   <br/>
   <%List al = new ArrayList();
   User u1 = new User("t1","tom");
   User u2 = new User("t2","marry");
   User u3 = new User("t3","cat");
   al.add(u1);al.add(u2);al.add(u3);al.add("String");
   pageContext.setAttribute("al",al);
    %>
   <cc:forEach items="${al}" var="l" varStatus="ix">
   Last:${ix.last} <br/> First:${ix.first}<br/>次数:(ix.index)
   <cc:if test="${l.class!=com.bean.User}"><div>index:${ix.index}:${l}</div></cc:if>
   <cc:if test="${l.class==com.bean.User}"><div>index:${ix.index}:${l.uname}</div></cc:if>
   </cc:forEach>
  </body>
</html>

jsp页面发布xml或者pdf数据
(1) 发布xml数据ps:从后台发送数据
package com.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;

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

import com.bean.User;

@SuppressWarnings("serial")
public class XmlServlet extends HttpServlet{
	@Override
		protected void service(HttpServletRequest req, HttpServletResponse resp)
				throws ServletException, IOException {
		
		System.out.println("protected");
		req.setCharacterEncoding("utf-8");
		resp.setHeader("Cache-Control", "no-cache");   
		resp.setHeader("Cache-Control", "no-store");   
		resp.setContentType("application/xml; charset=utf-8");
		PrintWriter out = resp.getWriter();
		/**
		 * OutputStream 只能输入二进制数据;
		 */
//		OutputStream ops = resp.getOutputStream();
		out.print(new XmlServlet().getXmlInfo());
		out.flush();
		out.close();
		}
private String getXmlInfo() {
    StringBuilder sb = new StringBuilder();
    sb.append("<videoSend>");
    sb.append("<header>");
    sb.append("<sid>1</sid>");
    sb.append("<type>service</type>");
    sb.append("</header>");
    sb.append("<service name=\"videoSend\">");
    sb.append("<fromNum>0000021000011001</fromNum>");
    sb.append("<toNum>33647405</toNum>");
    sb.append("<videoPath>mnt/5.0.217.50/resources/80009.mov</videoPath>");
    sb.append("<chargeNumber>0000021000011001</chargeNumber>");
    sb.append("</service>");
    sb.append("</videoSend>");
    return sb.toString();
}
public static void main(String[] args) throws Exception{
	URL webUrl = new URL("http://localhost/views/XmlServlet");
	InputStreamReader reader = new InputStreamReader(webUrl
			.openStream());
	BufferedReader breader = new BufferedReader(reader);
	StringBuilder result = new StringBuilder();
	String line = null;
	while ((line = breader.readLine()) != null) {
		result.append(line);
	}
	System.out.println(result.toString());
}
}
     2.第二种页面发布xml数据或者json的方式
        后台
package cn.itcast.servlet;

import java.io.IOException;
import java.util.List;

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

import cn.itcast.domain.News;
import cn.itcast.service.VideoNewsService;
import cn.itcast.service.impl.VideoNewsServiceBean;


public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private VideoNewsService service = new VideoNewsServiceBean();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<News> videos = service.getLastNews();
		String format = request.getParameter("format");
		if("json".equals(format)){
			// [{id:56,title:"xxxxx",timelength:90},{id:16,title:"xbbx",timelength:20}]
			StringBuilder builder = new StringBuilder();
			builder.append('[');
			for(News news : videos){
				builder.append('{');
				builder.append("id:").append(news.getId()).append(',');
				builder.append("title:\"").append(news.getTitle()).append("\",");
				builder.append("timelength:").append(news.getTimelength());
				builder.append("},");
			}
			builder.deleteCharAt(builder.length() - 1);
			builder.append(']');
			request.setAttribute("json", builder.toString());
			request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response);
		}else{
			request.setAttribute("videos", videos);
			request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
		}
	}

}
        页面

<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><?xml version="1.0" encoding="UTF-8"?>
<videonews><c:forEach items="${videos}" var="video">
	<news id="${video.id}">
		<title>${video.title}</title>
		<timelength>${video.timelength}</timelength>
	</news></c:forEach>
</videonews>

(2) 页面发布pdf数据
      a java发布
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.io.File"%>
<%@page import="java.io.DataOutput"%>
<%@page import="java.io.DataOutputStream"%>
<%@page import="java.io.DataInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.BufferedReader"%>
<%
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 'pdf.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>
  <%
  out.clear();
  out = pageContext.pushBody();
  response.setContentType("application/pdf");
  try{
	  String strPdfPath = new String("f://2015.pdf");
	  File file = new File(strPdfPath);
	  if(file.exists()){
	  BufferedOutputStream temps = new BufferedOutputStream(response.getOutputStream());
	  DataInputStream in = new DataInputStream(new FileInputStream(file));
	  byte[] b =new byte[2048];
	  while((in.read(b))!=-1){
		  temps.write(b);
		  temps.flush();
	  }
	  in.close();
	  temps.close();
	  }else{
		  out.print(strPdfPath+"文件不存在!");
	  }
  }catch(Exception e){
	  out.print(e.getMessage());
  }
  %>
  <body>
    
  </body>
</html>
      b  标签发布
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.io.File"%>
<%@page import="java.io.DataOutput"%>
<%@page import="java.io.DataOutputStream"%>
<%@page import="java.io.DataInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.BufferedOutputStream"%>
<%
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 'pdf.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>
    <object  classid="clsid:CA8A9780-280D-11CF-A24D-444553540000" border="0">
    <param name="_Version" value="65539">
    <param name="_ExtentX" value="20108">
    <param name="_ExtentY" value="10866">
    <param name="_StockProps" value="0">
    <param name="SRC" value="2015.pdf">
    </object>
    <object data="2014.pdf" type="application/pdf" border="0" width="70%" height="800">
    alt:<a href="">2015.pdf</a>
    </object>
  </body>
</html>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值