IDEA与Maven搭建SSH框架流程和国际化i18n

1、正常流程新建maven项目,部署tomcat

2、配置pom.xml

<properties>                
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.0-b01</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.7</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.7</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.3.24.1</version>
      <exclusions>
        <exclusion>
          <groupId>javassist</groupId>
          <artifactId>javassist</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>2.3.24.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-convention-plugin</artifactId>
      <version>2.3.24.1</version>
    </dependency>

    <dependency>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.16</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.0.6.Final</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>

</dependencies>

若后面接口实现类的重写方法报错,加入:

<build>
    <finalName>ssh</finalName>
    <plugins>
      <!-- 编码和编译和JDK版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>utf8</encoding>
        </configuration>
      </plugin>
    </plugins>
</build>

3、配置web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- 配置Spring框架核心的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>

  <!-- Struts2核心过滤器配置 -->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

4、jdbc.properties

driverClasss=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/dbcp?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
username=root
password=***

5、log4j.properties,日志输出到文件

#Log4j建议只使用四个级别,优先级从高到低分别是 ERROR、WARN、INFO、DEBUG
log4j.rootLogger=DEBUG,Console,file

#控制台日志
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n

#普通文件日志
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D\:/WorkSpace_Python/ssh/logs/ssh.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.Threshold=ALL
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n

#sql OFF
log4j.logger.org.springframework=WARN
log4j.logger.com.alibaba.druid.pool=WARN

6、struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="ssh" extends="struts-default" namespace="/">
        <action name="user_*" class="com.example.controller.UserAction" method="{1}">
            <result name="success">/WEB-INF/page/index.jsp</result>
            <result name="detail">/WEB-INF/page/detail.jsp</result>
        </action>
        <action name="*" class="com.example.controller.ChangeLanguageAction" method="{1}">
            <result name="success">/WEB-INF/page/index.jsp</result>
        </action>
    </package>
    <constant name="struts.custom.i18n.resources" value="message.message" />
</struts>

7、spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描外部配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <context:component-scan base-package="com.example" />

    <!--配置Druid连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <!--配置连接池属性-->
        <property name="driverClassName" value="${driverClasss}"/>
        <property name="url" value="${jdbcUrl}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="3" />
        <property name="minIdle" value="3" />
        <property name="maxActive" value="20" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 1" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>
    <!--配置Hibernate整合Spring-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--注入连接池-->
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!--配置Hibernate的映射文件-->
        <property name="mappingResources">
            <list>
                <value>hbm/User.hbm.xml</value>
            </list>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.example.bean</value>
            </list>
        </property>
    </bean>

    <!-- sessionFactory注入dao的方法:在userDao代码中通过set方法注入sessionFactory -->

    <!--配置事务管理-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

8、国际化资源文件,在struts.xml中配置使其生效

  • message/message_en_US.properties
key=developer
  • message/message_zh_CN.properties
key=\u5f00\u53d1\u8005

9、hbm/User.hbm.xml,在数据库建立对应表

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.example.bean.User" table="user">
        <id name="userId" column="userId">
            <generator class="native" />
        </id>
        <property name="age" column="age" length="20"/>
        <property name="name" column="name"/>
    </class>
</hibernate-mapping>

10、视图jsp

  • webapp/index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<h2>Hello World!</h2>
<s:text name="key" />
<a href="changeLanguage?lang=zh">中文</a>&nbsp;&nbsp;&nbsp;<a href="changeLanguage?lang=en">英文</a><br>
</body>
</html>
  • /WEB-INF/page/index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<h2>Hello World!</h2>
<s:text name="key" />
<a href="user_showUser?id=1">showUser</a>
</body>
</html>
  • /WEB-INF/page/detail.jsp,展示数据库查出的数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<h2>Hello World!</h2>
name:${user.name}
age:${user.age}
<s:text name="key" />
</body>
</html>

11、New->Class,给出部分代码
com.example.bean.User
com.example.dao.IUserDao
com.example.dao.impl.UserDaoImpl
com.example.service.IUserService
com.example.service.impl.UserServiceImpl
com.example.controller.UserAction

package com.example.dao.impl;

import com.example.bean.User;
import com.example.dao.IUserDao;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional
@Repository("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements IUserDao{

    @Resource
    public void setMySessionFactory(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public void insertUser(User user) {
        this.getHibernateTemplate().save(user);
    }

    @Override
    public User getUserById(Integer userId) {
        return this.getHibernateTemplate().get(User.class, userId);
    }
}
package com.example.controller;

import com.example.service.IUserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.example.bean.User;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class UserAction  extends ActionSupport {

    private Logger logger = Logger.getLogger(UserAction.class);

    @Resource(name="userService")
    private IUserService userService;

    public String showUser(){
        HttpServletRequest request = ServletActionContext.getRequest();
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        ActionContext.getContext().put("user", user);
        logger.info("controller.showUser:" + user);

        return "detail";
    }

}

com.example.controller.ChangeLanguageAction

package com.example.controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * Author:
 * DateTime:2017-12-22 14:39
 */
public class ChangeLanguageAction  extends ActionSupport {

    public String changeLanguage(){
        HttpServletRequest request = ServletActionContext.getRequest();
        String lang = request.getParameter("lang");
        //读取操作系统当前默认的语言环境
        Locale locale = Locale.getDefault();
        if("zh".equals(lang)){
            locale = new Locale("zh","CN");
        }else if("en".equals(lang)){
            locale = new Locale("en","US");
        }

        // locale应用到当前请求的上下文
        ActionContext.getContext().setLocale(locale);
        //将Locale设置到session中
        ServletActionContext.getRequest().getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);

        return SUCCESS;
    }
}

12、结果页面效果,注意url的变化

这里写图片描述

这里写图片描述

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值