Preface:

Function module: login, registration, personal information management, address book management, schedule, file management. The login and registration pages should have input validation in the form of a struts2 validation framework (-validation.xml configuration file). (2) The query function of the address book must support fuzzy query. Note: Registration needs to be model-driven.

This is the requirement given by the teacher. In fact, the current experiment has always been a small case of Struts2, with less complicated logic and single function module, similar to the library management system last time. If we want to improve it, the follow-up work will be very heavy. Decide to use Spring +Struts2+ Hibernate.


Functional modules:

  1. The login and registration of individual users, the modification of personal information and the change of avatar after successful login. (An interceptor is used and you can only do this if you are logged in, otherwise you can only access the home page.)
  2. You can add, delete, or modify contacts in the address book by name or mobile phone number.
  3. Add, delete, change and check the schedule.

I. Environment building:

Use MyEclipse + MySQL. Framework uses Struts2+Spring+Hibernate.

1. Database:

Select * from user; select * from friends;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `userId` int(100) NOT NULL AUTO_INCREMENT,
  `userName` varchar(100) NOT NULL.`password` varchar(100) NOT NULL.`work` varchar(100) NOT NULL.`realName` varchar(100) NOT NULL.`phone` varchar(100) NOT NULL.PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for `friends`
-- ----------------------------
DROP TABLE IF EXISTS `friends`;
CREATE TABLE `friends` (
  `friendId` int(100) NOT NULL AUTO_INCREMENT,
  `userId` int(100) NOT NULL.`friendName` varchar(100) NOT NULL.`friendPhone` varchar(100) NOT NULL.`friendCompany` varchar(100) NOT NULL.`friendQQ` varchar(100) NOT NULL.PRIMARY KEY (`friendId`),
  KEY `user_id` (`userId`),
  CONSTRAINT `user_id` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1'.'hlk1135'.'123456'.'students'.'Shi Kun'.'17862821585');

-- ----------------------------
-- Records of friends
-- ----------------------------
INSERT INTO `friends` VALUES ('1'.'1'.'Lu Chi-lu'.'17862821111'.Alibaba.'862186722');
INSERT INTO `friends` VALUES ('2'.'1'.'Li Dongjie'.'17862821111'."Baidu".'111111111');
INSERT INTO `friends` VALUES ('3'.'1'.'Cao Hengyang'.'17862821111'.'Google'.'111111111');
Copy the code

2. Construction of project structure

When the SSH environment was set up initially, Add in Myeclipse was used to import it automatically, but due to conflicts between JAR packages, I changed to manually import all of them. There are a few jars that are unnecessary, but I can assure you that there are absolutely no conflicts and that SSH projects will definitely run well. Struts2+Spring3+Hibernate4 integrate JAR package download

1) web. XML:


       
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <! -- Configure Spring listeners to initialize ApplicationContext objects -->  
  <listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  </listener>  
  <context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>  
  </context-param>  
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
    <! -- Automatic scan action -->  
    <init-param>  
      <param-name>actionPackages</param-name>  
      <param-value>com.hlk.action</param-value>  
    </init-param> 
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>
 </web-app>Copy the code

Error: Classpath: classpath: classpath: classpath: classpath: classpath: classpath: classpath

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/beans.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/beans.xml]  
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/beans.xml] Copy the code

Finally, after continuous testing and adjustment, the following conclusions are obtained for reference only:

<! -- needed for ContextLoaderListener -->
 <! -- Specify the location of spring configuration file -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <! The configuration file can be loaded successfully.
  <! -- <param-value>/WEB-INF/classes/beans.xml,/WEB-INF/classes/action-beans.xml</param-value> -->
  <! Failed to load configuration file
  <! -- <param-value>/WEB-INF/beans.xml,/WEB-INF/action-beans.xml</param-value> -->
  <! The configuration file can be loaded successfully.
  <! -- <param-value>classpath:*beans.xml</param-value> -->
  <! Failed to load configuration file
  <! -- <param-value>classpath:beans.xml,action-beans.xml</param-value> -->
  <! The configuration file can be loaded successfully.
  <param-value>classpath:beans.xml,classpath:action-beans.xml</param-value>
 </context-param>
 <! -- Bootstraps the root web application context before servlet initialization -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>Copy the code

Stackoverflow:

Do not use classpath. This may cause problems with different ClassLoaders (container vs. application). WEB-INF is always the better choice.Copy the code

