这几天搭了个spring+struts2+mybatis的架子,练练手,顺便熟悉熟悉struts2.
环境:myEclipse10+tomcat7+jdk1.6(1.8的jre报错,所以换成了1.6).
框架:spring+struts2+mybatis。
前言:
1.spring+mybatis的配置同 spring MVC ;
2.唯一要注意的是strtus2和spring的整合(spring中的bean注入到action中,网上各种讲解,但都相对于各自的项目,所以,新入手struts2的时候还是要自己耐心体验);
3.由于struts2本身存在bug,且相比较spring MVC没有什么优势,所以,年轻的项目基本不会选择strtus2,我使用他纯属偶然,若看客是以较功利的目的学习框架的话,不建议学习看本章博客。
以下,为框架:
一. 首先是jar包,这个比较烦人(相对于个人而言,企业都有整套的jar包),
以下为本人使用的jar包(由于公司不使用struts2,所以虽然我借鉴了前人的博客,但还是被jar包冲突狠狠的折磨了一番):
其中,commons-fileupload,commons.io,commons.lang3,freemarker,javassist,ognl,spring-strtus,struts2-core,struts2-spring-plugin,xwork-core为与struts2相关的jar包,注意,aopalliance,aspectjrt要增加。
至于每个jar包的作用请自行百度(请原谅我和部分jar包不熟的不负责任的态度)。
二. 层级
传统的企业级的项目,由于考虑到扩展性,会将service分拆为service接口,和serviceImple实现类,
我属于玩票性质,所以直接忽略了service层(图片里的service并没有使用,可忽略),直接将在action中使用mapper(框架是死的,活学活用最重要(请原谅我给自己的懒惰找借口))。
新人这里要注意src/Resources这个文件夹,这是资源文件夹,可以随意设置,
右击项目,选择Build Path 选择Configure Build Path自行设置(不懂请百度)。
接着是web.xml,application-common.xml,mybatis.xml,struts.xml,log4j.xml,如下:
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <!-- 对Spring容器进行实例化 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-common.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
application-common.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 数据库连接 属性 博客:http://blog.itpub.net/7971010/viewspace-1114524 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="username" value="root"/> <!-- <property name="password" value="${jdbc.mysql.password}"/> --> <property name="connectionProperties" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db_database24"/> <property name="initialSize" value="1"/> <property name="minIdle" value="1"/> <property name="maxActive" value="5"/> <property name="maxWait" value="60000"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:/mybatis-config.xml"/> <property name="mapperLocations" value="classpath*:main/java/com/zq/mapper/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="main.java.com.zq.dao"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- proxy-target-class 意思 博客:http://blog.csdn.net/z69183787/article/details/17161297 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="100" /> <context:component-scan base-package="main.java.com.zq"/> <context:annotation-config /> <!-- 面向切面编程使用 :博客:http://kld208.iteye.com/blog/1632935 --> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="dialect" value=""/>
</properties>
<typeAliases>
<typeAlias alias="user" type="main.java.com.zq.model.User"/>
</typeAliases>
</configuration>
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> <!-- 指定以name的方式组合action和service的关系 <constant name="struts.objectFactory.spring.autoWire" value="name"></constant> --> <package name="shop.admin" namespace="/admin" extends="struts-default"> <action name="loginAction" class="loginAction" method="Login"> <result name="SUCCESS">/WEB-INF/login.jsp</result> </action> </package> </struts>
log4j.xml:
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=debug, stdout log4j.logger.java.sql.PreparedStatement=debug
文件夹struts请忽略,这里是为了分写struts接口时使用的,但我只写了一个接口,所以,就只能呵呵了····
以下问代码部分:
LoginAction.java
package main.java.com.zq.action; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import main.java.com.zq.dao.LoginMapper; import main.java.com.zq.model.User; import main.java.com.zq.service.LoginService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @Scope("prototype") @Controller("loginAction") public class LoginAction extends ActionSupport implements ModelDriven<User> { Logger logger=Logger.getLogger(LoginAction.class); @Autowired private LoginMapper loginMapper; private static final long serialVersionUID = 1L; @Override public User getModel() { // TODO Auto-generated method stub return user; } private User user=new User(); public User getUser() { return user; } public void setUser(User user) { this.user=user; } public void setLoginMapper(LoginMapper loginMapper) { this.loginMapper = loginMapper; } public String Login(){ Map<Object, Object> map=new HashMap<Object, Object>(); map.put("username", user.getUsername()); map.put("password", user.getPassword()); System.out.println(map.toString()); logger.debug(map.toString()); Map<?, ?> resultMap=loginMapper.login(map); if(resultMap.get("password").equals(user.getPassword())){ return "SUCCESS"; }else { return SUCCESS; } } }
LoginMapper.java:
package main.java.com.zq.dao; import java.util.Map; import org.springframework.stereotype.Repository; public interface LoginMapper { Map login(Map map); }
LoginMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="main.java.com.zq.dao.LoginMapper">
<select id="login" parameterType="map" resultType="map">
SELECT * from tb_user where username=#{username} limit 1
</select>
</mapper>
User.java:
package main.java.com.zq.model; import java.io.Serializable; /** * * @author Sean * */ public class User implements Serializable{ private static final long serialVersionUID = 1L; private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String password; }
Test.java(这是我测试用的,建议坚持使用测试类,无论你偷懒直接建Test类还是使用junit,Test能在你不知道哪里出错的时候一步一步调试,让你有迹可循):
package main.java.com.zq.utils; import java.util.HashMap; import java.util.Map; import main.java.com.zq.action.LoginAction; import main.java.com.zq.dao.LoginMapper; import main.java.com.zq.model.User; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String [] args){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-common.xml"); System.out.println(context.getBean("dataSource").toString()); LoginMapper loginMapper= (LoginMapper) context.getBean("loginMapper"); Map map=new HashMap(); map.put("username", "admin"); System.out.println(loginMapper.login(map)); LoginAction loginAction=(LoginAction) context.getBean("loginAction"); User user=new User(); user.setPassword("adine"); user.setUsername("admin"); loginAction.setUser(user); System.out.println(loginAction.Login().toString()); } }
jsp部分只有一个表单,其他什么都没有,不喜欢jsp,html万岁!
github:https://github.com/zhouqia/spring-mybatis-struts2.git
可以直接克隆,里面的代码不可以直接用,但都有,那些想直接拉下来跑的,我就呵呵了,多动手少年。
以上。
为全部代码。
如果可以轻松搭建,建议可以看绿考虑 strtus2的过滤器和mybatis的插件的原理,你会发现都是使用动态代理实现的,
而且,你可以考虑考虑,他们使用的动态代理到底是环形的,还是直线形的。
最讨厌又臭又长的文章,以后写博客,要尽量精简。