Html2Text 方法实现

This commit is contained in:
x ronger 2019-11-18 19:04:39 +08:00
parent 67c332a40e
commit f684510fcb
10 changed files with 166 additions and 12 deletions

View File

@ -71,7 +71,7 @@ public class WebMvcConfigurer extends WebMvcConfigurationSupport {
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
// TODO 先不拦截接口,进行测试 // TODO 先不拦截接口,进行测试
registry.addInterceptor(restAuthTokenInterceptor()).addPathPatterns("/api/**") registry.addInterceptor(restAuthTokenInterceptor()).addPathPatterns("/api/**")
.excludePathPatterns("/api/v1/**"); .excludePathPatterns("/api/v1/console/**","/api/v1/article/articles/**","/api/v1/article/detail/**");
} }

View File

@ -24,7 +24,9 @@ public class ArticleDTO {
/** 浏览总数 */ /** 浏览总数 */
private Integer articleViewCount ; private Integer articleViewCount ;
/** 预览内容 */ /** 预览内容 */
private Integer articlePreviewContent ; private String articlePreviewContent ;
/** 文章内容 */
private String articleContent ;
/** 评论总数 */ /** 评论总数 */
private Integer commentCount ; private Integer commentCount ;
/** 过去时长 */ /** 过去时长 */

View File

@ -26,9 +26,9 @@ public class Article implements Serializable,Cloneable {
/** 文章标签 */ /** 文章标签 */
private String articleTags ; private String articleTags ;
/** 浏览总数 */ /** 浏览总数 */
private Integer articleViewCount ; private Integer articleViewCount;
/** 预览内容 */ /** 预览内容 */
private Integer articlePreviewContent ; private String articlePreviewContent ;
/** 评论总数 */ /** 评论总数 */
private Integer commentCount ; private Integer commentCount ;
/** 文章永久链接 */ /** 文章永久链接 */

View File

@ -0,0 +1,20 @@
package com.rymcu.vertical.entity;
import lombok.Data;
import java.util.Date;
@Data
public class ArticleContent {
private Integer idArticle;
private String articleContent;
private String articleContentHtml;
private Date createdTime;
private Date updatedTime;
}

View File

@ -4,6 +4,7 @@ import com.rymcu.vertical.core.mapper.Mapper;
import com.rymcu.vertical.dto.ArticleDTO; import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.dto.Author; import com.rymcu.vertical.dto.Author;
import com.rymcu.vertical.entity.Article; import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.entity.ArticleContent;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
@ -18,4 +19,6 @@ public interface ArticleMapper extends Mapper<Article> {
Integer insertArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); Integer insertArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml);
Integer updateArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); Integer updateArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml);
ArticleContent selectArticleContent(@Param("idArticle") Integer idArticle);
} }

View File

@ -4,8 +4,12 @@ import com.rymcu.vertical.core.service.AbstractService;
import com.rymcu.vertical.dto.ArticleDTO; import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.dto.Author; import com.rymcu.vertical.dto.Author;
import com.rymcu.vertical.entity.Article; import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.entity.ArticleContent;
import com.rymcu.vertical.mapper.ArticleMapper; import com.rymcu.vertical.mapper.ArticleMapper;
import com.rymcu.vertical.service.ArticleService; import com.rymcu.vertical.service.ArticleService;
import com.rymcu.vertical.util.Html2TextUtil;
import com.rymcu.vertical.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -28,7 +32,7 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
public List<ArticleDTO> articles(String searchText, String tag) { public List<ArticleDTO> articles(String searchText, String tag) {
List<ArticleDTO> list = articleMapper.selectArticles(searchText, tag); List<ArticleDTO> list = articleMapper.selectArticles(searchText, tag);
list.forEach(article->{ list.forEach(article->{
article = genArticle(article); article = genArticle(article,0);
}); });
return list; return list;
} }
@ -53,6 +57,14 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
article = articleMapper.selectByPrimaryKey(idArticle); article = articleMapper.selectByPrimaryKey(idArticle);
article.setArticleTitle(articleTitle); article.setArticleTitle(articleTitle);
article.setArticleTags(articleTags); article.setArticleTags(articleTags);
if(StringUtils.isNotBlank(articleContentHtml)){
Integer length = articleContentHtml.length();
if(length>200){
length = 200;
}
String articlePreviewContent = articleContentHtml.substring(0,length);
article.setArticlePreviewContent(Html2TextUtil.getContent(articlePreviewContent));
}
article.setUpdatedTime(new Date()); article.setUpdatedTime(new Date());
articleMapper.updateArticleContent(article.getIdArticle(),articleContent,articleContentHtml); articleMapper.updateArticleContent(article.getIdArticle(),articleContent,articleContentHtml);
} }
@ -64,13 +76,28 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
@Override @Override
public ArticleDTO findArticleDTOById(Integer id) { public ArticleDTO findArticleDTOById(Integer id) {
ArticleDTO articleDTO = articleMapper.selectArticleDTOById(id); ArticleDTO articleDTO = articleMapper.selectArticleDTOById(id);
articleDTO = genArticle(articleDTO); articleDTO = genArticle(articleDTO,1);
return articleDTO; return articleDTO;
} }
private ArticleDTO genArticle(ArticleDTO article) { private ArticleDTO genArticle(ArticleDTO article,Integer type) {
Author author = articleMapper.selectAuthor(article.getArticleAuthorId()); Author author = articleMapper.selectAuthor(article.getArticleAuthorId());
article.setArticleAuthor(author); article.setArticleAuthor(author);
article.setTimeAgo(Utils.getTimeAgo(article.getUpdatedTime()));
if(type == 1){
ArticleContent articleContent = articleMapper.selectArticleContent(article.getIdArticle());
article.setArticleContent(articleContent.getArticleContentHtml());
} else {
if(StringUtils.isBlank(article.getArticlePreviewContent())){
ArticleContent articleContent = articleMapper.selectArticleContent(article.getIdArticle());
Integer length = articleContent.getArticleContentHtml().length();
if(length>200){
length = 200;
}
String articlePreviewContent = articleContent.getArticleContentHtml().substring(0,length);
article.setArticlePreviewContent(Html2TextUtil.getContent(articlePreviewContent));
}
}
return article; return article;
} }
} }

View File

