一.题目
利用JavaBean实现用户类,包含姓名、性别、爱好,爱好需要用多选框
实现表单1进行获取数据,表单2显示获取结果。
利用Servlet实现逻辑代码
二.实现效果
三.具体实现
1.User实体类
package com.hjj.pojo;/*** @author:嘉佳 Date:2023/11/6 0:10**/
public class User {private String name;private String sex;private String[] hobbies;public User() {}public User(String name, String sex, String[] hobbies) {this.name = name;this.sex = sex;this.hobbies = hobbies;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String[] getHobbies() {return hobbies;}public void setHobbies(String[] hobbies) {this.hobbies = hobbies;}
}
2.dataEntry.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>用户信息录入</title>
</head>
<body>
<%--
设置 input 标签的 type 为checkbox 或者 radio 时,
必须同时设置 input 标签的 value 属性,此时 value 的值就是提交给服务器的值
--%>
<form action=${pageContext.request.contextPath}/show method="post">用户名:<input type="text" name="name"><br>性别:<input type="radio" name="sex" value="男">男<input type="radio" name="sex" value="女">女<br>爱好:<input type="checkbox" name="hobbies" value="吃饭">吃饭<input type="checkbox"name="hobbies" value="睡大觉">睡大觉<input type="checkbox" name="hobbies" value="CRUD">CRUD<br><input type="submit" value="提交">
</form>
</body>
</html>
3.showInfo.jsp
<%@ page import="com.hjj.pojo.User" %><%--Created by IntelliJ IDEA.User: ALASIJIADate: 2023/11/11Time: 17:08To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html>
<head><meta charset="UTF-8"><title>用户信息</title>
</head>
<body>
<%request.setCharacterEncoding("UTF-8");
%>
<%// 从 ServletContext 中获取 JavaBeanUser user = (User) application.getAttribute("user");
%><h1>用户信息</h1>
<p>姓名:<%=user.getName()%>
</p>
<p>性别:<%=user.getSex()%>
</p>
<p>爱好:<% for (String hobby : user.getHobbies()) { %><%= hobby %><% } %>
</p></body>
</html>
4.sevlet文件
package com.hjj.sevletgk.hw9;import com.hjj.pojo.User;import javax.servlet.ServletContext;
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;/*** @author:嘉佳 Date:2023/11/11 16:20**/
@WebServlet("/show")
public class showInfo extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String name = req.getParameter("name");String sex = req.getParameter("sex");String[] hobbies = req.getParameterValues("hobbies");User user = new User(name, sex, hobbies);ServletContext servletContext = getServletContext();servletContext.setAttribute("user",user);resp.setCharacterEncoding("UTF-8");resp.sendRedirect("hw9/showUser.jsp");}
}