TheStar

导航

 

一,工具类,分页类和连接数据库jdbc

package com.direct.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class ConnCreate {
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private static final String URL="jdbc:mysql://localhost:3306/countryside_buy?userUnicode=true&characterEncoding=utf-8";
	private static final String USER="root";
	private static final String PWD="123456";
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//创建连接对象
	public Connection createConn(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USER, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	//关闭连接
	public void closeJ(Connection conn,PreparedStatement ps,ResultSet rs) throws SQLException{
		if(rs!=null)  rs.close();
		if(ps!=null)  ps.close();
		if(conn!=null)  conn.close();
	}
		
}

  

package com.direct.util;

import java.io.Serializable;
import java.util.ArrayList;

public class JavaBeanPage<T> implements Serializable {

	/*
	 * javaBean 定义分页模型 泛型
	 */
	private int pagesize=3;//每页显示的条数
	private int pageno=1;//当前页码
	private int totalrecords;//总数据条数
	private int totalpage;
	private ArrayList<T> datalist = null;//当前页的数据
	
	public int getPagesize() {
		return pagesize;
	}
	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}
	public int getPageno() {
		return pageno;
	}
	public void setPageno(int pageno) {
		this.pageno = pageno;
	}
	public int getTotalrecords() {
		return totalrecords;
	}
	public void setTotalrecords(int totalrecords) {
		this.totalrecords = totalrecords;
	}
	public int getTotalpage() {
		return totalpage;
	}
	// 设置总页数   总数据/每页条数
	public void setTotalpage() {
		if (totalrecords%pagesize==0) {
			this.totalpage = totalrecords/pagesize;
		}else {
			this.totalpage = totalrecords/pagesize+1;
		}
	}
	public ArrayList<T> getDatalist() {
		return datalist;
	}
	public void setDatalist(ArrayList<T> datalist) {
		this.datalist = datalist;
	}
	public JavaBeanPage(int pagesize, int pageno, int totalrecords,
			int totalpage, ArrayList<T> datalist) {
		super();
		this.pagesize = pagesize;
		this.pageno = pageno;
		this.totalrecords = totalrecords;
		this.totalpage = totalpage;
		this.datalist = datalist;
	}
	public JavaBeanPage() {
		super();
	}

}

二,dao层对数据的连接和对数据的基本操作

package com.direct.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;


import com.direct.entity.User;
import com.direct.util.ConnCreate;
import com.direct.util.JavaBeanPage;

