struts.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>
<constant name="struts.objectFactory" value="spring"></constant>
    <constant name="struts.custom.i18n.resources" value="com.training.resource.tab"></constant>
    
<package name="" extends="struts-default">
<interceptors>
    <interceptor name="login" class="com.training.interceptor.CheckLoginInterceptor" />
<interceptor-stack name="teamwareStack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="login" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="teamwareStack"></default-interceptor-ref> <global-results>
<result name="loginError">/login.jsp</result>
</global-results>



 <!-- =======================================User Action===============================================  -->
   <action name="language" class="LoginAction" method="language">
<result name="Engineer" type="redirectAction">
    <param name="actionName">viewRequest</param></result>
<result name="SDM" type="redirectAction">
    <param name="actionName">SDMRequest</param></result>
<result name="IT Manager" type="redirectAction">
<param name="actionName">allRequest</param></result>
<result name="Admin">/Admin/Admin.jsp </result>
<result name="IT Staff">/ITStaff/Staff.jsp </result>
<result name="error">/login.jsp</result>
</action>

<action name="index" class="LoginAction">
<result name="Engineer" type="redirectAction">
<param name="actionName">viewRequest</param></result>
<result name="SDM" type="redirectAction">
<param name="actionName">SDMRequest</param></result>
<result name="IT Manager" type="redirectAction">
<param name="actionName">allRequest</param></result>
<result name="Admin">/Admin/Admin.jsp </result>
<result name="IT Staff">/ITStaff/Staff.jsp </result>
<result name="error">/login.jsp</result>
</action>

<action name="logout" class="LogoutAction" method="logoutPage">
<result name="success">/login.jsp</result>
    </action> <action name="changepassword" class="PWDchangeAction">
<result name="Engineer">/Engineer/EngineerchangePSW.jsp </result>
<result name="SDM"> /SDM/SDMchangePSW.jsp</result>
<result name="IT Manager">/Manager/ManagerchangePSW.jsp</result>
<result name="Admin"> /Admin/AdminchangePSW.jsp</result>
<result name="IT Staff"> /ITStaff/StaffChangePSW.jsp</result>
</action>
         </package>
</struts>
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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/IT
  </property>
<!--dialect,每个数据库对应的Dialet匹配其平台特性-->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
  </property>
<!--数据库密码-->
<property name="connection.password">551775</property>
<!--数据库驱动-->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
  </property>
<!--是否将运行产生的sql语句输出到日志--> <property name="hibernate.show_sql">True</property>
<!--Examda,是否使用数据库外连接-->
<property name="hibernate.use_out_join">True</property>
<property name="hbm2ddl.auto">update</property>
<property name="format_sql">true</property>
<mapping resource="com/training/model/User.hbm.xml" />
<mapping resource="com/training/model/Request.hbm.xml" />
<mapping resource="com/training/model/RequestType.hbm.xml" />
</session-factory>
</hibernate-configuration>
hibernateUtil.java
package com.training.hibernate;import org.hibernate.*;
import org.hibernate.cfg.Configuration;public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} public static void shutdown() {
getSessionFactory().close();
}
}