@ -0,0 +1,43 @@
package com.rymcu.vertical.util;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
public class Html2TextUtil extends HTMLEditorKit.ParserCallback {
private static Html2TextUtil html2Text = new Html2TextUtil();
private StringBuffer s;
public Html2TextUtil() {
}
public void parse(String html) throws IOException {
InputStream inputStream = new ByteArrayInputStream(html.getBytes());
Reader reader = new InputStreamReader(inputStream);
ParserDelegator delegator = new ParserDelegator();
s = new StringBuffer();
// the third parameter is TRUE to ignore charset directive
delegator.parse(reader, this, Boolean.TRUE);
}
public void handleText(char[] text, int pos) {
s.append(text);
}
public String getText() {
return s.toString();
}
public static String getContent(String str) {
try {
html2Text.parse(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return html2Text.getText();
}
}

View File

@ -6,6 +6,10 @@ import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session; import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import java.text.ParseException;
import java.time.*;
import java.util.Date;
public class Utils { public class Utils {
public static final String HASH_ALGORITHM = "SHA-1"; public static final String HASH_ALGORITHM = "SHA-1";
public static final int HASH_INTERATIONS = 1024; public static final int HASH_INTERATIONS = 1024;
@ -57,4 +61,48 @@ public class Utils {
Integer code = (int)((Math.random()*9+1)*100000); Integer code = (int)((Math.random()*9+1)*100000);
return code; return code;
} }
public static String getTimeAgo(Date date) {
String timeAgo;
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalDate oldLocalDate = localDateTime.toLocalDate();
LocalDate today = LocalDate.now();
Period p = Period.between(oldLocalDate, today);
if(p.getYears() > 0){
timeAgo = p.getYears()+" 年前 ";
}else if(p.getMonths() > 0){
timeAgo = p.getMonths()+" 月前 ";
}else if(p.getDays() > 0){
timeAgo = p.getDays()+" 天前 ";
}else {
long to = System.currentTimeMillis();
long from = date.getTime();
int hours = (int) ((to - from)/(1000 * 60 * 60));
if(hours > 0){
timeAgo = hours+" 小时前 ";
}else {
int minutes = (int) ((to - from)/(1000 * 60));
if(minutes > 0){
timeAgo = " 刚刚 ";
}else {
timeAgo = minutes+" 分钟前 ";
}
}
}
return timeAgo;
}
public static void main(String[] args){
LocalDate localDate = LocalDate.parse("2019-11-15");
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
String s = getTimeAgo(Date.from(instant));
System.out.println(s);
}
} }

View File

@ -47,7 +47,7 @@ public class ArticleController {
return GlobalResultGenerator.genSuccessResult(map); return GlobalResultGenerator.genSuccessResult(map);
} }
@GetMapping("/{id}") @GetMapping("/detail/{id}")
public GlobalResult detail(@PathVariable Integer id){ public GlobalResult detail(@PathVariable Integer id){
ArticleDTO articleDTO = articleService.findArticleDTOById(id); ArticleDTO articleDTO = articleService.findArticleDTOById(id);
Map map = new HashMap<>(); Map map = new HashMap<>();

View File

@ -30,6 +30,7 @@
<result column="article_tags" property="articleTags"></result> <result column="article_tags" property="articleTags"></result>
<result column="article_view_count" property="articleViewCount"></result> <result column="article_view_count" property="articleViewCount"></result>
<result column="article_preview_content" property="articlePreviewContent"></result> <result column="article_preview_content" property="articlePreviewContent"></result>
<result column="article_content" property="articleContent"></result>
<result column="comment_count" property="commentCount"></result> <result column="comment_count" property="commentCount"></result>
<result column="time_ago" property="timeAgo"></result> <result column="time_ago" property="timeAgo"></result>
<result column="article_permalink" property="articlePermalink"></result> <result column="article_permalink" property="articlePermalink"></result>
@ -37,9 +38,16 @@
<result column="updated_time" property="updatedTime"></result> <result column="updated_time" property="updatedTime"></result>
</resultMap> </resultMap>
<resultMap id="AuthorResultMap" type="com.rymcu.vertical.dto.Author"> <resultMap id="AuthorResultMap" type="com.rymcu.vertical.dto.Author">
<result column="id" jdbcType="VARCHAR" property="idUser"/> <result column="id" property="idUser"/>
<result column="nickname" jdbcType="VARCHAR" property="userNickname"/> <result column="nickname" property="userNickname"/>
<result column="avatar_url" jdbcType="VARCHAR" property="userAvatarURL"/> <result column="avatar_url" property="userAvatarURL"/>
</resultMap>
<resultMap id="ArticleContentResultMap" type="com.rymcu.vertical.entity.ArticleContent">
<result column="id_article" property="idArticle"/>
<result column="article_content" property="articleContent"/>
<result column="article_content_html" property="articleContentHtml"/>
<result column="created_time" property="createdTime"/>
<result column="updated_time" property="updatedTime"/>
</resultMap> </resultMap>
<insert id="insertArticleContent"> <insert id="insertArticleContent">
insert into article_content (id_article,article_content,article_content_html,created_time,updated_time) insert into article_content (id_article,article_content,article_content_html,created_time,updated_time)
@ -49,7 +57,7 @@
update article_content set article_content = #{articleContent},article_content_html = #{articleContentHtml},updated_time = sysdate() where id_article = #{idArticle} update article_content set article_content = #{articleContent},article_content_html = #{articleContentHtml},updated_time = sysdate() where id_article = #{idArticle}
</update> </update>
<select id="selectArticles" resultMap="DTOResultMap"> <select id="selectArticles" resultMap="DTOResultMap">
select art.*,su.nickname,su.avatar_url from article art left join sys_user su on art.article_author_id = su.id select art.*,su.nickname,su.avatar_url from article art left join sys_user su on art.article_author_id = su.id order by updated_time desc
</select> </select>
<select id="selectAuthor" resultMap="AuthorResultMap"> <select id="selectAuthor" resultMap="AuthorResultMap">
select * from sys_user where id = #{id} select * from sys_user where id = #{id}
@ -57,4 +65,7 @@
<select id="selectArticleDTOById" resultMap="DTOResultMap"> <select id="selectArticleDTOById" resultMap="DTOResultMap">
select art.*,su.nickname,su.avatar_url from article art left join sys_user su on art.article_author_id = su.id where art.id = #{id} select art.*,su.nickname,su.avatar_url from article art left join sys_user su on art.article_author_id = su.id where art.id = #{id}
</select> </select>
<select id="selectArticleContent" resultMap="ArticleContentResultMap">
select article_content_html from article_content where id_article = #{idArticle}
</select>
</mapper> </mapper>