干貨運用resteasy整合web框架,同時將后台接口以js形式導出到前台


不多說先上 web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
      <context-param>
        <param-name>resteasy.resources</param-name>
        <param-value>com.server.rest.Echo</param-value>
    </context-param>
    
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>
    
    
    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>
    
         
    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <!-- 將后台接口導出到ajax js到前台 -->
    <servlet>
        <servlet-name>RESTEasy-JSAPI</servlet-name>
        <servlet-class>org.jboss.resteasy.jsapi.JSAPIServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>RESTEasy-JSAPI</servlet-name>
        <url-pattern>/restJs.js/*</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.server</groupId>
  <artifactId>resteasyDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>resteasyDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
    
     <repositories> 
       <repository> 
          <id>JBoss repository</id> 
          <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> 
       </repository> 
    </repositories> 


    <dependencies>
         <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>
        
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jsapi</artifactId>
            <version>2.3.1.GA</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.7</version>
    </dependency>
        
    </dependencies>
    <build>
        <finalName>resteasyDemo</finalName>
        <plugins>
             <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-compiler-plugin</artifactId>  
                <configuration>  
                    <source>1.6</source>  
                    <target>1.6</target>  
                </configuration>  
            </plugin>  
        </plugins>
    </build>
</project>

java類

package com.server.rest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import com.alibaba.fastjson.JSON;
import com.server.util.SecurityCode;
import com.server.util.SecurityImage;
import com.server.vo.ResponseResult;

@Path(value = "echo")
public class Echo {
    @GET
    @Path(value = "/{message}")
    public String echoServicePath(@PathParam("message") String message)
    {
        return message;
    }
    
    @GET
    @Path(value = "/test")
    public String echoServiceQuery(@QueryParam("test") String test)
    {
        
        ResponseResult resultStr = new ResponseResult();
        resultStr.setCode(0);
        resultStr.setMsg("調用成功");
        resultStr.setValue("傳入參數:"+test);
        return JSON.toJSONString(resultStr);
    }
    
    @GET
    @Path(value = "/getPic")
    public String getPic(
            @Context HttpServletRequest request,
            @Context HttpServletResponse response)
    {
        HttpSession session = request.getSession();
        String securityCode = SecurityCode.getSecurityCode();
        session.setAttribute("code", securityCode);
        String base64Str = "data:image/gif;base64,"+SecurityImage.getImageAsInputStream(securityCode.replaceAll("", " "));
        return base64Str;
    }
    
    @GET
    @Path(value = "/check")
    public String checkCode(
            @Context HttpServletRequest request,
            @Context HttpServletResponse response,
            @QueryParam("code") String code)
    {
        HttpSession session = request.getSession();
        String SessionCode = (String) session.getAttribute("code");
        
        ResponseResult resultStr = new ResponseResult();
        resultStr.setMsg("調用成功");
        resultStr.setValue("傳入參數:"+code);;
        if(code.equals(SessionCode)) {
            resultStr.setCode(0);
        } else {
            resultStr.setCode(1);
        }
        return JSON.toJSONString(resultStr);
    }
}

驗證碼校驗類

package com.server.util;

import java.util.Arrays;

/**
 * 工具類,生成隨機驗證碼字符串
 * 
 * @author minxing
 *
 */
public class SecurityCode {
    /**
     * 驗證碼難度級別,Simple只包含數字,Medium包含數字和小寫英文,Hard包含數字和大小寫英文
     */
    public enum SecurityCodeLevel {
        Simple, Medium, Hard
    };

    /**
     * 產生默認驗證碼,4位中等難度
     * 
     * @return String 驗證碼
     */
    public static String getSecurityCode() {
        return getSecurityCode(4, SecurityCodeLevel.Medium, false);
    }