public class UserJdbc {
	
	
	//从数据中用sql语句分页,得到每页的显示数据集合对象
	public JavaBeanPage<User> getlist(Map<String, Object> map){
		JavaBeanPage<User> page = new JavaBeanPage<User>();
		page.setPageno(Integer.parseInt((String) map.get("pageno")));      //设置当前页码
	//	page.setPagesize((Integer)map.get("pagesize"));    //设置每页显示的数据数量
		
		page.setTotalrecords(getCount());//设置总数据条数
		page.setTotalpage();//设置总页数
/*		ArrayList<User> datalist = page.getDatalist();
		System.out.println(datalist.get(0)); */
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		PreparedStatement ps = null;
		ResultSet rs =null; 
		//  查询起始位置    (当前页数-1)*每页显示的条数
		int begin =(page.getPageno() -1)*page.getPagesize();
		//查询每页显示条数
		int end = page.getPagesize();
		String sql = "select * from user limit  "+begin+" , "+end;
		ArrayList<User> list = new ArrayList<User>();//临时存放user对象,最后传入page中的集合
		
		try {
			ps = conn.prepareStatement(sql);
			 rs = ps.executeQuery();
			 while (rs.next()) {
					User user= new User(rs.getInt("user_id"),
							rs.getString("user_name"),
							rs.getString("user_email"), 
							rs.getString("user_password"),
							rs.getString("user_telphone"),
							rs.getInt("user_status"),
							rs.getString("user_sex"));
					//System.out.println(user);
					list.add(user);
			}
			 page.setDatalist(list);
			 
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	
		return page;
	}
	
	//访问数据库得到数据的总条数
	public int getCount(){
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		PreparedStatement ps = null;
		ResultSet rs =null;
		int count=0;
		String  sql = "select count(user_id) as count from user";
		try {
		          ps = conn.prepareStatement(sql);
		          rs = ps.executeQuery();
		         while (rs.next()) {
					count= rs.getInt("count");
				}    
		         // System.out.println("总数据条数:"+count);
		          
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return count;
	}
	
	public ArrayList<User> qurey(String name,String pwd){
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		StringBuffer sql=new StringBuffer("select * from user where 1=1");
		ArrayList<User>  uList=new ArrayList<User>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		if (name!=null&&!("").equals(name)&&pwd!=null&&!("").equals(pwd)) {
			sql.append(" and user_name='"+name+"'");		
			sql.append("  and  user_password='"+pwd+"'");
		
		try {
			 ps=  conn.prepareStatement(sql.toString());
			 rs = ps.executeQuery();
			while (rs.next()) {
				User user= new User(rs.getInt("user_id"),
						rs.getString("user_name"),
						rs.getString("user_email"), 
						rs.getString("user_password"),
						rs.getString("user_telphone"),
						rs.getInt("user_status"),
						rs.getString("user_sex"));
				uList.add(user);
				//System.out.println("list添加一个对象");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		}				
		return uList;	
	}
	//参数列表不同,不同的调用,应该用重载
	public ArrayList<User> qurey(String name,int id){
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		StringBuffer sql=new StringBuffer("select * from user where 1=1");
		ArrayList<User>  uList=new ArrayList<User>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		 if(name!=null&&!("").equals(name)){
			sql.append(" and user_name='"+name+"'");	
		}else if(id!=0){
			sql.append(" and user_id='"+id+"'");	
		}
		try {
			 ps=  conn.prepareStatement(sql.toString());
			 rs = ps.executeQuery();
			while (rs.next()) {
				User user= new User(rs.getInt("user_id"),
						rs.getString("user_name"),
						rs.getString("user_email"), 
						rs.getString("user_password"),
						rs.getString("user_telphone"),
						rs.getInt("user_status"),
						rs.getString("user_sex"));
				uList.add(user);
				System.out.println("list添加一个对象");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}				
		return uList;	
	}
	

	//增
	public Boolean addUsers(User uent){
		Boolean bool = false;
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		PreparedStatement ps = null;
		String sql = "insert into user(user_name,user_email,user_password,user_telphone,user_status,user_sex) values(?,?,?,?,?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, uent.getUname());
			ps.setString(2, uent.getUemail());
			ps.setString(3, uent.getUpwd());
			ps.setString(4, uent.getUtel());
			ps.setInt(5, uent.getUsatus());
			ps.setString(6, uent.getUsex());
			int temp = ps.executeUpdate();
			if (temp>0) {
				System.out.println("添加成功!!!");
				bool = true;
			}		
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}			
		return bool;
	}
	// 改
	public Boolean changeUser(int id,User uent){
		Boolean bool = false;
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		PreparedStatement ps=null;
		//update user set user_name=?,user_email=?,user_password=?,user_telphone=?,user_sex=? where name ='star' 
		StringBuffer sql = new StringBuffer("update user set user_name=?,user_email=?,user_password=?,user_telphone=?,user_sex=? where user_id= '"+id+"'");
		try {
			ps = conn.prepareStatement(sql.toString());		
			ps.setString(1, uent.getUname());
			ps.setString(2, uent.getUemail());
			ps.setString(3, uent.getUpwd());
			ps.setString(4, uent.getUtel());
			ps.setString(5, uent.getUsex());		
			int rows = ps.executeUpdate();
			if(rows>0){
				System.out.println("修改成功!!!");
				bool=true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}				
		return bool;	
	}
	//删
	public Boolean deleteUser(int id){
		Boolean bool = false;
		ConnCreate connCreate = new ConnCreate();
		Connection conn = connCreate.createConn();
		PreparedStatement ps = null;
		String sql = "delete from user where user_id='"+id+"'";
		try {
			ps = conn.prepareStatement(sql);
			int rows = ps.executeUpdate();
			if (rows>0) {
				System.out.println("删除成功!!!");
				bool = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connCreate.closeJ(conn, ps, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
		return bool;
	}
	
/*	public static void main(String[] args) {
		ArrayList<User> list = new UserJdbc().qurey("小白","123456");
		System.out.println(list.size());
		
		User user = new User(1, "小蓝", "nn147552384@163.com", "435256", "13996932845", 0, "女");
		new UserJdbc().addUsers(user);
		System.out.println(new UserJdbc().getCount());
		//new UserJdbc().getlist();
	}*/
}

  三,service层的接受前台数据和响应

package com.direct.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

import com.direct.dao.UserJdbc;
import com.direct.entity.User;
import com.direct.util.JavaBeanPage;

public class UserServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");// 设置字符编码
		response.setContentType("text/html;charset=utf-8");// 设置输出内容的类型及字符编码
		response.setCharacterEncoding("utf-8");

		/*
		 * 三种作用域 
		 * request 一次请求 只能用forward转换页面 
		 * session 一次会话 在浏览器中可以访问,关闭浏览器重开不能
		 * application 一直 关闭浏览器后在打开,访问得到 (一般用于网站访问人数的数据)
		 */		
		String username = request.getParameter("username");// 获取值 表单值
		String[] values = request.getParameterValues("hobby");// 获取数组 表单复选框
		String hob = "";
		for (int i = 0; i < values.length; i++) {
			hob+=values[i]+",";
		}
		
		HttpSession session = request.getSession();
		session.setAttribute("sname", "dgdfhhh");
		session.setAttribute("spwd", "fugfgh");
		session.setMaxInactiveInterval(10);//设置最大存在时间  单位秒
		session.invalidate();//销毁
		session.removeAttribute("sname");//移除存放的值

		ServletContext application = this.getServletContext();
		application.setAttribute("aname", "fyjhjhgjfk");
		application.setAttribute("apwd", "dfjgfhdf");
		
		/*
		 * 内部跳转 请求转发 forward() 一次请求 外部跳转 重定向 sendRedirect() 两次请求
		 */
		// request.getRequestDispatcher("MyJsp.jsp").forward(request, response);
		PrintWriter out = response.getWriter();// 返回PrintWriter 输出流对象
//		out.print("sdfniodg");//响应给前台
//		response.sendRedirect("MyJsp.jsp");// 重定向跳转页面
		String op = request.getParameter("op");
		
               if(("page").equals(op)){
			//op=page&pageno=1
			String pageno = request.getParameter("pageno");//当前页码
			System.out.println(pageno+"pageno");
			Map< String, Object> map = new HashMap<String, Object>();
			map.put("pageno", pageno);
			//map.put("pagesize", 3);
			UserJdbc userJdbc = new UserJdbc();
			JavaBeanPage<User> pagelist = userJdbc.getlist(map);
			request.setAttribute("nowdate", new  Date());//存入当前时间
			request.setAttribute("pagelist", pagelist);//存入request属性值
			//request.getRequestDispatcher("pagelist.jsp").forward(request, response);
			request.getRequestDispatcher("jstl.jsp").forward(request, response);
		} else {
			System.out.println("--------------else----------");
		}
		

	}

}
                

  四,jsp页面取数据和显示的几种方式

  jstl中 c 标签和 fmt 标签的简单使用。和实现真分页。以及el表达式的简单运用

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib  uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt" %>
<%
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 'jstl.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>
    <table cellpadding="0" cellspacing="0" width="50%"  align="center">
        		<tr> <th>编号</th>
        		<th>ID</th>
        		<th>用户名</th>
        		   <th>邮件</th>
        		   <th>电话</th>
        		   <th>密码</th>
        		   <th>性别</th>
        		</tr>
        		        <c:forEach   items="${pagelist.datalist}"  var="item"  varStatus="status">
	        		        <tr>
	        		        			<td>${status.index }</td>
	        		        		    <td>${item.uid }</td>
				        			<td>${item.uname }</td>
				        		        <td>${item.uemail }</td>
				        		        <td> ${item.utel }</td>
				        		        <td>${item.upwd }</td>
				        		        <td>${item.usex }</td>
	        		        </tr>
        		        </c:forEach>
        		        
        		         <tr>
        		         		<td></td>
			        		         <td>当前页:${pagelist.pageno } /总页数:${pagelist.totalpage }</td>
			        		         <td><a href="UserServlet?op=page&pageno=1"> 首页</a></td>
			        		         <td><a href="UserServlet?op=page&pageno=${pagelist.pageno>1?pagelist.pageno-1:pagelist.pageno}">上一页</a></td>
			        		         <td><a href="UserServlet?op=page&pageno=${pagelist.pageno<pagelist.totalpage?pagelist.pageno+1:pagelist.totalpage}">下一页</a></td>
			        		         <td><a href="UserServlet?op=page&pageno=${pagelist.totalpage }">尾页</a></td>
        		         </tr>
         </table>
         <c:set    value="99"  var="score"></c:set>
          成绩:<c:out  value="${score}"></c:out>
         <c:if test="${score>80}">成绩很优秀   </c:if><br/>
         <c:set  value="6" var="grade" ></c:set>
         <select name="grade">
              <c:choose>
		             <c:when test="${grade==1}">
		            		 <option value="1">倔强青铜</option>
		             </c:when>
		             <c:when test="${grade==2}">
		             		<option value="2">秩序白银</option>
		             </c:when>
		             <c:when test="${grade==3}">
		           			 <option value="3">荣耀黄金</option>
		             </c:when>
		              <c:when test="${grade==4}">
		            		 <option value="4">尊贵铂金</option>
		             </c:when>
		              <c:when test="${grade==5}">
		             		<option value="5">永恒钻石</option>
		             </c:when>
					<c:otherwise >
							<option >王者</option>
					</c:otherwise>
             </c:choose>
         </select>
         <br/>
         <c:set value="语文,数学,英语,C++,C#,JAVA,PHP"  var="subject" scope="session"></c:set>
         <c:forTokens items="${subject}" delims=","  begin="0" end="2"   var="ke">
         		<c:out value="${ke}"></c:out><br/>
         </c:forTokens>
         <br/>
		当前时间:<fmt:formatDate value="${nowdate}" pattern="yyyy年MM月dd日 HH:mm:ss"/>         
		<br/>
		<h3>数字格式化:</h3>
			<c:set var="balance" value="120000.2309" />
			<p>格式化数字 (1): <fmt:formatNumber value="${balance}" 
			            type="currency"/></p>
			<p>格式化数字 (2): <fmt:formatNumber type="number" 
			            maxIntegerDigits="3" value="${balance}" /></p>
			<p>格式化数字 (3): <fmt:formatNumber type="number" 
			            maxFractionDigits="3" value="${balance}" /></p>
			<p>格式化数字 (4): <fmt:formatNumber type="number" 
			            groupingUsed="false" value="${balance}" /></p>
			<p>格式化数字 (5): <fmt:formatNumber type="percent" 
			            maxIntegerDigits="3" value="${balance}" /></p>
			<p>格式化数字 (6): <fmt:formatNumber type="percent" 
			            minFractionDigits="10" value="${balance}" /></p>
			<p>格式化数字 (7): <fmt:formatNumber type="percent" 
			            maxIntegerDigits="3" value="${balance}" /></p>
			<p>格式化数字 (8): <fmt:formatNumber type="number" 
			            pattern="###.###E0" value="${balance}" /></p>
			<p>美元 :
			<fmt:setLocale value="en_US"/>
			<fmt:formatNumber value="${balance}" type="currency"/></p>

<hr/>
<%--el表达式的使用:
等于:== eq
不等于:!= ne
大于等于:>= ge
小于等于:<= le
小于:< lt
大于:> gt
逻辑与: && and
逻辑或: || or
逻辑非: ! not
是否为空:empty
--%>

总条数:${requestScope.pagelist.totalrecords }<br/>
等于:${pagelist.pageno eq pagelist.pagesize }<br/>
不等于:${pagelist.pageno ne pagelist.pagesize }<br/>

  </body>
</html>

 jstl中标签的使用,c,fmt,functions。

服务器开启后,直接访问本页面即可

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@  taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"  prefix="fn"%>
<%
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 'jstlApply.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>
    <!-- 1根据不同年龄段 判断人群类别。 少年 青年 …….. (多种方式实现)
	         2使用forTokens  拆分遍历数据。(blue,red,green|yellow|pink,black|white)
             3获得时间:格式化输出年 月 日 时 分 秒 AM /PM
             4得到一个数字 已不同的方式输出为金额格式  (美元 人民币)
     -->
     <c:set  value="25"  var="age"></c:set>
     <c:out value="${age}"></c:out><br/>
     <hr/>
  c:choose和c:when方式:  
    <c:choose>
    	<c:when test="${age<=10}">儿童</c:when>
    	<c:when test="${age<=30&&age>10}">青年</c:when>
    	<c:when test="${age<=50&&age>30}">中年</c:when>
    	<c:when test="${age>50}">老年</c:when>
    </c:choose><br/>
  c:if方式:  
   <c:if test="${age<=10}">儿童</c:if>
    <c:if test="${age<=30&&age>10}">青年</c:if>
    <c:if test="${age<=50&&age>30}">中年</c:if>
    <c:if test="${age>50}">老年</c:if><br/>
       <hr/>
    <c:set value="blue,red,green|yellow|pink,black|white"  var="str"></c:set>
    原字符串:<c:out value="${str}"></c:out><br/>
    c:forTokens:
    <c:forTokens items="${str}" delims=","  var="color">
        <c:forTokens items="${color}" delims="|" var="co">
    	${co}
        </c:forTokens>
    </c:forTokens>
         <hr/>
    <c:set   value="<%=new Date() %>"  var="nowdate"></c:set><br/>
    <fmt:formatDate value="${nowdate}" pattern="yyyy年MM月dd日  HH:mm:ss a" var="date"/>
    fmt:formatDate:<c:out value="${date}"></c:out><br/>
    <c:set value="3568" var="num"></c:set>
     fmt:formatNumber:
       <fmt:formatNumber   type="currency" value="${num}" ></fmt:formatNumber><br/>
		<fmt:formatNumber currencySymbol="$"  value="${num}"></fmt:formatNumber><br/>
        <fmt:formatNumber  currencyCode="$" value="${num}"></fmt:formatNumber><br/>
      <!--  jstl函数:使用
					5 判断字符串A中是否有存在子串B (忽略大小写/不忽略大小写);
					6 集合中装有多个字符串,遍历 输出以指定字符结尾的 字符串;
					7集合中装有多个字符串,输出不同字符串中指定字符出现的位置。
					8将多个字符串 拼接为一个字符串。
					9截取返回 字符串 指定范围、 之前、 之后的内容。
					10字符串的替换操作。
         -->
		<% String str1 = "javascripet";
				String str2 = "vAsc";
				ArrayList liststr =  new ArrayList();
				liststr.add("bluejstl");
				liststr.add("redjstld");
				liststr.add("yelllowjstl");
				liststr.add("blackjstla");
				liststr.add("bluejstl");
				request.setAttribute("liststr",liststr);
		 %>
		 jstl:function<br/>
		${fn:contains(str1,str2) }<br/>
		${fn:containsIgnoreCase(str1,str2) }<br/>
		endsWith:
		<c:forEach items="${liststr}" var="strl"  varStatus="status">
			${status.index}
		    ${strl}
			${fn:endsWith(strl, "jstl")} <%="," %><br/>
		</c:forEach><br/>
	indexOf:	<c:forEach items="${liststr}" var="strof">
			 ${strof}
			 ${fn:indexOf(strof, 'j')}
			 <%="," %>
		</c:forEach><br/>
     <hr/>
		<c:set var="string1" value="I am from google"/>
		<c:set var="string2" value="${fn:replace(string1, 'google', 'runoob')}" />
		<p>replace替换后的字符串 : ${string2}</p>
		     <hr/>
		<c:set var="string1" value="www runoob com"/>
		<c:set var="string2" value="${fn:split(string1, ' ')}" />
		<%
				String[] arr = {"This","is","array","string"};
				request.setAttribute("arr",arr);
		 %>
		 <c:set value="${arr}" var="array"></c:set>
		 arr使用join连接: ${fn:join(array,'-') }
		<c:set var="string3" value="${fn:join(string2, '-')}" /><!-- string2是字符串数组 -->
		<p>字符串为 : ${string3}</p>
		<c:set var="string4" value="This is first String."/>
		<c:set var="string5" value="${fn:substring(string4, 5, 15)}" />
		<p>生成的子字符串为 : ${string5}</p>
		<c:set var="string6" value="${fn:substringAfter(string4, 'is')}" />
		<p>After生成的子字符串 : ${string6}</p>
		<c:set var="string7" value="${fn:substringBefore(string4,  'first')}" />
		<p>Before生成的子字符串 : ${string7}</p>

  </body>
</html>

 五,web.xml中的配置,以及使用配置文件实现初始化数据

<?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">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.direct.servlet.UserServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
		  <servlet-name>config_jsp</servlet-name>
		     <jsp-file>/config.jsp</jsp-file>
		  <init-param>
		        <param-name>configFile</param-name>
		            <param-value>confi.txt配置文件的信息</param-value>
		  </init-param>
  </servlet>
  <servlet-mapping>
  	    <servlet-name>config_jsp</servlet-name>
            <url-pattern>/conf.jsp</url-pattern>
  </servlet-mapping>

  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  六,web.xml 中初始化的数据在发布服务器后可直接访问取数据

config.jsp

访问   http://localhost:8082/webProject/conf.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 'config.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>
  
  			配置文件名:<%=config.getInitParameter("configFile") %>
  </body>
</html>

  

 

posted on 2017-12-15 17:26  TheStar  阅读(794)  评论(0编辑  收藏  举报