struts2 学习笔记(简单的登陆功能实现)

1.简单的jsp页面代码。

登陆界面

1 <body>
2     <form action="login" method="post">
3         用户名<input name='username' type="text"/>
4         密码<input name='password' type="password">
5         <input type="submit" name='s'>
6     </form>
7   </body>

登陆成功界面    几个字,登陆成功
登陆失败界面    几个字,登录失败

 

2.xml配置文件。建立在src目录下。

 1 <?xml version="1.0" encoding="UTF-8"?>
 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    
 6 <struts>
 7 <constant name="struts.devMode" value="true"/>
 8 <package name="hello" extends="struts-default">
 9      <action name="login" class="com.action.LoginAction" method="execute">
10          <result name="success">/success.jsp</result>
11          <result name="error">/error.jsp</result>
12      </action>
13 </package>
14 </struts>

 

3.建立包com.action。新建LoginAction.java。

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;


public class LoginAction {
    public String login(){
        HttpServletRequest request = ServletActionContext.getRequest();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //将用户名和密码定死
        if(username.equals("zyzyzy")&&password.equals("zyzyzy")){
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("password", password);
            return "login";
        }
        else
            return "error";
    }

}

 

4.web.xml。建立的目录为/struts/WebRoot/WEB-INF/web.xml。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7     <filter>
 8         <filter-name>struts2</filter-name>
 9         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
10     </filter>
11     <filter-mapping>
12         <filter-name>struts2</filter-name>
13         <url-pattern>/*</url-pattern>
14     </filter-mapping>
15   <welcome-file-list>
16     <welcome-file>index.jsp</welcome-file>
17   </welcome-file-list>
18 </web-app>


p.s.  jar包导入

 

posted @ 2015-01-25 11:13  码码怡  阅读(153)  评论(0编辑  收藏  举报