To convert the given JSP code to Struts, you need to create an action class and configure it in the struts.xml file. Here's how you can do it:

  1. Create an action class that extends ActionSupport:
public class LoginAction extends ActionSupport {
   private String name;
   private String pwd;

   // Getters and setters for name and pwd
   
   public String execute() {
      Admin admin = new Admin();
      admin.setName(name);
      admin.setPwd(pwd);
      
      LinkBean db = new LinkBean();
      if (db.Login(admin)) {
         // Store the admin object in session for future use
         HttpSession session = ServletActionContext.getRequest().getSession();
         session.setAttribute("admin", admin);

         return SUCCESS;
      } else {
         addActionError("Username or password is incorrect");
         return ERROR;
      }
   }
}
  1. Configure the action class in struts.xml:
<struts>
   <package name="default" extends="struts-default">
      <action name="login" class="com.example.LoginAction">
         <result name="success">wait.jsp</result>
         <result name="error">login.jsp</result>
      </action>
   </package>
</struts>
  1. Modify the JSP code to use the Struts action:
<%@ taglib prefix="s" uri="/struts-tags"%>

<body>
   <s:form action="login">
      <s:textfield name="name" label="Name" />
      <s:password name="pwd" label="Password" />
      <s:submit value="Login" />
   </s:form>
   <s:fielderror />
</body>
  1. Modify the wait.jsp page to retrieve the admin object from session:
<%@ page language="java" import="com.bean.Admin"%>
<%@ page import="javax.servlet.http.HttpSession"%>

<body>
   <% HttpSession session = request.getSession();
      Admin admin = (Admin) session.getAttribute("admin");
      if (admin != null) {
         out.print("恭喜你 !" + admin.getName() + "用户登陆成功!");
      } else {
         out.print("用户名或密码错误,单击<a href='login.jsp'>此处</a>重新登录!");
      }
   %>
</body>

That's it! Now, when the login form is submitted, the action class will be invoked, and based on the result (SUCCESS or ERROR), the appropriate page will be displayed

page language=java import=javautilcombean pageEncoding=utf-8body jspuseBean id=a class=combeanAdmin jspuseBean jspsetProperty name=a property= asetNamerequestgetParametername; asetPwdreque

原文地址: https://www.cveoy.top/t/topic/hJhN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录