【Java】【EL表达式】快速入门

  • index.jsp
<%@ page import="com.demo.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    JDemo


JDemo

<% User user = new User(); user.setName("张三"); user.setAge("23"); request.setAttribute("user", user); request.getRequestDispatcher("/2.jsp").forward(request, response); %>
  • 2.jsp
<%@ page import="com.demo.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


<%
    User user = (User) request.getAttribute("user");
    out.print(user.getName());
    out.print(user.getAge());
%>
<%--EL属性导航,这种方式可以不用暴力反射也可以直接获取private字段值--%>
${user["name"]}
${user["age"]}


  • User
package com.demo.entity;

public class User {
private String name;
private String age;

@Override
public String toString() {
    return "User{" +
                   "name='" + name + '\'' +
                   ", age='" + age + '\'' +
                   '}';
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    User user = (User) o;

    if (name != null ? !name.equals(user.name) : user.name != null) return false;
    return age != null ? age.equals(user.age) : user.age == null;

}

@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + (age != null ? age.hashCode() : 0);
    return result;
}

public String getName() {

    return name;
}

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

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}
}
  • IndexServlet.java
package com.demo;

import java.io.IOException;
import java.io.PrintWriter;

public class IndexServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    this.doPost(request, response);
}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}

你可能感兴趣的:(【Java】【EL表达式】快速入门)