JavaWeb - 【Filter】表单显示

本文通过一个名为MyFilter的Servlet过滤器实例,展示了如何处理HTTP请求并动态填充数据到页面。MyFilter拦截了/product-input.action和/product-save.action路径,根据路径将请求转发到对应的jsp页面,并在保存产品信息时填充了产品对象。此外,还提供了index.jsp、product_input.jsp和product_details.jsp的页面代码,用于展示商品录入和详情显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Filter入门示例

  • 需求分析
  • 程序设计
    • MyFilter
    • index.jsp
    • product_input.jsp
      • < table >
    • product_details.jsp
  • 效果测试

一:需求分析

在这里插入图片描述

二:程序设计

1> MyFilter

package xyz.xx.filter;

import org.apache.commons.beanutils.BeanUtils;
import xyz.xx.pojo.Product;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String servletPath = req.getServletPath();
        String path = null;

        if("/product-input.action".equals(servletPath)){
            path = "/WEB-INF/pages/product_input.jsp";
        }else if("/product-save.action".equals(servletPath)){
            path = "/WEB-INF/pages/product_details.jsp";
            Product p1 = new Product();
            try {
                BeanUtils.populate(p1,req.getParameterMap());
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            p1.setProductId(10012);
            servletRequest.setAttribute("product",p1);
        }

        if(path!=null) {
            servletRequest.getRequestDispatcher(path).forward(servletRequest, servletResponse);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
      <a href="product-input.action">商品录入</a>
  </body>
</html>

product_input.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="product-save.action" method="post">
    <table>
        <tr>
            <td>ProductName:</td>
            <td><input type="text" name="productName"></td>
        </tr>
        <tr>
            <td>ProductDesc:</td>
            <td><input type="text" name="productDesc"></td>
        </tr>
        <tr>
            <td>ProductPrice:</td>
            <td><input type="text" name="productPrice"></td>
        </tr>
        <tr>
            <td colspan="2"><input style="width:100%;height:30px" type="submit" value="Submit"></td>
        </tr>
    </table>
</form>
</body>
</html>

product_details.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style type="text/css">
        table{
            width: 600px;
            text-align: center;
            border: red 1px solid;
            border-collapse: collapse;
        }
        tr,th,td{
            border: red 3px solid;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <table align="center">
        <tr>
            <th>ProductId</th>
            <th>ProductName</th>
            <th>ProductDesc</th>
            <th>ProductPrice</th>
        </tr>
        <tr>
            <td>${requestScope.product.productId}</td>
            <td>${requestScope.product.productName}</td>
            <td>${requestScope.product.productDesc}</td>
            <td>${requestScope.product.productPrice}</td>
        </tr>
    </table>
</body>
</html>
三:效果测试

在这里插入图片描述





在这里插入图片描述

<think>嗯,用户想了解Java Web中用户注册表单的数据校验方法。首先,我需要回忆一下相关的知识。根据之前提供的引用内容,特别是引用[2]和引用[4],用户注册表单的校验通常涉及前端和后端的校验。 首先,前端的校验一般使用HTML和JavaScript,这样可以即时反馈给用户,比如检查输入是否为空、密码是否符合复杂度要求、邮箱格式是否正确等。例如,引用[2]提到了使用JavaScript进行输入框是否空的判断,以及下拉列表事件的处理。这时候需要确保用户在提交表单之前,数据已经符合基本要求,减少不必要的服务器请求。 然后是后端校验,这部分通常在Servlet或者Controller中进行,处理来自前端的请求,并进一步验证数据的合法性。引用[1]和[4]提到使用JavaBean或者FormBean来封装表单数据,并进行校验。比如,RegisterFormBean可能包含校验逻辑,或者在Service层调用DAO之前进行数据验证。例如,用户名的唯一性检查可能需要查询数据库,这通常在Service层处理,如引用[4]中的UserDaoImpl的insert方法。 另外,正则表达式在前后端校验中都很重要,比如邮箱格式、手机号格式的验证。前端可以用JavaScript的正则表达式,后端Java也可以用Pattern来匹配。同时,防止XSS攻击和SQL注入也是后端校验的一部分,需要过滤或转义用户输入的特殊字符。 可能还需要考虑国际化和本地化的校验,比如不同地区的手机号格式不同,或者密码策略的不同要求。此外,错误信息的友好提示也很重要,前端和后端都需要返回易于理解的错误信息,帮助用户正确填写表单。 用户可能还关心如何结合框架来简化校验,比如使用Hibernate Validator或者Spring的校验注解,但根据提供的引用,用户可能使用的是较传统的Servlet+JSP模式,所以重点应放在基础的前后端校验实现上。 总结一下,实现步骤大致是:前端使用HTML和JavaScript进行基本校验,后端Servlet接收数据后进行详细校验,包括格式、唯一性等,最后调用DAO层将数据存入数据库。同时,要确保安全性,如防止重复提交、使用HTTPS传输数据等。</think>在Java Web开发中,用户注册表单的数据校验需要结合前端和后端共同实现,以下是具体实现方式: ### 一、前端校验(客户端校验) 1. **基础格式校验** - 使用HTML5原生属性实现即时验证: ```html <input type="text" name="username" required pattern="[A-Za-z0-9]{4,16}"> <input type="email" name="email" required> ``` - 通过JavaScript增强校验逻辑: ```javascript function validateForm() { if (document.getElementById("password").value.length < 8) { alert("密码至少8位"); return false; } // 其他校验逻辑... } ``` 引用示例中的表单验证方法[^2] 2. **实时反馈机制** - 通过事件监听实现输入时校验: ```javascript document.getElementById("username").addEventListener("blur", checkUsername); ``` ### 二、后端校验(服务端校验) 1. **Servlet层校验** 在`doPost()`方法中处理请求: ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); if (username == null || username.trim().isEmpty()) { request.setAttribute("error", "用户名不能为空"); request.getRequestDispatcher("/register.jsp").forward(request, response); return; } // 更多校验逻辑... } ``` 引用[3]中的登录页面处理逻辑 2. **业务层校验** 在Service层进行复杂校验: ```java public class UserService { public boolean checkUsernameExist(String username) throws SQLException { return userDao.findByUsername(username) != null; } } ``` 引用[4]中的Service层实现 3. **正则表达式校验** 使用Java标准库进行格式验证: ```java if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) { throw new ValidationException("手机号格式错误"); } ``` ### 三、数据封装与校验框架 1. **JavaBean封装** 创建表单数据对象: ```java public class RegisterFormBean { private String username; private String password; // 添加校验方法... } ``` 引用[1]中的RegisterFormBean实现 2. **校验框架集成** 使用Hibernate Validator等框架: ```java public class User { @NotNull(message = "用户名不能为空") @Size(min=4, max=16) private String username; } ``` ### 四、安全增强措施 1. **防止重复提交** - 使用Token机制: ```jsp <input type="hidden" name="token" value="${sessionScope.token}"> ``` 2. **输入过滤** ```java String safeInput = HTMLFilter.filter(request.getParameter("content")); ``` ### 五、错误处理机制 1. **统一错误返回** ```java Map<String, String> errors = new HashMap<>(); if (invalid) errors.put("email", "邮箱格式错误"); request.setAttribute("errors", errors); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值