structs2 项目开发总结

 

转载他人的文章:只为传播知识,谢谢合作!

http://blog.sina.com.cn/s/blog_6cbe0cff0101j6jl.html                          

request.getContextPath()

 

http://www.cnblogs.com/yqskj/articles/2226401.html

 

http://blog.csdn.net/clj198606061111/article/details/6712248

http://blog.csdn.net/znwnymys/article/details/52507136

http://blog.csdn.net/e421083458/article/details/8769256

 

 

 

 

 

 

管理员:

create database  se  ;

表 admin
create table admin  (
   id int  not null primary key auto_increment ,
   name varchar(45)   not null ,
   pwd varchar(45) not null
);

insert  into admin values( 1 , '旺旺管员'  , '123' );                                                         

       ------------------  -----------------------------------                                                                                                                                             

 index.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>">

  <title>后台管理系统</title>

  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">

  
  
 <script type="text/javascript">
 function form_submit(){
  
  document.getElementById("login").submit();
 }
 function form_reset(){
  document.getElementById("login").reset();
 }
 </script>
 <style type="text/css">
 body{
  background-color: #111111;
 }

 </style>
 
 </head>
<body>

          <div align="center">
      
             <s:form action="admin" id="login" theme="simple">
             <table >
          
              <tr>
      <td background="images/login_07.gif" height="84px">

       <table>
        <tr height="30px">
         <td>
          用户名:
         </td>
         <td>
          <input type="text" name="name" />
         </td>

        </tr>
        <tr height="30px">
         <td>
          密&nbsp; &nbsp;码:
         </td>
         <td>
          <input type="password" name="pwd" />
         </td>
        </tr>

       </table>
      </td>


      <td height="84px">
       <div id="center_middle_right"></div>
      </td>


      <td background="images/login_09.gif" height="84px">
       <table style="margin-top: 0px;">
        <s:submit type="image" src="images/dl.gif" id="id_log"
         method="adminLogin">

        </s:submit>
       </table>
       <img src="images/cz.gif" width="60" height="20"
        οnclick="form_reset()"
        style="margin-left: 3px; margin-top: 6px;">

      </td>


     </tr>
             </table>
                 
                  </s:form>
       
         </div>
 

 </body>
</html>

 

 

------------------------------------------------

 

    web.xml文档代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>structs2_3</display-name>

<filter>
 <!-- 指定Filter的名字,不能为空 -->
   <filter-name>struts2</filter-name>
   <!-- 指定Filter的实现类,此处使用的是Struts2提供的拦截器类 -->
   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>

<filter>
 <!-- 指定Filter的名字,不能为空 -->
   <filter-name>strutsFilterDispatcher</filter-name>
   <!-- 指定Filter的实现类,此处使用的是Struts2提供的拦截器类 -->
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
 </filter>
 <filter-mapping>
   <!-- Filter的名字,该名字必须是filter元素中已声明过的过滤器名字 -->
   <filter-name>struts2</filter-name>
   <!-- 定义Filter负责拦截的URL地址 -->
  <url-pattern>*.action</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <!-- Filter的名字,该名字必须是filter元素中已声明过的过滤器名字 -->
   <filter-name>strutsFilterDispatcher</filter-name>
   <!-- 定义Filter负责拦截的URL地址 -->
   <url-pattern>/*</url-pattern>
 </filter-mapping>

 

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

-------------------------------                                                                                                                                                  

                                                                                                                                                      

       struts。xml 文档代码:

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="1000701096" />
 

<package name="default" extends="struts-default">
   
<action name="admin" class="com.action.Login">
   
<result name="success">/admin/test.jsp</result>
   
<result name="loginerror">/admin/loginerror.jsp</result>
   
<result name="exit">/admin/index.jsp</result>
  
</action>
   
</package>

</struts>   

 

---------------------------------------------------------       

package com.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.dao.AdminDao;

//import com.model.User;

public class Login {

 public String adminLogin() {// ��̨�����¼
  HttpServletRequest request = ServletActionContext.getRequest();
  String name = request.getParameter("name");
  String password = request.getParameter("pwd");
  if(AdminDao.login(name, password))
  {
   return "success";
  }else {
   return "loginerror";
  }
 
 }

 
 public String exit(){
  return "exit";
 }
}

-------------------------------------------------------------------------

 

AdminDao类代码:

 

package com.dao;

import java.util.List;

import javax.jws.soap.SOAPBinding.Use;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.model.Admin;
import com.model.HibernateSessionFactory;
//import com.model.User;

public class AdminDao {
 public static boolean login(String name,String pwd)
 {
  Session session=HibernateSessionFactory.getSession();
  try {
   
   Criteria criteria=session.createCriteria(Admin.class);
   criteria.add(Restrictions.eq("name", name)).add(Restrictions.eq("pwd", pwd));
   List<Admin> admins=criteria.list();
   
   session.close();
   if(admins.isEmpty())
   {
    return false;
   }else {
    return true;
   }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
  return false;
 }
 
}

-----------------------------------------------------------------------

 

package com.model;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@linkhttp://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err.println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
    }
    private HibernateSessionFactory() {
    }
 
 /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

  if (session == null || !session.isOpen()) {
   if (sessionFactory == null) {
    rebuildSessionFactory();
   }
   session = (sessionFactory != null) ? sessionFactory.openSession()
     : null;
   threadLocal.set(session);
  }

        return session;
    }

 /**
     *  Rebuild hibernate session factory
     *
     */
 public static void rebuildSessionFactory() {
  try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }

 /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

 /**
     *  return session factory
     *
     */
 public static org.hibernate.SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 /**
     *  return session factory
     *
     * session factory will be rebuilded in the next call
     */
 public static void setConfigFile(String configFile) {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 /**
     *  return hibernate configuration
     *
     */
 public static Configuration getConfiguration() {
  return configuration;
 }

}

