zoukankan      html  css  js  c++  java
  • Struts2学习(三)

    获取页面数据

    1、属性驱动

    • 对于属性驱动,我们需要在Action中定义与表单元素对应的所有的属性,因而在Action中会出现很多的getter和setter方法
    • 表单 或 URL 中的 参数名称 跟 Action 类中的属性名称一致,即可
    • 属性驱动的第一种方式(推荐使用的方式,直接将action做一个model(类似bean结构),就可以得到请求参数.)

      index.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body>   <div class="container"> <h4>属性驱动(赞成使用):</h4> <form action="${ pageContext.request.contextPath }/customer/results/register" method="post" > <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <input type="password" name="confirm" placeholder="确认密码"> <input type="submit" value="注册"> </form> <a href="${ pageContext.request.contextPath }/customer/results/register?username=zhangsanfeng">注册</a> </div> </body> </html>

      struts.xml

      <?xml version="1.0" encoding="UTF-8"?>
      
      <!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
          "http://struts.apache.org/dtds/struts-2.5.dtd">
      
      <struts>
           <package name="customer-results" namespace="/customer/results" extends="struts-default">
      
              <action name="register" class="ecut.results.action.RegisterAction">
                  <result>/WEB-INF/pages/results/register_success.jsp</result>
              </action>
      
              <action name="login" class="ecut.results.action.LoginAction">
                  <result>/WEB-INF/pages/results/login_success.jsp</result>
              </action>
      
          </package>
      </struts>

      Action类

      package ecut.results.action;
      
      import org.apache.logging.log4j.LogManager;
      import org.apache.logging.log4j.Logger;
      import com.opensymphony.xwork2.Action;
      
      import ecut.results.entity.Customer;
      
      public class RegisterAction implements Action {
          
          private static final Logger logger = LogManager.getLogger();
          
          private String username ;
          private String password ;
          private String confirm ;
          
          private Customer customer ;
      
          @Override
          public String execute() throws Exception {
              
              if( customer != null ) {
                  logger.info( "customer username : " + customer.getUsername() );
                  logger.info( "customer password : " + customer.getPassword() );
                  logger.info( "customer confirm : " + customer.getConfirm() );
              } else {
                  logger.info( "username : " + username );
                  logger.info( "password : " + password );
                  logger.info( "confirm : " + confirm );
              }
              
              return SUCCESS;
          }
      
          public Customer getCustomer() {
              return customer;
          }
      
          public void setCustomer(Customer customer) {
              this.customer = customer;
          }
          
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      
          public String getConfirm() {
              return confirm;
          }
      
          public void setConfirm(String confirm) {
              this.confirm = confirm;
          }
          
      }

      register_success.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>注册成功</title> </head> <body> <h1>注册成功</h1> <h4> username: ${ username } </h4> <h4> page scope: ${ pageScope.username } </h4> <h4> request scope: ${ requestScope.username } </h4> <h4> session scope: ${ sessionScope.username } </h4> <h4> application scope: ${ applicationScope.username } </h4> <hr> <h4> customer.username : ${ customer.username } </h4> <h4> request scope: ${ requestScope.customer.username } </h4> </body> </html>

      在同一个请求中因此参数保留在requestScope中

    • 属性驱动的第二种方式(反对使用,在action中声明一个model,js不通用)

      index.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body>   <div class="container"> <h4>属性驱动(反对使用):</h4> <form action="${ pageContext.request.contextPath }/customer/results/register" method="post" > <input type="text" name="customer.username" placeholder="用户名"> <input type="password" name="customer.password" placeholder="密码"> <input type="password" name="customer.confirm" placeholder="确认密码"> <input type="submit" value="注册"> </form> </div> </body> </html>

      Action中增加customer 的model

    2、模块驱动

    •  对于模型驱动,使用的Action对象需要实现ModelDriven接口并给定所需要的类型.而在Action中我们只需要定义一个封装所有数据信息的javabean
    • 模块驱动的具体实现

      index.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body>   <div class="container"> <h4>模型驱动:</h4> <form action="${ pageContext.request.contextPath }/customer/results/login" method="post" > <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <input type="submit" value="登录"> </form> </div> </body> </html>

      Action类

      package ecut.results.action;
      
      import org.apache.logging.log4j.LogManager;
      import org.apache.logging.log4j.Logger;
      
      import com.opensymphony.xwork2.Action;
      import com.opensymphony.xwork2.ModelDriven;
      import ecut.results.entity.Customer;
      
      public class LoginAction implements Action , ModelDriven<Customer> {
          
          private static final Logger logger = LogManager.getLogger();
          
          private Customer customer ;
      
          @Override
          public String execute() throws Exception {
              System.out.println( this );
              logger.info( "username : " + customer.getUsername() );
              logger.info( "password : " + customer.getPassword() );
              return SUCCESS;
          }
          
          @Override
          public Customer getModel() {
              logger.info( "调用 getModel方法" );
              //首先实现接口ModelDriven,其次通过getModel方法告诉Struts将参数封装到那个对象去
              if( this.customer == null ) {
                  logger.info( "创建对象" );
                  this.customer = new Customer();
              } 
              return  this.customer ;
          }
      
          public Customer getCustomer() {
              return customer;
          }
      
          public void setCustomer(Customer customer) {
              this.customer = customer;
          }
      
      }

      Action类实现ModelDriven接口并覆盖getModel()方法,在Action类中实例化一个model对象,由Struts2提供的拦截器(ParametersInterceptor)去完成数据封装,让getModel方法返回这个对象。getModel()方法在excute()方法执行之前。因为每一次请求,都是一个新的action,所以getModel()方法中的判断语句是多余的,与spring有所不同。

      注意:getModel 返回的是Action类中定义的model(this.customer),而不能直接返回 new Customer,excute方法和getModel应该使用的是同一个对象,不然会抛出空指针异常

      login_success.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录成功</title> </head> <body> <h1>登录成功</h1> <h4> customer.username : ${ customer.username } </h4> <h4> request scope: ${ requestScope.customer.username } </h4> <hr> <h4> session scope: ${ sessionScope.customer.username } </h4> </body> </html>

    访问 Servlet API

    1、间接访问(推荐使用的方法)
    • 通过ActionContext来访问
        ActionContext context = ActionContext.getContext();
        Map<String,Object> applicationMap = context.getApplication(); // 这个 Map 集合 ServletCotnext
        Map<String,Object> sessionMap = context.getSession(); // 这个 Map 集合与 HttpSession
        HttpParameters params = context.getParameters(); // request parameter
    • 测试案例

      index.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Apache Struts</title> <style type="text/css"> .container { width: 90% ; margin: 10px auto ; box-shadow: 0px 0px 5px 4px #dedede ; padding: 5px 5px ; } ul .required { color : blue ; } ul li { font-size: 16px ; padding: 5px 5px ; } </style> </head> <body> <div class="container"> <h4>登录( 并将用户信息存储到 Session 中 ):</h4> <form action="${ pageContext.request.contextPath }/servlet/login" method="post" > <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <input type="submit" value="登录"> </form> <!-- 提示完应该将session中的值移除 ,提示完再次访问不应该再由提示--> ${ sessionScope.error_message } <%--EL3.0才支持直接调用方法
      ${ pageContext.session.removeAttribute( 'error_message' ) }
      --%> <!-- 使用jsp内置对象删除--> <% session.removeAttribute( "error_message" ) ;%> </div> </body> </html>

       struts.xml

      <?xml version="1.0" encoding="UTF-8"?>
      
      <!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
          "http://struts.apache.org/dtds/struts-2.5.dtd">
      
      <struts>
        <package name="servlet" namespace="/servlet" extends="struts-default">
      
              <default-class-ref class="ecut.results.action.CustomerAction" />
      
              <action name="login" method="login">
                  <!-- 使用了重定向,因此不是同一个request,则通过requestScop是无法获得值的,只能通过session获取 -->
                  <result name="success" type="redirectAction">
                      <param name="actionName">main</param>
                  </result>
                  <result name="input" type="redirect">/results/index.jsp</result>
              </action>
      
              <action name="main">
                  <result>/WEB-INF/pages/results/login_success.jsp</result>
              </action>
      
              <action name="logout" method="logout">
                  <!-- 指定重定向到那个页面,工程名可以省略,若不加/则默认是/servlet -->
                  <result type="redirect">
                      <param name="location">/results/index.jsp</param>
                  </result>
              </action>
      
          </package>
      </struts>

      Action类

      package ecut.results.action;
      
      import java.util.Map;
      
      import com.opensymphony.xwork2.Action;
      import com.opensymphony.xwork2.ActionContext;
      import com.opensymphony.xwork2.ModelDriven;
      
      import ecut.results.entity.Customer;
      
      public class CustomerAction implements Action , ModelDriven<Customer>{
          
          private Customer customer ;
      
          @Override
          public String execute() throws Exception {
              System.out.println( "execute" );
              return SUCCESS;
          }
          
          public String login() throws Exception {
              System.out.println( "login" );
              // 获得 当前正在执行的 Action 的 上下文对象
              ActionContext context = ActionContext.getContext();
              // 通过 ActionContext 的 getSession 来获得 与 HttpSession 对应的 Map 集合
              // 针对这个 Map 的 所有操作 都会立即 "同步" 到 HttpSession 对象中
              Map< String , Object > sessionMap = context.getSession();
              if( "zhangsanfeng".equals( customer.getUsername() ) && "hello2017".equals( customer.getPassword() ) ){
                  sessionMap.put( "customer" ,  this.customer ) ; // 由拦截器去完成这个操作session.setAttribute( "customer" , this.customer );
                  return SUCCESS;
              } else {
                  sessionMap.put( "error_message" ,  "用户名或密码错误" );
                  return  INPUT;
              }
              
          }
          
          public String logout() throws Exception {
              System.out.println( "logout" );
              ActionContext context = ActionContext.getContext();
              Map< String , Object > sessionMap = context.getSession();
              sessionMap.remove( "customer" ) ; // session.removeAttribute( "customer" );
              return SUCCESS;
          }
      
          @Override
          public Customer getModel() {
              if( this.customer == null ){
                  this.customer = new Customer();
              }
              return this.customer;
          }
      
          public Customer getCustomer() {
              return customer;
          }
      
          public void setCustomer(Customer customer) {
              this.customer = customer;
          }
          
      }

      login_success.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录成功</title> </head> <body> <h1>登录成功</h1> <h4> customer.username : ${ customer.username } </h4> <h4> request scope: ${ requestScope.customer.username } </h4> <hr> <h4> session scope: ${ sessionScope.customer.username } </h4> <a href="${ pageContext.request.contextPath }/servlet/logout">注销</a> </body> </html>

      logout_success.jsp

      <%@ page language = "java" pageEncoding = "UTF-8" %>
      <%@ page contentType = "text/html; charset= UTF-8"%>
      <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>注销成功</title> </head> <body> <h1>注销成功</h1> </body> </html>
    2、直接访问(不推荐使用,如果已经使用了 Struts 框架,则应该优先考虑使用 Struts 而不是使用 Servlet )
    • 实现接口并提供 setter 方法(与servlet API 耦合大).
        org.apache.struts2.util.ServletContextAware
        org.apache.struts2.interceptor.ServletRequestAware
        org.apache.struts2.interceptor.ServletResponseAware
    • 通过 ServletActionContext 类的静态方法
        org.apache.struts2.ServletActionContext.getPageContext()
        org.apache.struts2.ServletActionContext.getRequest()
        org.apache.struts2.ServletActionContext.getRequest().getSession()
        org.apache.struts2.ServletActionContext.getResponse()
        org.apache.struts2.ServletActionContext.getServletContext()

    转载请于明显处标明出处

    https://www.cnblogs.com/AmyZheng/p/9204047.html

  • 相关阅读:
    使用aws和tomcat搭建服务器过程中的一些坑.
    10
    9
    8
    7
    6
    5
    hihoCoder 1582 Territorial Dispute 【凸包】(ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛)
    hihoCoder 1584 Bounce 【数学规律】 (ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛)
    hihoCoder 1578 Visiting Peking University 【贪心】 (ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛)
  • 原文地址:https://www.cnblogs.com/AmyZheng/p/9204047.html
Copyright © 2011-2022 走看看