WEB后台传数据给前台



1.利用cookie对象 

Cookie是服务器保存在客户端中的一小段数据信息。使用Cookie有一个前提,就是客户端浏览器允许使用Cookie并对此做出相应的设置。一般不赞成使用Cookie。

(1)后台代码

        Cookiecookie=new Cookie("name", "hello");

        response.addCookie(cookie);

(2)前台代码

   Cookie[]cookies=request.getCookies();

   for(inti=0;i<cookies.length;i++){

               if(cookies[i].getName().toString().equals("name")){

                       out.print(cookies[i].getValue());

               }

   }

 

2.利用session对象

session对象表示特定会话session的用户数据。客户第一次访问支持session的JSP网页,服务器会创建一个session对象记录客户的信息。当客户访问同一网站的不同网页时,仍处于同一个session中。

(1)后台代码

        request.getSession().setAttribute("name",name);

        request.getSession().setMaxInactiveInterval(2);

        response.sendRedirect("welcome.jsp");

(2)前台代码(jsp页面)

Objectuser=request.getSession().getAttribute("name");

 


3.利用request重定向,设置setAttribute

(1)后台代码

request.setAttribute("name", "cute");

request.getRequestDispatcher("welcome.jsp").forward(request,response);  //网址不会改变

PS:如果后台使用的转发代码为 response.sendRedirect("welcome.jsp"); //网址变为welcome.jsp

则request设置的参数无效,因为已经切换到另一个请求了,request参数的有效期为本次请求。

(2)前台代码

Stringname=request.getAttribute("name").toString();

 

4.利用Ajax进行异步数据请求(得到的数据可以以json或xml格式返回,便于处理)

(1)后台代码案例(运用servlet传输数据)

public class TestServlet extends HttpServlet {

 

        /**

         * Constructor of the object.

         */

        publicTestServlet() {

               super();

        }

 

        public voiddoGet(HttpServletRequest request, HttpServletResponse response)

                       throwsServletException, IOException {

               doPost(request,response);

        }

        public voiddoPost(HttpServletRequest request, HttpServletResponse response)

                       throwsServletException, IOException {

 

               response.setContentType("text/html");

               PrintWriterout = response.getWriter();

            Stringdata="[{\"name\":\"apple\",\"price\":23},{\"name\":\"banana\",\"price\":12},{\"name\":\"orange\",\"price\":8}]";

               out.write(data);

               out.flush();

               out.close();

        }

 

        /**

         * Initialization of the servlet. <br>

         *

         * @throws ServletException if an error occurs

         */

        public voidinit() throws ServletException {

               //Put your code here

        }

}
2.前台js请求处理数据代码

function createXMLHttpRequest(){

        varxmlrequest;

        if(window.XMLHttpRequest){

               xmlrequest=newXMLHttpRequest();

        }elseif(window.ActiveXObject){

               try{

                       xmlrequest=newActiveXObject("Msxm12.XMLHTTP");

               }catch(e){

                       try{

                               xmlrequest=newActiveXObject("Microsoft.XMLHTTP");

                       }catch(e){

                               xmlrequest="";

                       }

               }

        }

        returnxmlrequest;

}

//获取数据的函数

function change(){

        var xmlrequest=createXMLHttpRequest();

        xmlrequest.open("POST","TestServlet",true);

        xmlrequest.onreadystatechange=function(){

               if(xmlrequest.readyState==4&&xmlrequest.status==200){

                       vardata=JSON.parse(xmlrequest.responseText);

                       varcontent="<table border=1>";

                       for(vari=0;i<data.length;i++){

                               content+="<tr>";

                               for(oin data[i]){

                                      content+="<td>"+data[i][o]+"</td>";

                               }

                               content+="</tr>";

                       }

                       content+="</table>";

                       document.getElementById("test").innerHTML=content;

               }

        };

        xmlrequest.send();

}

### 前台递BigDecimal到后台的实现方式及注意事项 在Web开发中,从前台后台递`BigDecimal`类型的数据是一个常见的需求。由于前通常是基于字符串形式数据,而后则需要将其解析为具体的数值类型(如`BigDecimal`),因此需要注意以下几个方面。 #### 数据递的方式 1. **JSON格式递** 使用RESTful API接口时,可以通过JSON格式将数据前台发送至后台。此时,前台可以将`BigDecimal`类型的值作为字符串或者数字形式嵌入JSON对象中。 示例代码如下: ```json { "amount": "123.45" } ``` 后台接收到该JSON后,需手动将字符串转换成`BigDecimal`类型[^1]。 2. **表单提交** 当使用HTML表单提交数据时,输入框中的值默认是以字符串形式递给服务器。例如: ```html <form action="/submit" method="post"> <input type="text" name="amount" value="123.45"/> <button type="submit">Submit</button> </form> ``` 此时,后台接收参数并完成类型转换即可。 #### 参数绑定与类型转换 为了简化操作,在Spring框架下可通过以下方式进行自动绑定: 1. **@RequestParam 注解** 若请求参数位于URL查询串或POST请求体中,可以直接利用`@RequestParam`注解配合自定义转换器实现类型映射。 ```java @PostMapping("/process") public String process(@RequestParam BigDecimal amount) { // 处理逻辑... return "success"; } ``` 2. **DTO封装** 定义一个包含`BigDecimal`字段的数据输对象(DTO),并通过`@RequestBody`注解放置于方法形参位置。 ```java public class RequestDto { private BigDecimal amount; // Getter and Setter methods } @PostMapping("/dto-process") public String dtoProcess(@RequestBody RequestDto requestDto) { BigDecimal amount = requestDto.getAmount(); // 进一步业务处理... return "processed"; } ``` #### 注意事项 1. **避免精度丢失** 在构建`BigDecimal`对象时应优先考虑使用字符串构造函数而不是直接入浮点数[^3]。这是因为浮点数本身存在存储误差,可能导致最终结果偏离预期。 2. **校验用户输入** 对来自客户数据务必加以验证,防止非法字符混入引发异常情况发生。比如金额字段只允许含有正负号、小数点以及阿拉伯数字等合法成分。 3. **国际化支持** 不同地区对于货币单位有着各自独特的表达习惯,所以在设计API之初就要考虑到这些差异因素的影响,并作出相应的适配措施。 ```java // 示例:安全地从String转为BigDecimal public static BigDecimal convertToBigDecimal(String strValue) throws NumberFormatException { if (strValue == null || strValue.trim().isEmpty()) { throw new IllegalArgumentException("Input cannot be empty"); } return new BigDecimal(strValue.trim()); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值