你的位置:首页 > Java教程

[Java教程]2. 简单的登录功能实现


1. 在WebContent目录下创建

login.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4  <head><title>登录界面</title></head> 5  <body> 6   <form action="login"> 7    用户名:<input name="username"><br> 8    密 码:<input type="password" name="userpass"><br> 9    <input type="submit" value="提 交">10    <input type="reset" value="取 消">11   </form>12  </body>13 </html>

error.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4  <head> 5   <title></title> 6  </head> 7  <body> 8   <font color="red" size="10">用户或密码错误!</font> 9  </body>10 </html>

welcome.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4  <head> 5   <title>欢迎</title> 6  </head> 7  <body> 8   <font color="red" size="10">登录成功!</font> 9  </body>10 </html>

2. 还必须为Struts提供配置文件,struts.

此文件可以放在src目录,也就是Eclipse中的Java Resources/src目录下,也可以放在WebContent/WEB-INF/classes/目录下,因为在eclipse部署发布web项目时,会自动把struts.

 1 <??> 2 <!DOCTYPE struts PUBLIC 3   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4   "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 <struts> 6   <package name="test" extends="struts-default"> 7         <!--class下为ActionClass,定义视图与物理资源间的映射--> 8     <action name="login" class="com.suo.LoginAction" method="execute"> 9       <result name="success">welcome.jsp</result>10       <result name="error">error.jsp</result>11     </action>12   </package>13 </struts>        

3. 在login.jsp中指定了该表单的action为login,class为com.suo.LoginAction.所以在src下建包com.suo,包中建类LoginAction

 1 package com.suo; 2 import com.opensymphony.xwork2.ActionSupport; 3 //通常继承ActionSupport 4 public class LoginAction extends ActionSupport{ 5 private String username; 6 private String userpass; 7  8 public String execute(){ 9  if("123456".equals(username)&&"123456".equals(userpass))10  return SUCCESS;11  else12  return ERROR;13  }14 15 public String getUsername() {16  return username;17  }18 public void setUsername(String username) {19  this.username = username;20  }21 public String getUserpass() {22  return userpass;23  }24 public void setUserpass(String userpass) {25  this.userpass = userpass;26  }27 }

代码部分就完成了,看看效果!

右键login.jsp,Run as->run on Server 

 

 

输入用户名密码  123456  都OK!