Servlet作业小练习

一.题目

利用JavaBean实现用户类,包含姓名、性别、爱好,爱好需要用多选框

实现表单1进行获取数据,表单2显示获取结果。

利用Servlet实现逻辑代码

二.实现效果

Servlet作业小练习_第1张图片

Servlet作业小练习_第2张图片

三.具体实现

1.User实体类

package com.hjj.pojo.hw9;

/**
 * @author:嘉佳 Date:2023/11/11 17:54
 **/
public class User {
    private String name;
    private String gender;
    private String[] hobbies;

    public User() {
    }

    public User(String name, String gender, String[] hobbies) {
        this.name = name;
        this.gender = gender;
        this.hobbies = hobbies;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    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" %>


    用户信息录入


<%--
设置 input 标签的 type 为checkbox 或者 radio 时,
必须同时设置 input 标签的 value 属性,此时 value 的值就是提交给服务器的值
--%>
用户名:
性别:
爱好:吃饭 睡大觉 CRUD

3.showInfo.jsp

<%@ page import="com.hjj.pojo.User" %><%--
  Created by IntelliJ IDEA.
  User: ALASIJIA
  Date: 2023/11/11
  Time: 17:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    用户信息


<%
    request.setCharacterEncoding("UTF-8");
%>
<%
    // 从 ServletContext 中获取 JavaBean
    User user = (User) application.getAttribute("user");
%>

用户信息

姓名:<%=user.getName()%>

性别:<%=user.getSex()%>

爱好:<% for (String hobby : user.getHobbies()) { %> <%= hobby %> <% } %>

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 {
    @Override
    protected 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");
    }
}

你可能感兴趣的:(servlet,jsp,javaweb)