    /**
     * 產生長度和難度任意的驗證碼
     * 
     * @param length
     *            長度
     * @param level
     *            難度級別
     * @param isCanRepeat
     *            是否能夠出現重復的字符,如果為true,則可能出現 5578這樣包含兩個5,如果為false,則不可能出現這種情況
     * @return String 驗證碼
     */
    public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
        // 隨機抽取len個字符
        int len = length;

        // 字符集合(除去易混淆的數字0、數字1、字母l、字母o、字母O)
        char[] codes = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
                'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

        // 根據不同的難度截取字符數組
        if (level == SecurityCodeLevel.Simple) {
            codes = Arrays.copyOfRange(codes, 0, 9);
        } else if (level == SecurityCodeLevel.Medium) {
            codes = Arrays.copyOfRange(codes, 0, 33);
        }
        // 字符集合長度
        int n = codes.length;

        // 拋出運行時異常
        if (len > n && isCanRepeat == false) {
            throw new RuntimeException(String.format(
                    "調用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出現異常,當isCanRepeat為%3$s時,傳入參數%1$s不能大於%4$s", len,
                    level, isCanRepeat, n));
        }
        // 存放抽取出來的字符
        char[] result = new char[len];
        // 判斷能否出現重復的字符
        if (isCanRepeat) {
            for (int i = 0; i < result.length; i++) {
                // 索引 0 and n-1
                int r = (int) (Math.random() * n);

                // 將result中的第i個元素設置為codes[r]存放的數值
                result[i] = codes[r];
            }
        } else {
            for (int i = 0; i < result.length; i++) {
                // 索引 0 and n-1
                int r = (int) (Math.random() * n);

                // 將result中的第i個元素設置為codes[r]存放的數值
                result[i] = codes[r];

                // 必須確保不會再次抽取到那個字符,因為所有抽取的字符必須不相同。
                // 因此,這里用數組中的最后一個字符改寫codes[r],並將n減1
                codes[r] = codes[n - 1];
                n--;
            }
        }
        return String.valueOf(result);
    }

    public static void main(String[] args) {
        System.out.println(getSecurityCode());
    }
}
package com.server.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.codec.binary.Base64;

/**
 * 驗證碼生成器類,可生成數字、大寫、小寫字母及三者混合類型的驗證碼。 支持自定義驗證碼字符數量; 支持自定義驗證碼圖片的大小; 支持自定義需排除的特殊字符;
 * 支持自定義干擾線的數量; 支持自定義驗證碼圖文顏色
 * 
 * @author minxing
 * @version 1.0
 */
public class SecurityImage {
    private static Random random = new Random();

    /*
     * 獲得字體
     */
    public static Font getFont(int fSize) {
        return new Font("Fixedsys", Font.CENTER_BASELINE, fSize);
    }