2) applicationcontext.xml :(Spring configuration file)


             
<beans xmlns="http://www.springframework.org/schema/beans"      
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"      
    xmlns:tx="http://www.springframework.org/schema/tx"      
    xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">  

    <! Automatic scanning of DAO and service packages (automatic injection)
    <context:component-scan base-package="com.hlk.dao,com.hlk.service"/>
    <! -- Import properties file -->
    <context:property-placeholder location="/WEB-INF/classes/config.properties"/>
    <! -- Configure data source -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <! DriverClass (URL); Druid DriverClass (URL);
        <property name="driverClassName" value="${driverClassName}" />
        <! -- Basic properties URL, user, password -->
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <! -- Configure initial size, min, Max -->
        <property name="initialSize" value="3" />
        <property name="minIdle" value="3" />
        <property name="maxActive" value="20" />
        <! -- Set timeout time for waiting to get connections -->
        <property name="maxWait" value="60000" />
        <! -- How often is it configured to detect idle connections that need to be closed in milliseconds -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <! Set the minimum time for a connection to live in the pool, in milliseconds.
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <! -- Configure filters to monitor statistics interception -->
        <property name="filters" value="stat" />
    </bean>
    <! Configure hibernate Session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <! Automatically scan hibernate class files configured in annotation mode    
        <property name="packagesToScan">
            <list>
                <value>com.hlk.model</value>
            </list>
        </property> 
    </bean>
    <! Transaction management with annotations -->    
    <bean id="txManager" name="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">    
        <property name="sessionFactory" ref="sessionFactory"></property>          
    </bean>
    <! Configure things with annotations -->  
    <tx:annotation-driven transaction-manager="txManager"/> 
</beans>Copy the code

The druid database connection pool is used here, and the code comments are very detailed, which I won’t cover here.

3) Config.properties:

hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://127.0. 01.:3306/information? useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false
jdbc_username=root
jdbc_password=

hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=trueCopy the code

Struts2 configuration file struts.xml:


       

       
<struts>

    <! Spring is responsible for creating the action object.
    <constant name="struts.objectFactory" value="spring" />
    <! -- Enable development mode -->
    <constant name="struts.devMode" value="true" />
    <! Struts configuration file changed, whether to reload -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <! Set browser to cache static content -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <! Request parameter encoding -->
    <constant name="struts.i18n.encoding" value="utf-8" />
    <! The system reloads the resource file every time the HTTP request is made.
    <constant name="struts.i18n.reload" value="true" />
    <! -- Maximum file upload value -->
    <constant name="struts.multipart.maxSize" value="104857600" />
    <! Struts2 support dynamic method calls
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <! -- Action name with slash -->
    <constant name="struts.enable.SlashesInActionNames" value="false" />
    <! Allow expression syntax in tags -->
    <constant name="struts.tag.altSyntax" value="true" />
    <! -- For WebLogic,Orion,OC4J this property should be set to true -->
    <constant name="struts.dispatcher.parametersWorkaround" value="false" />
</struts>Copy the code

Hibernate reverse engineering generates User and FriendsJavaEntity class.

What if I can’t reverse engineer with Hibernate in MyEclipse? No problem! Please click here! Click this to tell you!!

Now that we’re done, we can start typing code to implement our requirements.


Ii. Realization of functions of each module:

1. User login

2. Successful login After successful login on the main page, the login information will be saved into the session for convenient display and search in other modules.

3. Contact management module

Because the ID of the user table is the foreign key of the Friends table, only the contacts of login users are displayed and queried. So storing the user in session above works.

1) Add contacts

One problem to note here is that when we add a contact, there is a contact record, including the userId, so we need to find the User object, set it to the contact object, and then save the contact.

    public String save() {
        // Select * from userId; Then add it to the contact object
        User user = userService.findUserById(userId);
        friends.setUser(user);
        // Call Service to save the contact
        friendService.save(friends);
        return "frilistAction";
    }Copy the code

2) View contact details

Here, the modal box of BootStrap is used again. For specific operations, you can refer to the detailed introduction in the previous small Demo. Struts2 simple library management system

3) Modify contact information

4) Fuzzy query by name and mobile phone number. Fuzzy query here supports only mobile phone number, only name, and both.

    /** * Fuzzy query */ based on name and phone number
    @Override
    public List<Friends> getAll(String friendName, String friendPhone) {
        HttpServletRequest request = ServletActionContext.getRequest();
        User user = (User)request.getSession().getAttribute("userInfo");
        int uid = user.getUserId();
        return this.getCurrentSession()
                .createQuery("from Friends where friendName like ? and friendPhone like ? and userId=?")
                .setParameter(0."%" + friendName + "%")
                .setParameter(1."%" + friendPhone + "%")
                .setInteger(2, uid)
                .list();
    }Copy the code

Enter the query information:

Query result:

The subsequent functional modules will continue to be improved, and the updated codes will be sorted and uploaded to Github.

Based on SSH personal information management system project source code