servlet返回json

5 篇文章 0 订阅

servlet返回json

最近,一直在做springmvc,个人的感觉用起来就是对servlet的封装。现在越用框架,越回到了以前的东西上。现在servlet到了3.0之后,吸收了框架中的一些先进的东西,比如说注解。这样在配置的时候,不会使web.xml文件变的过于的庞大。
下面是一个servlet返回json的小例子:
1、使用maven创建一个webapp项目
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.xueyoucto.xueyou</groupId>
    <artifactId>servletJson</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>servletJson Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>servletJson</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8989/manager/text</url>
                    <username>tomcat</username>
                    <password>tomcat</password>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <!-- 指定编码格式,否则在DOS下运行mvn compile命令时会出现莫名的错误,因为系统默认使用GBK编码 -->
                    <compilerArguments>
                        <extdirs>src/main/webapp/WEB-INF/lib</extdirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <!-- 指定编码格式,否则在DOS下运行mvn命令时当发生文件资源copy时将使用系统默认使用GBK编码 -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

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>Archetype Created Web Application</display-name>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>Util.encodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>



项目文件夹:


JsonServlet.java
package com.xueyoucto.xueyou.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016-09-09.
 */
@WebServlet(name = "Servlet",urlPatterns = "/getjson")
public class JsonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        System.out.println(param);
        response.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        map.put("resCode",1);
        map.put("resString",param);
        String resJSON = JSON.toJSONString(map);
        out.print(resJSON);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

encodingFilter.java
package Util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.core.ConditionalTagSupport;
import java.io.IOException;

/**
 * Created by Administrator on 2016-09-09.
 */
@WebFilter(filterName = "encodingFilter")
public class encodingFilter implements Filter {
    private final String ENCODE = "UTF-8";
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding(ENCODE);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

jsonTest.js
var BASE_URL="http://localhost:8989/servletJson/";
$(function () {
    alert(33);
    $('#testajax').click(function () {
        $.ajax({
            type:'get',
            url:BASE_URL + 'getjson',
            data:{param:'就是我'},
            success: function (data) {
                alert(data);
            },
            error: function () {
                alert("服务器连接异常");
            }
        })
    });
});

jsonTest.jsp
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2016-09-09
  Time: 15:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <script src="${pageContext.request.contextPath}/Component/jquery-1.12.2.min.js"></script>
    <script src="${pageContext.request.contextPath}/Component/json2.js"></script>
    <script src="${pageContext.request.contextPath}/js/jsonTest.js"></script>
    <title>jsonTest</title>
</head>
<body>
<input id="testajax" type="button" value="测试ajax"/>
</body>
</html>

这里面servlet的名字和路径是采用注解的方式配置的。
@WebServlet(name = "Servlet",urlPatterns = "/getjson")

运行效果:

点击“测试ajax”:

这样前台能够对json进行随意的处理了。这就是一个简单的demo。希望能够给你一些帮助和启发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值