IDEA與Maven搭建SSH框架流程和國際化i18n
阿新 • • 發佈:2019-01-03
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> <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的變化