JSP displays data for HBase

Source: Internet
Author: User

JSP Displays data for HBase

Software:

Jdk1.7,eclipse ee,vmware installed CentOs6.5, Hadoop-2.6.0,HBase-0.99.2

1, build a normal dynamic Web program, run with the guide jar package, without maven and ant .

2 . The corresponding jar packages of HBase and Hadoop are directed into the project;

The main is to run the HBase API, the specified table name and the contents of the row key read out.

and add the log4j.properties file.

3. Create a servlet class and create a JSP file that puts HBase 's lib Jar bag copy into Web of the /web_ceshi2/webcontent/web-inf/lib go inside.

Project directory Structure:

Code:

Output_hbase.java:

Package Control;import Java.io.ioexception;import model. Article;import Org.apache.hadoop.conf.configuration;import Org.apache.hadoop.hbase.keyvalue;import Org.apache.hadoop.hbase.client.get;import Org.apache.hadoop.hbase.client.hbaseadmin;import Org.apache.hadoop.hbase.client.htable;import Org.apache.hadoop.hbase.client.htableinterface;import Org.apache.hadoop.hbase.client.htablepool;import Org.apache.hadoop.hbase.client.result;import Org.apache.hadoop.hbase.client.resultscanner;import Org.apache.hadoop.hbase.client.Scan; @SuppressWarnings (" Deprecation ") public class Output_hbase {hbaseadmin admin=null; Configuration conf=null;/** * Constructor load config */public output_hbase () {conf = new configuration (); Conf.set (" Hbase.zookeeper.quorum "," 192.168.1.200:2181 "); Conf.set (" Hbase.rootdir "," hdfs://192.168.1.200:9000/hbase "); SYSTEM.OUT.PRINTLN ("initialization complete"); try {admin = new hbaseadmin (conf);} catch (IOException e) {e.printstacktrace ()}} public static void Main (string[] args) {output_hbase o=new output_hbase (); O. Get ("article", "1");} Public article get (string tableName, String row) {System.out.println ("get performed 1"); @SuppressWarnings ("Resource") Htablepool Htablepool = new Htablepool (conf, 1000); Htableinterface table = htablepool.gettable (tableName); System.out.println ("Get performed 2"); Get get = new Get (Row.getbytes ()); System.out.println ("Get performed 3"); Article Article = null;try {System.out.println ("get performed 4"); Result result = Table.get (get); System.out.println ("Get performed 5"); Keyvalue[] raw = Result.raw (); System.out.println ("Get performed 6"), if (raw.length = = 5) {System.out.println ("Get performed 7"), Article = new article (); Article.setid (New String (Raw[3].getvalue ())); Article.settitle (New String (Raw[4].getvalue ())); Article.setauthor (New String (Raw[0].getvalue ())); Article.setdescribe (New String (Raw[2].getvalue ())); Article.setcontent (New String (Raw[1].getvalue ()));} New Start (Article.getid (), Article.gettitle (), Article.getauthor (), Article.getdescribe (), article.getcontent ()); SYSTEM.OUT.PRINTLN ("Executed Ah--id" +article.getid () + "\ n");SYSTEM.OUT.PRINTLN ("Executed AH-title" +article.gettitle () + "\ n"); SYSTEM.OUT.PRINTLN ("executed--author" +article.getauthor () + "\ n"); SYSTEM.OUT.PRINTLN ("Executed AH-description" +article.getdescribe () + "\ n"); SYSTEM.OUT.PRINTLN ("executed--The Body" +article.getcontent () + "\ n");} catch (IOException e) {e.printstacktrace ();} return article;} /** * Get all data for table * @param tableName */public void Getalldata (String tableName) {try {@SuppressWarnings ("resource") htable HTa ble = new htable (conf, tableName); Scan scan = new scan (); Resultscanner scanner = Htable.getscanner (scan); for (Result Result:scanner) {if (Result.raw (). length==0) { SYSTEM.OUT.PRINTLN (tablename+ "table data is empty!) ");} Else{for (KeyValue Kv:result.raw ()) {System.out.println (New string (Kv.getkey ()) + "\ T" +new string (Kv.getvalue ()));}}} catch (IOException e) {e.printstacktrace ();}}}


Outprx.java:

Package Control;import model.  Article;public class Outprx {private string Id;private string Title;private string Author;private string describe;private String content;public outprx () {}public void get () {System.out.println ("Here This line is 1"); output_hbase out1=new output_hbase (); SYSTEM.OUT.PRINTLN ("This line here is 2"); Article Article=out1.get ("article", "520"); System.out.println ("Here This line is 3"); This.id=article.getid (); This.title=article.gettitle (); this.author= Article.getauthor (); This.describe=article.getdescribe (); This.content=article.getcontent (); System.out.println ("Here it's 4");} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String Getauthor () {return author;} public void Setauthor (String author) {this.author = author;} Public String Getdescribe () {return describe;} public void Setdescribe (String describe) {this.describe = describe;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;}} 



Article:

package Model;public class article {private string id;private string Title;private string Describe;private string Content;private string Author;public article () {}public article (string id,string title,string Describe,string content,string author) {this.id=id;this.title=title;this.describe=describe;this.content=content; This.author=author;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String Getdescribe () {return describe;} public void Setdescribe (String describe) {this.describe = describe;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} Public String Getauthor () {return author;} public void Setauthor (String author) {this.author = author;} Public String toString () {return this.id+ "\ t" +this.title+ "\ T" +this.author+ "\ T" +this.describe+ "\ T" +this.content;} 


(This class is irrelevant to the display and can be ignored)

Import_hbase:

Package Control;import Java.io.ioexception;import Org.apache.hadoop.conf.configuration;import Org.apache.hadoop.hbase.hbaseconfiguration;import Org.apache.hadoop.hbase.client.mutation;import Org.apache.hadoop.hbase.client.put;import Org.apache.hadoop.hbase.mapreduce.tablemapreduceutil;import Org.apache.hadoop.hbase.mapreduce.tableoutputformat;import Org.apache.hadoop.hbase.mapreduce.TableReducer; Import Org.apache.hadoop.io.longwritable;import Org.apache.hadoop.io.nullwritable;import Org.apache.hadoop.io.text;import Org.apache.hadoop.mapreduce.job;import Org.apache.hadoop.mapreduce.Mapper; Import Org.apache.hadoop.mapreduce.reducer;import Org.apache.hadoop.mapreduce.lib.input.fileinputformat;import Org.apache.hadoop.mapreduce.lib.input.textinputformat;public class Import_hbase {public static class Mymapper extends mapper<longwritable, text, longwritable, text>{@Overrideprotected void map (longwritable key, text Value,mapper <longwritable, Text, longwritable, Text> Context ConteXT) throws IOException, Interruptedexception {//Set row key + content Context.write (key, value);}} public static class Myreduce extends Tablereducer<longwritable, Text, nullwritable>{private String family= "info"; @Overrideprotected void reduce (longwritable arg0, iterable<text> v2s,reducer<longwritable, Text, Nullwritable, Mutation> Context context) throws IOException, interruptedexception {for (Text value:v2s) {String line=value.tostring (); String[] Splited=line.split ("\ t"); String Rowkey=splited[0]; Put put = new put (Rowkey.getbytes ());p Ut.add (Family.getbytes (), "id". GetBytes (), Splited[0].getbytes ());p Ut.add ( Family.getbytes (), "title". GetBytes (), Splited[1].getbytes ());p Ut.add (Family.getbytes (), "Author". GetBytes (), Splited[2].getbytes ());p Ut.add (Family.getbytes (), "describe". GetBytes (), Splited[3].getbytes ());p Ut.add ( Family.getbytes (), "content". GetBytes (), splited[4].getbytes ()); Context.write (Nullwritable.get (), put);}}} private static String tablename= "article"; @SuppressWarnings ("DepRecation ") public static void main (string[] args) throws Exception {Configuration conf = hbaseconfiguration.create (); Conf.set ("Hbase.rootdir", "hdfs://192.168.1.200:9000/hbase"); Conf.set ("Hbase.zookeeper.quorum", " 192.168.1.200:2181 "); Conf.set (tableoutputformat.output_table, tableName); Job Job = new Job (conf, Import_HBase.class.getSimpleName ()); Tablemapreduceutil.adddependencyjars (Job); Job.setjarbyclass (Import_hbase.class); Job.setmapperclass ( Mymapper.class); Job.setreducerclass (Myreduce.class); Job.setmapoutputkeyclass (Longwritable.class); Job.setmapoutputvalueclass (Text.class); Job.setinputformatclass (textinputformat.class); job.setOutputFormatClass (Tableoutputformat.class); Fileinputformat.setinputpaths (Job, "HDFS://192.168.1.200:9000/HBASE_SOLR"); Job.waitforcompletion (True);}}


HttpServlet:

Package Servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.annotation.WebServlet; Import control.  outprx;/** * Servlet Implementation class Test */@WebServlet ("/test") public class Test extends HttpServlet {private static           Final long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public Test () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse R esponse) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception,        IOException {//TODO auto-generated method Stuboutprx oo=new outprx (); Oo.get (); Request.setattribute ("id", Oo.getid ()),///value Request.setattribute ("title", Oo.gettitle ());//Stored value Request.setattri Bute ("Author", Oo.getauthor ());///Value Request.setattribute ("Describe", oo.getdescribe ());//value Request.setattribute ("Content", Oo.getcontent () );///Value System.out.println ("==================================================================================        =="); SYSTEM.OUT.PRINTLN ("Executed Ah--id" +oo.getid () + "\ n"); SYSTEM.OUT.PRINTLN ("Executed AH-title" +oo.gettitle () + "\ n"); SYSTEM.OUT.PRINTLN ("executed--author" +oo.getauthor () + "\ n"); SYSTEM.OUT.PRINTLN ("Executed AH-description" +oo.getdescribe () + "\ n");        SYSTEM.OUT.PRINTLN ("Executed AH-the body" +oo.getcontent () + "\ n");                Request.getrequestdispatcher ("/hello.jsp"). Forward (Request,response); System.out.println ("-----------------------------------------------------------------------------");} /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method stub}}

Log4j.properties:

# # # Set Log levels-for more verbose logging "info" to ' Debug ' # # #log4j. rootlogger=debug,stdout,file## Disable oth ER log #log4j. Logger.org.springframework=off #log4j. Logger.org.apache.struts2=off # Log4j.logger.com.opensymphony.xwork2=off #log4j. Logger.com.ibatis=off #log4j. logger.org.hibernate=off### Direct Log messages to stdout # # #log4j. appender.stdout=org.apache.log4j.consoleappenderlog4j.appender.stdout.target= system.outlog4j.appender.stdout.layout= Org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}:%L-%m%n### Direct messages to File MyLog.log # # #log4j. appender.file=org.apache.log4j.fileappenderlog4j.appender.file.file=logs /spider_web.loglog4j.appender.file.datepattern = '. ' yyyy-mm-ddlog4j.appender.file.layout= Org.apache.log4j.patternlayoutlog4j.appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%L-%m%n### Direct messages to File MyLog.log # # #log4j. Logger.cn.superwu.crm.service=info, ServerdailyrollingfilelOg4j.appender.serverdailyrollingfile=org.apache.log4j.dailyrollingfileappender Log4j.appender.serverdailyrollingfile.file=logs/biapp-service.log Log4j.appender.serverdailyrollingfile.datepattern= '. ' YYYY-MM-DD log4j.appender.serverdailyrollingfile.layout= ORG.APACHE.LOG4J.PATTERNLAYOUTLOG4J.APPENDER.SERVERDAILYROLLINGFILE.LAYOUT.CONVERSIONPATTERN=%D{YYY-MM-DD HH:mm : ss}-[%r]-[%p]%m%n#log4j.logger.cn.superwu.crm.service.drmservice=info, serverdailyrollingfile# log4j.appender.drm=org.apache.log4j.rollingfileappender#log4j.appender.drm.file=logs/crm-drm.log# log4j.appender.drm.maxfilesize=10000kb#log4j.appender.drm.maxbackupindex=10#log4j.appender.drm.append=true# log4j.appender.drm.layout=org.apache.log4j.patternlayout#log4j.appender.drm.layout.conversionpattern=[start]%d {YYYY/MM/DD/HH:MM:SS} [date]%n%p[priority]%n%x[ndc]%n%t[thread]%n%c[category]%n%m[message]%n%n# LOG4J.APPENDER.DRM.LAYOUT.CONVERSIONPATTERN=[%5P]%D{YYYY-MM-DD hh:mm:ss}[%c] (%f:%l)%n%m%n%n


HELLO.JSP:

<pre name= "code" class= "Java" ><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >



Right-click the servlet class to run it and run the interface as follows:


Eclipse Displays the entire interface:

the Web interface that Eclipse displays:

Project Engineering Interface shown by Eclipse:

The interface displayed on the Web page:

View data for HBase:

To view the HBase table structure:

Before you run the Web program, you must make sure that Hadoop and HBase are turned on:



If there is an error loading, you can recreate a project.

Example: @WebServlet ("/test")

There are other errors that show that you can't find any class, and you'll start by recreating the project yourself.

Created is not so well, in concrete case specific analysis.


This is purely self-entertaining, of course, with Maven better, with Springmvc better.




JSP displays data for HBase

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.