在Eclipse下基于Maven整合Struts2,Spring和Mybatis3框架。
新建Maven project,type选择webapp
这里我的jsp报错,解决办法:
右击项目,找到buildpath,点击Configure buildpath,如下图
点击next,出现下图后,选择你的web服务器
修改pom.xml文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>comgroupId>
<artifactId>javawebartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>javaweb Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<struts.version>2.3.28struts.version>
<spring.version>3.0.5.RELEASEspring.version>
<mybatis.version>3.2.6mybatis.version>
<log4j.version>1.2.17log4j.version>
properties>
<dependencies>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-coreartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-spring-pluginartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.30version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>javawebfinalName>
build>
project>
在resources目录下添加applicationContext.xml:
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="action">context:component-scan>
<context:component-scan base-package="service.impl">context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource_dev" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource_dev" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource_dev" />
bean>
beans>
在resources目录下添加配置文件jdbc.properties(配置自己的数据库信息,用户名,密码):
# JDBC Configuration
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/web
username=root
password=password
# DBCP Pool settings
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
在resources目录下添加struts配置文件struts.xml:
<struts>
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.multipart.maxSize" value="99000000" />
<constant name="struts.multipart.saveDir" value="/tmp"/>
<constant name="struts.configuration.xmlreload" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ui.theme" value="xhtml" />
<include file="User.xml">include>
struts>
sources目录下添加mybatis配置文件mybatis-config.xml:
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
settings>
<typeAliases>
typeAliases>
configuration>
在web.xml中添加如下配置:
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
在工程中添加如下类:
UserAction .java代码如下:
package action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import beans.User;
import service.IUserService;
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Resource
private IUserService userService;
private User user;
private List userlist;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List getUserlist() {
return userlist;
}
public void setUserlist(List userlist) {
this.userlist = userlist;
}
public String execute() throws Exception {
System.out.println("execute");
return SUCCESS;
}
public String addUser() {
userService.addUser(user);
return SUCCESS;
}
public String deleteUser() {
userService.deleteUser(user.getId());
return SUCCESS;
}
public String queryAllUser() {
userlist = userService.queryAllUser();
return "list";
}
public void validate() {
System.out.println("validate()会对action中的所有方法进行校验");
// if(this.user.getName() == null || this.user.getName().trim().equals("")) {
// this.addFieldError("name", "用户名不能为空!");
// }
}
//直接返回一个字符串
public String queryUserNameByID() throws IOException{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
//response.sendError(401,"timeout");
PrintWriter out = response.getWriter();
out.println("luangeng123");//返回的字符串数据
out.flush();
out.close();
return null;
}
}
User .java
package beans;
import java.sql.Date;
public class User {
private Integer id;
private String name;
private String pwd;
private String sex;
private Integer age;
private String email;
private String phone;
private Date register_time;
private Date last_update_time;
private String remark;
private Integer active;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getRegister_time() {
return register_time;
}
public void setRegister_time(Date register_time) {
this.register_time = register_time;
}
public Date getLast_update_time() {
return last_update_time;
}
public void setLast_update_time(Date last_update_time) {
this.last_update_time = last_update_time;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public User(Integer id,String name, String pwd, String sex,Integer age,String email, String phone,Date register_time,Date last_update_time,String remark,Integer active){
this.id = id;
this.name = name;
this.pwd = pwd;
this.sex = sex;
this.age = age;
this.email = email;
this.phone = phone;
this.register_time = register_time;
this.last_update_time = last_update_time;
this.remark = remark;
this.active = active;
}
public User(){ }
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", sex=" + sex + ", age=" + age + ", email="
+ email + ", phone=" + phone + ", register_time=" + register_time + ", last_update_time="
+ last_update_time + ", remark=" + remark + ", active=" + active + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
IUserDao
package dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import beans.User;
public interface IUserDao {
public void addUser(User user);
@Delete("delete from f_user_t where id=#{id}")
public void delUser(Integer userId);
@Select("select * from f_user_t where id=#{id")
public User queryUserById(Integer userId);
@Select("select * from f_user_t")
public List queryAll();
}
mapper中的User.xml
<mapper namespace="dao.IUserDao">
<resultMap type="beans.User" id="userResult">
<result property="id" column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<result property="username" column="username" />
<result property="password" column="password" />
resultMap>
<insert id="insertUser" parameterType="beans.User">
insert into f_user_t
(name,pwd,sex,age,email,phone,register_time,last_update_time,remark,active)
values
(#{name},#{pwd},#{sex},#{age},#{email},#{phone},now(),now(),#{remark},#{active})
insert>
mapper>
IUserService .java
package service;
import java.util.List;
import beans.User;
public interface IUserService {
public abstract void addUser(User user);
public abstract void deleteUser(Integer userId);
public abstract User queryUserById(Integer userId);
public abstract List queryAllUser();
}
UserService.java
package service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dao.IUserDao;
import beans.User;
import service.IUserService;
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private IUserDao userDao;
public void addUser(User user) {
userDao.addUser(user);
}
public void deleteUser(Integer userId) {
userDao.delUser(userId);
}
public User queryUserById(Integer userId) {
return userDao.queryUserById(userId);
}
public List queryAllUser() {
return userDao.queryAll();
}
}
struts的User.xml
<struts>
<package name="user" namespace="/user" extends="struts-default">
<action name="*" class="userAction" method="{1}">
<result name="success" type="redirectAction">queryAllUserresult>
<result name="error">/error.jspresult>
<result name="list">/list.jspresult>
<result name="input">/error.jspresult>
action>
package>
struts>
list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>用户列表title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
head>
<body>
<center>
<h2>用户列表h2>
<h3><s:a action="toadd" namespace="/user">添加新用户s:a> h3>
<table width="90%" border="1">
<tr>
<th>用户idth>
<th>用户名称th>
<th>用户密码th>
<th>ageth>
<th>emailth>
<th>sexth>
<th>phoneth>
<th>remarkth>
<th>操作th>
tr>
<s:iterator value="userlist">
<tr>
<td><s:property value="id"/> td>
<td><s:property value="name"/> td>
<td><s:property value="pwd"/> td>
<td><s:property value="age"/> td>
<td><s:property value="email"/> td>
<td><s:property value="sex"/> td>
<td><s:property value="phone"/> td>
<td><s:property value="remark"/> td>
<td>
<s:a action="toupdate" namespace="/user">
<s:param name="user.id" value="id"/>修改
s:a>
<s:a action="delete" namespace="/user">
<s:param name="user.id" value="id"/>删除
s:a>
td>
tr>
s:iterator>
table>
center>
body>
html>
启动mysql,创建数据库web,创建表f_user_t, 插入数据:
启动Tomcat,访问 http://localhost:8080/javaweb/user/queryAllUser
轉自:http://www.cnblogs.com/luangeng/p/5800782.html