    /*
     * 繪制干擾線
     */
    public static void drowLine(Graphics g, int width, int height) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }

    /*
     * 獲得顏色
     */
    public static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }

    /**
     * 生成驗證碼圖片
     * 
     * @param securityCode
     *            驗證碼字符
     * @return BufferedImage 圖片
     */
    public static BufferedImage createImage(String securityCode) {
        // 驗證碼長度
        int codeLength = securityCode.length();
        // 字體大小
        int fSize = 35;
        int fWidth = fSize;
        // 圖片寬度
        int width = codeLength * fWidth;
        // 圖片高度
        int height = fSize * 2;
        // 圖片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();
        // 設置背景色
        g.setColor(Color.WHITE);
        // 填充背景
        g.fillRect(0, 0, width, height);
        // 設置邊框顏色
        g.setColor(Color.LIGHT_GRAY);
        // 邊框字體樣式
        g.setFont(new Font("Arial", Font.BOLD, height - 2));
        // g.setFont(getFont());
        // 繪制邊框
        g.drawRect(0, 0, width - 1, height - 1);
        // 繪制噪點
        // Random rand = new Random();
        // 設置噪點顏色
        // g.setColor(Color.BLACK);
        // for (int i = 0; i < codeLength * 6; i++) {
        // int x = rand.nextInt(width);
        // int y = rand.nextInt(height);
        // // 繪制1*1大小的矩形
        // g.drawRect(x, y, 1, 1);
        // }

        // 繪制干擾線
        for (int i = 0; i <= 100; i++) {
            drowLine(g, width, height);
        }

        // 繪制驗證碼
        int codeY = height - 20;
        // 設置字體顏色和樣式
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        g.setFont(getFont(fSize));
        for (int i = 0; i < codeLength; i++) {
            g.drawString(String.valueOf(securityCode.charAt(i)), i * 16 + 5, codeY);
        }
        // 關閉資源
        g.dispose();
        return image;
    }

    /**
     * 返回驗證碼圖片的流格式
     * 
     * @param securityCode
     *            驗證碼
     * @return ByteArrayInputStream 圖片流
     */
    public static String getImageAsInputStream(String securityCode) {
        BufferedImage image = createImage(securityCode);
        // 創建儲存圖片二進制流的輸出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 創建ImageOutputStream流
        ImageOutputStream imageOutputStream = null;
        InputStream in = null;
        try {
            imageOutputStream = ImageIO.createImageOutputStream(baos);
            // 將二進制數據寫進ByteArrayOutputStream
            ImageIO.write(image, "jpg", imageOutputStream);
            in = new ByteArrayInputStream(baos.toByteArray());
        } catch (IOException e) {

        } finally {
        }
        return getImageBinary(in);
    }

    public static String getImageBinary(InputStream in) {
        BufferedImage bi;
        try {
            bi = ImageIO.read(in);
            int width = bi.getWidth(); // 得到源圖寬
            int height = bi.getHeight(); // 得到源圖長
            System.out.println(width + "---" + height);
            width = (width) * 7 / 10;
            height = (height) * 7 / 10;

            Image image = bi.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            BufferedImage biNew = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = biNew.getGraphics();
            g.drawImage(image, 0, 0, null); // 繪制縮小后的圖
            g.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(biNew, "JPEG", baos);
            byte[] bytes = baos.toByteArray();

            return Base64.encodeBase64String(bytes).trim();
        } catch (Exception e) {
        }
        return null;
    }

    public static void main(String[] args) {
//        String securityCode = SecurityCode.getSecurityCode().replaceAll("", " ");
//        String base64Str = getImageAsInputStream(securityCode);
//        System.out.println("data:image/gif;base64," + base64Str);
    }
}

html

<!DOCTYPE html>
<html>

    <head>
        <title>Bootstrap test</title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="js/jquery-1.12.4.min.js"></script>
        <script src="restJs.js"></script>
        <style type="text/css">
            .pic{margin:10px auto}
            .code{height:30px;display:block}
            .span{font-size:30px;}
        </style>
    </head>

    <body>
        <h1>Hello, world!</h1>
        <img class="pic">
        <input type="text" class="code"></input>
        <span></span>
    </body>

    <script>
        
        $(function() {
            var picBase64 = Echo.getPic();
            $('.pic').attr('src',picBase64);
            var echoResultPath = Echo.echoServicePath({message:111});
            console.log(JSON.stringify(echoResultPath));
            var echoResultQuery = Echo.echoServiceQuery({test:"測試"});
            console.log(JSON.parse(echoResultQuery)['code']+"---"+JSON.parse(echoResultQuery)['value']);
            
            
            $('.pic').on('click',function() {
                var picBase64 = Echo.getPic();
                $('.pic').attr('src',picBase64);
            })
            
            $('.code').on('blur',function() {
                var code = $('.code').val();
                if(code) {
                    var result = Echo.checkCode({code:code});
                    if(JSON.parse(result)['code'] == 0) {
                        $('span').html("驗證碼匹配成功");
                    } else {
                        $('span').html("驗證碼匹配失敗");
                    }
                }
            })
            
        })
    
    </script>

</html>

 

本例子,我是實現了一個小功能就是驗證碼的校驗


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM