首页 > 代码库 > 基于struct2的完整用户登录

基于struct2的完整用户登录

首先在lib下导入struct2相应的jar包

在web.xml配置struct2过滤器

  <filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>

Model,业务逻辑层,验证用户名和密码,暂定都为"admin"。当然如果嵌入项目中,验证的数据可以从数据库提取

LoginCheck.java

public class LoginCheck {
   public boolean isLogin(String username,String password){
	 if(username.equals("admin")&&password.equals("admin")){
		 return true;
	 }else{
		 return false;
	 }
   }
}


Controller

LoginAction.java

为了获得更多的支持,可以继承ActionSupport类

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
	 String username=null;
	 String password=null;
	 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 execute(){
	  LoginCheck lc=new LoginCheck();
	  if(lc.isLogin(username, password)){
		  return "success";
	  }else{
		  return "failure";
	  }
  }
}
配置structs.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
         "http://struts.apache.org/dtds/struts-2.0.dtd">
<!-- struts为配置文件根元素 -->
<struts>
	<!-- Action必须放在指定的包名空间中 -->
	<package name="login" extends="struts-default">
		<!-- 定义login的action,其实现类为LoginAction -->
		<action name="login" class="LoginAction">
			<!-- 定义处理结果与视图资源之间的关系 -->
			<result name="success">/wel.jsp</result>
			<result name="failure">/err.jsp</result>
		</action>
	</package>
</struts>


接下来的都是视图层

登录页面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
    <title>My JSP 'login.jsp' starting page</title>
  </head>
  <body>
  <form action="login.action" method="post">
         用户名<input type="text" name="username"><br>
         密码<input type="password" name="password"><br>
    <input type="submit" value=http://www.mamicode.com/"提交">>


错误处理页面err.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>  
    <title>My JSP 'err.jsp' starting page</title>
  </head>
  <body>
          失败页面
  </body>
</html>

登录成功页面wel.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>  
    <title>My JSP 'wel.jsp' starting page</title>
  </head>  
  <body>
         成功页面<br>
  </body>
</html>

基于struct2的完整用户登录