JSON and Servlet example

JSON and Servlet example

In the previous section of JSON-Java example youhave learned how to create a java class by using JSON classes. Now inthis example we will tell you how to use JSON classes for creating Servlet.

In this example we have created  an object of JSONArrayand then we have added elements into this array by using the method add().To have functionality of JSON in your application you must have JSON-lib andits supported jar files. These are: commons-lang.jar,commons-beanutils.jar, commons-collections.jar,commons-logging.jar, ezmorph.jarand json-lib-2.2.2-jdk15.jar

Here is the example code of JSONServlet.java asfollows:

JSONServlet.java  

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.JSONArray;

public class JSONServlet extends  HttpServlet{
  public void doGet(HttpServletRequest request,
  HttpServletResponse response
)
   throws ServletException,IOException{
 JSONArray arrayObj=new JSONArray();
 arrayObj.add("MCA");
 arrayObj.add("Amit Kumar");
 arrayObj.add("19-12-1986");
 arrayObj.add(24);
 arrayObj.add("Scored");
 arrayObj.add(new Double(66.67));
  PrintWriter out = response.getWriter();
  out.println(arrayObj);
  for(int i=0;i<arrayObj.size();i++){
  out.println(arrayObj.getString(i));
  }
  }
}

We have to do corresponding servlet mapping into web.xmlas given below:

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5"
 <servlet>
  <servlet-name>JSONServlet</servlet-name>
  <servlet-class>JSONServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>JSONServlet</servlet-name>
  <url-pattern>/JSONServlet</url-pattern>
 </servlet-mapping>
</web-app>

To run this example follow this step by step procedure:

  • create a JSONServlet.java class
  • compile JSONServlet and place it into WEB-INF/classes directory
  • Download JSONLibraries and place it into Tomcat's lib directory
  • Start Tomcat Webserver and type
    http://localhost:8080/JSON/JSONServlet  into browser's address bar you will have following output on your browser.

Output:


Download JSON-Servlet Project code


这个问题有些宽泛,我会尽力回答,但需要您提供更多的细节。 基于ElementUI+JSON+Servlet的完整案例通常是一个Web应用程序,其中ElementUI是一个基于Vue.js的UI框架,JSON是一种数据格式,而ServletJava Web应用程序中的一种Java类,用于处理HTTP请求和响应。 在这个案例中,可能会使用ElementUI创建前端界面,JSON用于传输数据,Servlet用于处理HTTP请求和响应。例如,您可以使用ElementUI创建一个表单,并使用JSON将表单数据发送到Servlet中进行处理和验证。 以下是一个基本的示例: 1. 创建一个HTML页面并使用ElementUI创建表单。 ```html <!DOCTYPE html> <html> <head> <title>ElementUI + JSON + Servlet example</title> <meta charset="UTF-8"> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> </head> <body> <div id="app"> <el-form ref="form" :model="form" label-width="80px"> <el-form-item label="Name"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label="Email"> <el-input v-model="form.email"></el-input> </el-form-item> <el-form-item label="Password"> <el-input v-model="form.password" type="password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">Submit</el-button> </el-form-item> </el-form> </div> <script> var app = new Vue({ el: '#app', data: { form: { name: '', email: '', password: '' } }, methods: { submitForm: function () { var self = this; var formData = JSON.stringify(this.form); // Send form data to servlet var xhr = new XMLHttpRequest(); xhr.open('POST', 'servlet-url', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); if (response.success) { self.$message({ message: 'Form submitted successfully!', type: 'success' }); } else { self.$message({ message: 'Form submission failed!', type: 'error' }); } } }; xhr.send(formData); } } }); </script> </body> </html> ``` 2. 创建一个Servlet类来处理收到的表单数据。 ```java import java.io.IOException; import java.io.PrintWriter; 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 org.json.JSONObject; @WebServlet("/servlet-url") public class FormServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FormServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject formData = new JSONObject(request.getReader().readLine()); String name = formData.getString("name"); String email = formData.getString("email"); String password = formData.getString("password"); // Perform validation and database operations here // Send response back to client response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject jsonResponse = new JSONObject(); jsonResponse.put("success", true); out.print(jsonResponse.toString()); out.flush(); } } ``` 在这个Servlet类中,我们首先从请求中获取表单数据,然后执行任何必要的验证和数据库操作,最后返回一个JSON响应,表示表单提交成功。 请注意,这只是一个基本的示例,实际应用程序可能需要更多的代码和功能来满足要求。同时,还需要在Web应用程序中包含ElementUI和JSON库的依赖项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值