用ROME来作:https://rome.dev.java.net/
自己的第一个项目IQBoree
里面要求有提供给客户Rss订阅的功能,找了下网上介绍,最后还是在rome的管网找到了解决方案
解决方案有两种:
1,写一个servlet,生成feed,直接由客户来订阅
2,写一个java.自动生成feed的xml文件,然后让客户通过读取这个xml文件来达到订阅Rss的目的
首先我就来讲解下第一种方法:
1.
FeedServlet.java
package com.iqboree.rss.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.iqboree.po.Article;
import com.iqboree.service.impl.ArticleManagerImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
/**
* @author Michael
*
*/
public class FeedServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(FeedServlet.class);
private static final String DEFAULT_FEED_TYPE = "default.feed.type";
private static final String FEED_TYPE = "type";
private static final String MIME_TYPE = "application/xml; charset=UTF-8";
private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
private static final DateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd");
private String _defaultFeedType;
List list;
public void init() {
_defaultFeedType = getServletConfig().getInitParameter(DEFAULT_FEED_TYPE);
_defaultFeedType = (_defaultFeedType!=null) ? _defaultFeedType : "atom_0.3";
log.info("初始化完成");//用来调试,可以看出在tomcat里的输出信息,自己可以去掉,后面的log.info() 也是同样的效果.
DATE_PARSER.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));//这里用来设置时区
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
try {
log.info("doget方法完成");
SyndFeed feed = getFeed(req);
String feedType = req.getParameter(FEED_TYPE);
feedType = (feedType!=null) ? feedType : _defaultFeedType;
feed.setFeedType(feedType);
res.setContentType(MIME_TYPE);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed,res.getWriter());
}
catch (FeedException ex) {
String msg = COULD_NOT_GENERATE_FEED_ERROR;
log(msg,ex);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
}
}
protected SyndFeed getFeed(HttpServletRequest req) throws IOException,FeedException {
log.info("Synd方法开始");
SyndFeed feed = new SyndFeedImpl();
feed.setTitle("Sample Feed (created with ROME)");//channle name ;display as the title
feed.setLink("http://rome.dev.java.net");
feed.setDescription("This feed has been created using ROME (Java syndication utilities");
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
List list = new ArrayList();
//项目是基于spring+webwork+hibernate的,但是在这里不知道让为这个servlet自动获得对应的DAO,所以只能用jdbc手动获取
String sql = "";
try {
log.info("开始进行jdbc操作");
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/iqboree";
Connection conn = DriverManager.getConnection(url,"root","ahuango");
if(conn == null)
{
log.info("conn NULL");
}
Statement stmt = conn.createStatement();
if(stmt==null)
{
log.info("NULLNULLNULL");
}
log.info("开始进行sql操作");
sql = "Select id,AddedDate,AddedBy,Title,Abstract,Body,CommentsEnabled,ViewCount," +
"ReleaseDate,ExpireDate,Approved,Listed,OnlyForMembers,Category_ID from iq_article";
ResultSet rs = stmt.executeQuery(sql);
log.info("begin iterator resultSet");
while(rs.next())
{
log.info("test 1");
Article art = new Article();
art.setId(Long.valueOf(rs.getString(1)));
log.info("test 2");
art.setAddedDate(rs.getDate(2));
log.info("test 3");
art.setAddedBy(rs.getString(3));
log.info("test 4");
art.setTitle(rs.getString(4));
log.info("test 5");
art.setAbstracts(rs.getString(5));
log.info("test 6");
art.setBody(rs.getString(6));
log.info("test 7");
art.setCommentsEnabled(Boolean.valueOf(rs.getBoolean(7)));
log.info("test 8");
art.setViewCount(Integer.valueOf(rs.getString(8)));
log.info("test 9");
art.setReleaseDate(rs.getDate(9));
log.info("test 10");
art.setExpireDate(rs.getDate(10));
log.info("test 11");
art.setApproved(Boolean.valueOf(rs.getBoolean(11)));
log.info("test 12");
art.setListed(Boolean.valueOf(rs.getBoolean(12)));
log.info("test 13");
art.setOnlyForMembers(Boolean.valueOf(rs.getBoolean(13)));
log.info("test 14");
// art.getCategory().setId(Long.valueOf(rs.getString(14)));
log.info("test 15");
list.add(art);
}
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
log.error("sql:"+sql+" "+e.toString());
}
//数据库信息获取完毕,里面的信息大家根据实际需要自己更改.
log.info("开始获取db");
//List articles=new ArticleManagerImpl().getCurrentNArticles(2);
log.info("开始迭代");
Iterator its = list.iterator();
log.info("开始添加feed条目");
while(its.hasNext())
{
Article art=(Article)its.next();
log.info("在while内部");
entry = new SyndEntryImpl();
entry.setTitle("\""+art.getTitle()+"\"");
entry.setLink("Link is:"+art.getId()+"\"");
try {
entry.setPublishedDate(DATE_PARSER.parse("2004-06-08"));
}
catch (ParseException ex) {
// IT CANNOT HAPPEN WITH THIS SAMPLE
}
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("The value is here:"+art.getTitle()); //set the content of this feed
entry.setDescription(description);
entries.add(entry);
}
feed.setEntries(entries);
return feed;
}
}
然后在web.xml中配置这个Rss的订阅地址
The web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>ROME Samples</display-name>
<servlet>
<servlet-name>FeedServlet</servlet-name>
<servlet-class>com.sun.syndication.samples.servlet.FeedServlet</servlet-class>
<init-param>
<param-name>default.feed.type</param-name>
<param-value>rss_2.0</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FeedServlet</servlet-name>
<url-pattern>/feed</url-pattern>
ervlet-mapping>
</web-app>
我的项目名称为IQBoree,所以这个feed相应的订阅地址为:http://localhost:8080/IQBoree/feed
2,自己生成一个xml文件,然后让客户来读取这个xml文件
生成xml文件:
if (true) {
try {
String feedType = "rss_1.0";
String fileName = "rssTest2.xml";
DateFormat dateParser = new SimpleDateFormat(DATE_FORMAT);
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(feedType);
feed.setTitle("Sample Feed (created with Rome)");
feed.setLink("http://rome.dev.java.net/");
feed.setDescription("This feed has been created using Rome (Java syndication utilities");
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
entry = new SyndEntryImpl();
entry.setTitle("Rome v1.0");
entry.setLink("http://wiki.java.net/bin/view/Javawsxml/Rome01");
entry.setPublishedDate(dateParser.parse("2006-11-16"));
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("Initial release of Rome");
entry.setDescription(description);
entries.add(entry);
//以上九行可以用来添加一条feed,可以更具自己的需要多添加几个,或者和第一种生成servlet的方法一样来从数据库读取
feed.setEntries(entries);
Writer writer = new FileWriter(fileName);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed,writer);
writer.close();
System.out.println("The feed has been written to the file ["+fileName+"]");
ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
}
使用rom读取rssUrl
把jdom和rom包拷贝到lib目录下。
直接在jsp页面上嵌入如下代码:
<%@ page language="java"
import="java.util.*;
import java.net.URL;
import java.io.InputStreamReader;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
" pageEncoding="UTF-8"%>
<%
try {
URL feedUrl = new URL("http://www.blogjava.net/crazycy/CommentsRSS.aspx");
//上面是那个需要读取的xml文件的存放地址,我这里找的是偶大哥的blog地址.
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
// System.out.println(feed);
out.println(feed);
// ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
%>
=============================================================================================
使用javaBean:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page import="com.sun.syndication.feed.synd.SyndFeed" %>
<%@ page import="com.sun.syndication.io.SyndFeedInput"%>
<%@ page import="com.sun.syndication.io.XmlReader"%>
<%@page import="java.net.*"%>
<%@page import="java.util.Properties"%>
<%@ page import="com.sun.syndication.feed.atom.Feed" %>
<%@ page import="java.util.List" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sina News</title>
</head>
<body>
<%
System.out.println("Start...");
String str ="http://www.blogjava.net/LittleRain/category/15573.html/rss";
Properties prop = System.getProperties();
// prop.put("http.proxyHost","10.10.10.11"); //这里填写代理的ip
//prop.put("http.proxyPort","8080");
boolean ok = false;
try {
URL feedUrl = new URL(str);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
out.println("Author:"+feed.getAuthor()+"<br>");
out.println("Title:"+feed.getTitle()+"<br>");
out.println("Description:"+feed.getDescription()+"<br>");
java.util.List list=feed.getEntries();
for (int i=0; i< list.size(); i++) {
com.sun.syndication.feed.synd.SyndEntry entry = (com.sun.syndication.feed.synd.SyndEntry)list.get(i);
//out.println(feed.get);
out.println(i+1+":");
out.println("<a href="+entry.getLink()+">"+entry.getTitle()+"</a>");
out.println(entry.getPublishedDate()+"<br>");
}
ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
if (!ok) {
System.out.println();
out.println("FeedReader reads and prints any RSS/Atom feed type.");
out.println("The first parameter must be the URL of the feed to read.");
System.out.println();
}
%>
</body>
</html>
大家在JSP的开发过程中,经常出现中文乱码的问题,可能一至困扰着您,我现在把我在JSP开发中遇到的中文乱码的问题及解决办法写出来供大家参考。
一、JSP页面显示乱码
下面的显示页面(display.jsp)就出现乱码:
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("JSP的中文处理");
%>
</body>
</html>
对不同的WEB服务器和不同的JDK版本,处理结果就不一样。原因:服务器使用的编码方式不同和浏览器对不同的字符显示结果不同而导致的。解决办法:在JSP页面中指定编码方式(gb2312),即在页面的第一行加上:<%@ page contentType="text/html; charset=gb2312"%>,就可以消除乱码了。完整页面如下:
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("JSP的中文处理");
%>
</body>
</html>
二、表单提交中文时出现乱码
下面是一个提交页面(submit.jsp),代码如下:
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<form name="form1" method="post" action="process.jsp">
<div align="center">
<input type="text" name="name">
<input type="submit" name="Submit" value="Submit">
</div>
</form>
</body>
</html>
下面是处理页面(process.jsp)代码:
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getParameter("name")%>
</body>
</html>
如果submit.jsp提交英文字符能正确显示,如果提交中文时就会出现乱码。原因:浏览器默认使用UTF-8编码方式来发送请求,而UTF-8和GB2312编码方式表示字符时不一样,这样就出现了不能识别字符。解决办法:通过request.seCharacterEncoding("gb2312")对请求进行统一编码,就实现了中文的正常显示。修改后的process.jsp代码如下:
<%@ page contentType="text/html; charset=gb2312"%>
<%
request.seCharacterEncoding("gb2312");
%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getParameter("name")%>
</body>
</html>
三、数据库连接出现乱码
只要涉及中文的地方全部是乱码,解决办法:在数据库的数据库URL中加上useUnicode=true&characterEncoding=GBK就OK了。
四、数据库的显示乱码
在mysql4.1.0中,varchar类型,text类型就会出现中文乱码,对于varchar类型把它设为binary属性就可以解决中文问题,对于text类型就要用一个编码转换类来处理,实现如下:
public class Convert {
/** 把ISO-8859-1码转换成GB2312
*/
public static String ISOtoGB(String iso){
String gb;
try{
if(iso.equals("") || iso == null){
return "";
}
else{
iso = iso.trim();
gb = new String(iso.getBytes("ISO-8859-1"),"GB2312");
return gb;
}
}
catch(Exception e){
System.err.print("编码转换错误:"+e.getMessage());
return "";
}
}
}
把它编译成class,就可以调用Convert类的静态方法ISOtoGB()来转换编码。
首先下载并解压最新的FCKeditor到各自的目录,一个是FCKeditor的核心文件,另一个是针对jsp的文件包
下载地址:
http://www.fckeditor.net/download 接下来我们可以开始配置了。
我是在eclipse下来配置的
环境:
jdk:1.4
eclisp:3.12
plugin:myeclipse4.0
FCKeditor :FCKeditor_2.3.2
FCKeditor.java:FCKeditor-2.3
1.新建一个webproject,我这里取名为FCK。
2.把FCKeditor_2.3.2目录下的FCKeditor目录拷贝到FCK工程的根目录,即WebRoot目录下。
3.将FCKeditor-2.3\web\WEB-INF目录下的web.xml中的两个servlet,servlet-mapping定义复制到工程的web.xml文件中去。
4.修改web.xml文件
把
<servlet-mapping> <servlet-name>Connector</servlet-name> <url-pattern>/editor/filemanager/browser/default/connectors/jsp/connector</url-pattern> </servlet-mapping>
<servlet-mapping> <servlet-name>SimpleUploader</servlet-name> <url-pattern>/editor/filemanager/upload/simpleuploader</url-pattern> </servlet-mapping> |
为
<servlet-mapping> <servlet-name>Connector</servlet-name> <url-pattern>/FCKeditor/editor/filemanager/browser/default/connectors/jsp/connector</url-pattern> </servlet-mapping>
<servlet-mapping> <servlet-name>SimpleUploader</servlet-name> <url-pattern>/FCKeditor/editor/filemanager/upload/simpleuploader</url-pattern> </servlet-mapping> |
这里的/FCKeditor/是对应你webroot目录下的FCKeditor目录。
5.拷贝FCKeditor-2.3\web\WEB-INF\lib下的两个jar包到WebRoot\WEB-INF\lib目录下
(在项目的库中添加FCKeditor-2.3\web\WEB-INF\lib下的两个jar包 达不到同样的效果,一定要拷贝到lib目录下)
6.在webroot目录下新建一个jsp,使用默认的MyJsp.jsp即可。
7. 文件开头处加入 :
<%@ taglib uri="http://fckeditor.net/tags-fckeditor" prefix="FCK" %>
8.在jsp中嵌入的代码:在Jsp中使用
方法一:(可能会出现:The requested resource (/FCK/editor/fckeditor.html) is not available)
<c:set var="basepath"><c:url value="/fck/" /></c:set>
<FCK:editor id="descn" basePath="${basepath}" height="500px">
<c:out value="${book.descn}" escapeXml="false" default="" />
</FCK:editor>
方法二:
<FCK:editor id="infoContent" basePath="/FCK/FCKeditor/"
width="800"
height="300"
>
请输入内容
</FCK:editor>
9.部署好工程,开启tomcat,打开MyJsp.jsp页面即可。
10.三种方法调用FCKeditor
<%--
三种方法调用FCKeditor
1.FCKeditor自定义标签 (必须加头文件 <%@ taglib uri="/TestFCKeditor" prefix="FCK" %> )
2.script脚本语言调用 (必须引用 脚本文件 <script type="text/javascript" src="/TestFCKeditor/FCKeditor/fckeditor.js"></script> )
3.FCKeditor API 调用 (必须加头文件 <%@ page language="java" import="com.fredck.FCKeditor.*" %> )
--%>
<%--
<form action="show.jsp" method="post" target="_blank">
<FCK:editor id="content" basePath="/TestFCKeditor/FCKeditor/"
width="700"
height="500"
skinPath="/TestFCKeditor/FCKeditor/editor/skins/silver/"
toolbarSet = "Default"
>
input
</FCK:editor>
<input type="submit" value="Submit">
</form>
--%>
<form action="show.jsp" method="post" target="_blank">
<table border="0" width="700"><tr><td>
<textarea id="content" name="content" style="WIDTH: 100%; HEIGHT: 400px">input</textarea>
<script type="text/javascript">
var oFCKeditor = new FCKeditor('content') ;
oFCKeditor.BasePath = "/TestFCKeditor/FCKeditor/" ;
oFCKeditor.Height = 400;
oFCKeditor.ToolbarSet = "Default" ;
oFCKeditor.ReplaceTextarea();
</script>
<input type="submit" value="Submit">
</td></tr></table>
</form>
<%--
<form action="show.jsp" method="post" target="_blank">
<%
FCKeditor oFCKeditor ;
oFCKeditor = new FCKeditor( request, "content" ) ;
oFCKeditor.setBasePath( "/TestFCKeditor/FCKeditor/" ) ;
oFCKeditor.setValue( "input" );
out.println( oFCKeditor.create() ) ;
%>
<br>
<input type="submit" value="Submit">
</form>
--%>
添加文件/TestFCKeditor/show.jsp:
<%
String content = request.getParameter("content");
out.print(content);
out.println(request.getParameter("title"));
%>
<!--表单中的input的name可以等于这里request.getParameter("parameter") 中的parameter参数。可以通过out.println输出
<FCK:editor id="content".....>FCK中的id相当于input的name
-->
11.FCKeditor编辑器文件上传配置
FCKeditor编辑器的配置文件是fckconfig.js,其中有对编辑器各种默认属性的设置。以下是fckeditor与java集成使用 时上传文件的设置(需要注意的是编辑器不会自动创建文件上传的文件夹,需要在项目的根目录中手动添加),将fckeditor.js文件中以下几个属性原 来的值修改为如下设置:
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + "filemanager/browser/default/browser.html?Connector=connectors/jsp/connector" ;
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + "filemanager/browser/default/browser.html?Type=Image&Connector=connectors/jsp/connector" ;
FCKConfig.FlashBrowserURL =FCKConfig.BasePath + "filemanager/browser/default/browser.html?Type=Flash&Connector=connectors/jsp/connector" ;
FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=File' ;
FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=Image' ;
FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=Flash' ;
至此,即可使用FCKeditor的文件上传功能。