----------------------------------------------------------------------

 

hibernate.cfg.xml

 

 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
 <!-- 方言 -->
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <!-- 链接地址 -->
 <property name="connection.url">
  jdbc:mysql://localhost:3306/se
 </property>
 <!-- 数据库user -->
 <property name="connection.username">root</property>
 <!-- 数据库user密码 -->
 <property name="connection.password">123</property>
 <!-- 连接driver -->
 <property name="connection.driver_class">
  com.mysql.jdbc.Driver
 </property>
 <property name="myeclipse.connection.profile">
  com.mysql.jdbc.Driver
 </property>
 <property name="show_sql">true</property>
 <property name="format_sql">true</property>
 <!-- 映射文件 -->
 <mapping resource="com/model/Admin.hbm.xml" />
</session-factory>
</hibernate-configuration>

 

 

-------------------------------------------------------

Admin.hbm.xml

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <!-- 映射数据库的admin表 -->
    <class name="com.model.Admin" table="admin" catalog="se">
     <!-- 映射id字段 -->
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <!-- 映射name字段 -->
        <property name="name" type="java.lang.String">
            <column name="name" length="45" not-null="true" />
        </property>
        <!-- 映射pwd字段 -->
        <property name="pwd" type="java.lang.String">
            <column name="pwd" length="45" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

 

----------------------------------------------------------------

package com.model;
public class Admin implements java.io.Serializable {
 //ӳ��id
 private Integer id;
 //����Աname
 private String name;
 //����Ա����
 private String pwd;
 /** Ĭ�Ϲ��캯�� */
 public Admin() {
 }
 /** ���캯�� */
 public Admin(String name, String pwd) {
  this.name = name;
  this.pwd = pwd;
 }

 public Integer getId() {
  return this.id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getName() {
  return this.name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPwd() {
  return this.pwd;
 }

 public void setPwd(String pwd) {
  this.pwd = pwd;
 }

}

---------------------------------------------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

---------------------------------------------

 

 

 

 

 

 

 

 

                                                                                                                                         

 

 -----------------------------------------

 

=================================

 

 

盖文档上传测试:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <base href="<%=basePath%>">
  
    <title>My JSP 'upload.jsp' starting page</title>

</head>
<body>
  哈哈哈哈哈
 
    <s:form action="uploadAction!excute.action" enctype="multipart/form-data" method="post">
      <s:file name="file" ></s:file>
   
 
   <!--  <s:file name="file"></s:file> -->  
   <!--  <s:file name="file"></s:file> --> 
   
      <s:submit label="上传"></s:submit>
    </s:form>
 
 
 
</body>
</html>

-------------------------------------------------- 
 <action name="uploadAction" class="com.action.UploadFileAction">
   <result name="success">/admin/index.jsp</result>
  </action>

--------------------------------------------------------------

 

package com.action;

import java.io.File;
import java.io.IOException;
import java.util.List;


import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction extends ActionSupport {
  
 private static final long serialVersionUID = 1L;

 private File file;
 
  private String fileContentType;
  private String fileFileName;
 
  public File getFile() {
   return file;
  }

  public void setFile( File file) {
   this.file = file;
  }

  public String getFileContentType() {
   return fileContentType;
  }

  public void setFileContentType(String fileContentType) {
   this.fileContentType = fileContentType;
  }

  public String getFileFileName() {
   return fileFileName;
  }

  public void setFileFileName(String fileFileName) {
   this.fileFileName = fileFileName;
  }

  public String excute() {
   System.out.println("file:"+ file.getAbsolutePath());
   //拿到上下文路径
   String path = ServletActionContext.getServletContext().getRealPath("/file2");
      System.out.println("path:"+ path);

   if (file != null) {
    File filetemp = new File(path);
  
    if (!filetemp.exists()) {
     //建立文件夹
     filetemp.mkdir();
    }
  
    try {
   
      File f = new File(filetemp, fileFileName);
      System.out.println("上传的文件为:"+fileFileName+"  "+this.fileContentType);
      FileUtils.copyFile( file, f);
     }
     catch (IOException e) {
     e.printStackTrace();
    }
   }
   System.out.println("上传成功");
   return SUCCESS;
 
 }


}

 

--------------------------------------------------

输出结果:

file:C:\Users\Administrator\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\work\Catalina\localhost\structs2_3\upload_479ffc4b_15920b239e3__8000_00000000.tmp
path:C:\Users\Administrator\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\structs2_3\file2
上传的文件为:博士报名.txt  text/plain
上传成功

 

 

 http://blog.sina.com.cn/s/blog_acdc06250101csrl.html 这是转载他人的文档, 传播知识,合作共赢!  以下是转载他人的资料

 

 http://blog.sina.com.cn/s/blog_5f9beca40101dgau.html  ServletActionContext的静态方法

 

 

 

 -============================================================

点覆

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值