解决方案 »

  1.   

    User.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 package="model"> <class name="com.training.model.User" table="User" mutable="true"
    dynamic-update="true">
    <id name="UID" type="integer" column="UID">
    <generator class="native" />
    </id>
    <property name="Name" unique="true"></property>
    <property name="Email" unique="true"></property>
    <property name="Password"></property>
    <property name="Rloe"></property>
    <many-to-one name="Report_Manage" column="Report_ID"></many-to-one>
    </class>

    </hibernate-mapping>
    UserAdd.java
    package com.training.action.userAction;import java.util.List;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    import com.training.model.User;
    import com.training.service.impl.UserServiceImpl;@SuppressWarnings("serial")
    public class UserAdd extends ActionSupport {
    private String name = null;
    private String password = null;
    private String email = null;
    private String role = null;
    private String reporter = null;
    UserServiceImpl userService; public void setUserService(UserServiceImpl userService) {
    this.userService = userService;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public String getPassword() {
    return password;
    } public void setPassword(String password) {
    this.password = password;
    } public String getEmail() {
    return email;
    } public void setEmail(String email) {
    this.email = email;
    } public String getRole() {
    return role;
    } public void setRole(String role) {
    this.role = role;
    } public String getReporter() {
    return reporter;
    } public void setReporter(String reporter) {
    this.reporter = reporter;
    } public String execute() throws Exception {
    try {
    User user = new User();
    User a = new User(); HttpServletRequest request = ServletActionContext.getRequest();
    role = request.getParameter("Role");
    user.setName(name);
    user.setPassword(Integer.toHexString(password.hashCode()));
    user.setEmail(email);
    user.setRloe(role); if (("Engineer").equals(role)) {
    reporter = request.getParameter("Reporter");
    a.setName(reporter);
    int ID = userService.getIDByName(a);
    a.setUID(ID);
    user.setReport_Manage(a);
    } userService.addUser(user);
    return SUCCESS;
    } catch (InstantiationError ex) {
    throw ex;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public void validate() {
    List nameList;
    List emailList;
    try {
    nameList = userService.userNameAll();
    emailList = userService.userEmailAll();
    for (int i = 0; i < nameList.size(); i++) {
    if (nameList.get(i)!=null && nameList.get(i).equals(name)) {
    this.addFieldError("Name", "the Name should be unique");
    }
    }
    for (int j = 0; j < emailList.size(); j++) {
    if (emailList.get(j)!=null && emailList.get(j).equals(email)) {
    this.addFieldError("Email", "the Email should be unique");
    }
    }
    if (name == null || name.trim().equals("")) {
    this.addFieldError("Name", "the name can not be null");
    }
    if (email == null || email.trim().equals("")) {
    this.addFieldError("Email", "the email can not be null");
    }
    if (password == null || password.trim().equals("")) {
    this.addFieldError("Password", "the password can not be null");
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }}
      

  2.   

    UserServiceImpl.javapackage com.training.service.impl;import java.util.ArrayList;
    import java.util.List;
    import com.training.dao.impl.UserDaoImpl;
    import com.training.model.User;
    import com.training.service.UserService;public class UserServiceImpl implements UserService {
    private UserDaoImpl userDao; public void setUserDao(UserDaoImpl userDao) {
    this.userDao = userDao;
    } /**
     * When a user Login,check its name and password in the database
     * 
     * @param user The one apply to login
     * @return A boolean value, if the user in the database,
     * it will return true,else it will return a false value
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public boolean checkLogin(User user) throws Exception {
    String hql = "from User user where user.Name=:s1 and user.Password=:s2";
    try{
          List list = userDao.queryByTwo(hql, user.getName(), user.getPassword());
          if (list.size() == 0)
           return false;
          else
           return true;
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } /**
     * User can change password by filling in correct new password and 
     * passwordConfirm
     * 
     * @param user     The one apply to change password
     * @param password The new password filled in
     * @param passwordConfirm The new password confirm
     * @return A boolean value,if the user fill in the correct new password
     * and password confirm,it will return true,else it will return a false
     * @throws Exception 
     */
    public boolean changePWD(User user, String password, String passwordConfirm) 
    throws Exception {
    try{
    if (password.equals(passwordConfirm) && password != null
    && !password.trim().equals("") && passwordConfirm != null
    && !passwordConfirm.trim().equals("")) {
    user.setPassword(password);
    userDao.changePWD(user);
    return true;
           } else
    return false;

    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } /**
     * The name of every user is unique.Check the role of one user by the name
     * 
     * @param user The one to be checked
     * @return      A string value which will info the user role
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public String checkRole(User user1){
    String hql = "from User user1 where user1.Name =:s1";
        ArrayList<User> list = (ArrayList<User>) userDao.queryByOne(hql, user1
                   .getName());
    return list.get(0).getRloe();

    } @SuppressWarnings("unchecked")
    public String checkRoleByID(User user1) throws Exception {
    String hql = "from User user1 where user1.UID =:s1";
    try{
         ArrayList<User> list = (ArrayList<User>) userDao.queryInt(hql, user1
                        .getUID());
             return list.get(0).getRloe();
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } public void addUser(User user) throws Exception {
    try{
    userDao.addUser(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List userList(User user) throws Exception {
    String hql = "from User user where user.Name<>'SystemSDM'";
    try{
         return userDao.query(hql);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    } } public void deleteUser(User user) throws Exception {
    try{
         userDao.deleteUser(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List getUserDetail(User user) throws Exception {
    try{
         List list = userDao.userDetail(user);
         return list;
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    } } public void updateUser(User user) throws Exception {
    try{
         userDao.updateUser(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List getAllSDM(User user) throws Exception {
    String hql = "from User user where user.Rloe='SDM' and user.Name <> 'SystemSDM'";
    try{
         return userDao.query(hql);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    } } public int getIDByName(User user) throws Exception {
    try{
         return userDao.getIDByName(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List getNameByID(User user) throws Exception {
    try{
         return userDao.getNameByID(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } public void whenDeleteSDM(User user) throws Exception {
    try{
         userDao.whenDeleteSDM(user);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List arrangeEngineer(User user) throws Exception {
    String hql = "from User user where user.Report_Manage.UID ='29'";
    try{
         return userDao.query(hql);
    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } /**
     * Get all the user name in the database. This function will be used 
     * when create or update a user to confirm the unique of name
     * 
     * @return A list of use name in database
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public List userNameAll() throws Exception {
    String hql = "select user.Name from User user";
    try{
    ArrayList<String> list = (ArrayList<String>) userDao.query(hql);
        return list;

    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    }
    } /**
     * Get all the user email in the database. This function will be used 
     * when create or update a user to confirm the unique of email
     * 
     * @return A list of use email in database
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public List userEmailAll() throws Exception {
    String hql = "select user.Email from User user";
    try{
    ArrayList<String> list =  (ArrayList<String>) userDao.query(hql);
        return list;

    } catch (NoSuchMethodError ne) {
    throw ne;
    } catch (Exception e) {
    throw e;
    } }}
      

  3.   

    UserDaoImpl.javapackage com.training.dao.impl;import java.util.ArrayList;
    import java.util.List;
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import com.training.dao.UserDao;
    import com.training.hibernate.HibernateUtil;
    import com.training.model.User;public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    BaseDaoImpl bd = new BaseDaoImpl(); public void addUser(User user) {
    try {
    this.getHibernateTemplate().save(user);
    } catch (RuntimeException e) {
    throw e;
    }
    } public void deleteUser(User user) {
    try {
    this.getHibernateTemplate().delete(user);
    } catch (RuntimeException e) {
    throw e;
    }
    } public void updateUser(User user) {
    try {
    this.getHibernateTemplate().update(user);
    } catch (RuntimeException e) {
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public List userDetail(User user) {
    String hql = "from User user where user.UID =:s1";
    return bd.baseQueryInt(hql, user.getUID()); } @SuppressWarnings("unchecked")
    public List queryInt(String Hql, int s1) {
    return bd.baseQueryInt(Hql, s1);
    } @SuppressWarnings("unchecked")
    public List query(String Hql) {
    return bd.baseQuery(Hql);
    } @SuppressWarnings("unchecked")
    public List queryByOne(String Hql, String s1) {
    return bd.baseQueryByOne(Hql, s1);
    } @SuppressWarnings("unchecked")
    public List queryByTwo(String Hql, String s1, String s2) {
    return bd.baseQueryByTwo(Hql, s1, s2);
    } @SuppressWarnings("unchecked")
    public List getNameByID(User user) {
    String hql = "from User user where user.Report_Manage.UID =:Report_Manage";
    Session session = null;
    try {
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query query = (Query) session.createQuery(hql);
    query.setInteger("Report_Manage", user.getReport_Manage().getUID());
    ArrayList<User> list = (ArrayList<User>) query.list();
    List<String> name = new ArrayList();
    for (int i = 0; i < list.size(); i++) {
    name.add(list.get(i).getName());
    }
    return name;
    } catch (HibernateException e) {
    session.getTransaction().rollback();
    throw e;
    }
    } @SuppressWarnings("unchecked")
    public int getIDByName(User user) {
    String hql = "from User user where user.Name =:Name";
    Session session = null;
    try {
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query query = (Query) session.createQuery(hql);
    query.setString("Name", user.getName());
    ArrayList<User> list = (ArrayList<User>) query.list();
    int id = list.get(0).getUID();
    return id;
    } catch (HibernateException e) {
    session.getTransaction().rollback();
    throw e;
    }
    } public void changePWD(User user) {
    String hql = "update User user set user.Password =:Password where user.Name =:Name";
    Session session = null;
    try {
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query query = (Query) session.createQuery(hql);
    query.setString("Password", user.getPassword());
    query.setString("Name", user.getName());
    query.executeUpdate();
    session.getTransaction().commit();
    session.close();
    } catch (HibernateException e) {
    session.getTransaction().rollback();
    throw e;
    }
    } public void whenDeleteSDM(User user) {
    String hql = "update User user set user.Report_Manage.UID ='29' where user.Report_Manage.UID =:Report_Manage";
    Session session = null;
    try {
    session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query query = (Query) session.createQuery(hql);
    query.setInteger("Report_Manage", user.getReport_Manage().getUID());
    query.executeUpdate();
    session.getTransaction().commit();
    session.close();
    } catch (HibernateException e) {
    session.getTransaction().rollback();
    throw e;
    } }
    }
      

  4.   

    就是分享点非商业性的东西,违规的事咱不干,m a i l/b l o g都禁了.
      

  5.   

    CheckLoginInterceptor.javapackage com.training.interceptor;import java.util.Map;
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
    import com.training.action.userAction.Login;@SuppressWarnings("serial")
    public class CheckLoginInterceptor extends AbstractInterceptor {
    public static final String Login_Key = "name"; @SuppressWarnings("unchecked")
    public String intercept(ActionInvocation actionInvocation) throws Exception {
    Object action = actionInvocation.getAction();
    if (action instanceof Login) {
    return actionInvocation.invoke();
    }
    Map session = actionInvocation.getInvocationContext().getSession();
    String login = (String) session.get(Login_Key);
    if (login != null && login.length() > 0) {
    return actionInvocation.invoke();
    } else {
    return "loginError";
    }
    }
    }UserServiceTest.javapackage com.training.utilTest;
    import java.util.List;import org.junit.After;
    import org.junit.Assert;import com.training.model.User;
    import com.training.service.UserService;
    import com.training.service.impl.UserServiceImpl;import org.junit.BeforeClass;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserServiceTest {
    static ApplicationContext beans;
    static UserService us ;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    beans = new ClassPathXmlApplicationContext("applicationContext.xml");
        us = (UserServiceImpl) beans.getBean("userService");
    } @After
    public void tearDown() throws Exception {
    }

        @org.junit.Test
    public void testCheckLogin() throws Exception{
    User user = new User();
    User user1 = new User();
    user.setName("Heidi");    user1.setName("Larry"); 
    user.setPassword("be32");  user1.setPassword("abc");
    boolean a0=us.checkLogin(user);
    boolean a1=us.checkLogin(user1);
    Assert.assertEquals(true, a0);
         Assert.assertEquals(false, a1);
    }
        
        @org.junit.Test
        public void testChangePWD() throws Exception{
         User user = new User();
         boolean a0=us.changePWD(user, "", "");
         boolean a1=us.changePWD(user, "ab", "adf");
         boolean a2=us.changePWD(user, "123", "123");
         Assert.assertEquals(false, a0);
         Assert.assertEquals(false, a1);
         Assert.assertEquals(true, a2);
        
        
        }
        
        @org.junit.Test
        public void testCheckRoleByID() throws Exception{
         User user = new User();
         user.setUID(3);
         String a=us.checkRoleByID(user);
         Assert.assertEquals("Engineer", a);
        }
        
        @SuppressWarnings("unchecked")
    @org.junit.Test
        public void testGetUserDetail() throws Exception{
         User user = new User();
         user.setUID(3);
         List<User> list=us.getUserDetail(user);
         Assert.assertEquals("Engineer", list.get(0).getRloe());
        }
        
        @org.junit.Test
        public void testGetIDByName() throws Exception{
         User user = new User();
         user.setName("Heidi");
         int id=us.getIDByName(user);
         Assert.assertEquals(3, id);
        }
        
        @SuppressWarnings("unchecked")
    @org.junit.Test
        public void testGetNameByID() throws Exception{
         User user = new User();
         User reporter = new User();
         reporter.setUID(2);
         user.setReport_Manage(reporter);
         List<String> name=us.getNameByID(user);
         Assert.assertEquals("Heidi", name.get(0));
        }
        
        
    }