• struts+spring+mybatis框架整合


    一转眼,毕业已经四个月了,回忆大学的点点滴滴,不由的想起了之前毕设做的东西,当时的项目是采用struts2+spring+mybatis框架开发的一个管理系统,整个项目的框架是由一个学长帮我们搭建好的,当时对于我这个刚接触java的童鞋,那样的东西感觉还是很新鲜的。利用空余时间,自己也使用struts2+spring+mybatis框架写个实现增删改查功能的例子。

    不扯那么多了,进入正题。

    首先,导入相关的jar包(后面附源码)

    其次,创建并编写配置文件

    ApplicationContext.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: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-3.0.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
    	<aop:aspectj-autoproxy proxy-target-class="true" />
    
    	<!-- dataSource -->
    
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    		destroy-method="close">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    		<property name="url"
    			value="jdbc:mysql://localhost:3306/testSSM?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>
    		<property name="username" value="root"></property>
    		<property name="password" value="root"></property>
    		<property name="maxActive" value="100"></property>
    		<property name="maxIdle" value="30"></property>
    		<property name="maxWait" value="500"></property>
    		<property name="defaultAutoCommit" value="true"></property>
    	</bean>
    
    	<bean id="transactionManager"
    		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    
    	<!-- dao -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="typeAliasesPackage" value="com.wporoad.app.entity" />
    	</bean>
    
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<property name="basePackage" value="com.wporoad.app.dao" />
    	</bean>
    	<bean id="userService" class="com.wporoad.app.serviceImpl.UserServiceImpl">
    		<property name="userMapper" ref="userMapper" />
    	</bean>
    	<bean id="userAction" class="com.wporoad.app.web.UserAction">
    		<property name="userService" ref="userService" />
    	</bean>
    
    </beans>
    

      数据源和映射文件都在ApplicationContext.xml进行配置

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
     
      <context-param>
      	<param-name>webAppRootKey</param-name>
      	<param-value>ssi.root</param-value>
      </context-param> 
     
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
          <param-name>actionPackages</param-name>
          <param-value>com.cstor.network.action</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:resource/applicationContext*.xml</param-value>
      </context-param>
      <listener>
        <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
      </listener>
      <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/resource/log4j.properties</param-value>
      </context-param>
      <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
      </listener>
    </web-app>
    

     struts.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
    	<constant name="struts.custom.i18n.resources" value="message"></constant>
    	
    	<package name="struts2" extends="struts-default">
    
    		<action name="user_add" class="com.wporoad.app.web.UserAction" method="addUser" >
    			<result name="success">/WEB-INF/page/success.jsp</result>
    			<result name="error">/error.jsp</result>
    		</action>
    		
    		<action name="user_list" class="com.wporoad.app.web.UserAction" method="queryUsers" >
    			<result name="success">/WEB-INF/page/success.jsp</result>
    			<result name="error">/error.jsp</result>
    			<result name="list">/WEB-INF/page/UserList.jsp</result>
    		</action>
    		
    		
    		<action name="user_del" class="com.wporoad.app.web.UserAction" method="delUser" >
    			<result name="list">/WEB-INF/page/UserList.jsp</result>
    			<result name="error">/WEB-INF/page/error.jsp</result>
    		</action>
    		
    		<action name="user_detail" class="com.wporoad.app.web.UserAction" method="detailUser" >
    			<result name="success">/WEB-INF/page/success.jsp</result>
    			<result name="error">/WEB-INF/page/error.jsp</result>
    			<result name="detail">/WEB-INF/page/detail.jsp</result>
    		</action>
    		
    		<action name="user_update" class="com.wporoad.app.web.UserAction" method="update" >
    			<result name="success">/WEB-INF/page/success.jsp</result>
    			<result name="error">/WEB-INF/page/error.jsp</result>
    			<result name="update">/WEB-INF/page/update.jsp</result>
    		</action>
    		
    		<action name="update" class="com.wporoad.app.web.UserAction" method="updateUser" >
    			<result name="success">/WEB-INF/page/success.jsp</result>
    			<result name="error">/WEB-INF/page/error.jsp</result>
    		</action>
    		
    	</package>
    </struts>

     接下来就是编写后台程序了

    1.辅助类

    package com.wporoad.app.entity;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	private String id;
    	private String userName;
    	private String password;
    	private String email;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	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;
    	}
    
    	public String getEmail() {
    		return email;
    	}
    
    	public void setEmail(String email) {
    		this.email = email;
    	}
    
    }
    

      2. action类UserAction

    package com.wporoad.app.web;
    
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.log4j.Logger;
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    import com.wporoad.app.entity.User;
    import com.wporoad.app.service.UserService;
    
    public class UserAction extends ActionSupport {
    	private static final long serialVersionUID = 1L;
    	private static Logger logger = Logger.getLogger(UserAction.class);
    
    	public UserService userService;
    
    	public UserService getUserService() {
    		return userService;
    	}
    
    	public void setUserService(UserService userService) {
    		this.userService = userService;
    	}
    
    	private String id;
    
    	public String getId() {
    		return id;
    	}
    
    	private String userName;
    	private String password;
    	private String email;
    
    	/**
    	 * 添加用户信息
    	 * 
    	 * @return
    	 */
    	public String addUser() {
    		User user = new User();
    		try {
    			String iid = UUID.randomUUID().toString();
    			user.setId(iid);
    			user.setUsername(userName);
    			user.setPassword(password);
    			user.setEmail(email);
    			userService.addUser(user);
    		} catch (Exception e) {
    			logger.error("exception in add user", e);
    			return ERROR;
    		}
    		return SUCCESS;
    	}
    
    	/**
    	 * 从数据库中获得所有的用户信息
    	 * 
    	 * @return
    	 */
    	public String queryUsers() {
    		try {
    			List<User> userList = userService.queryUsers();
    			HttpServletRequest request = ServletActionContext.getRequest();
    			request.setAttribute("list", userList);
    			return "list";
    		} catch (Exception e) {
    			logger.error("Exception in queryUsers", e);
    			return ERROR;
    		}
    	}
    
    	/**
    	 * 删除用户信息
    	 * 
    	 * @return
    	 */
    	public String delUser() {
    		try {
    			userService.delUser(id);
    			List<User> userList = userService.queryUsers();
    			HttpServletRequest request = ServletActionContext.getRequest();
    			request.setAttribute("list", userList);
    		} catch (Exception e) {
    			logger.error("Exception in delUser", e);
    			return ERROR;
    		}
    		return "list";
    	}
    
    	public String detailUser() {
    		try {
    			List<User> userList = userService.detailUser(id);
    			User user = userList.get(0);
    			HttpServletRequest request = ServletActionContext.getRequest();
    			request.setAttribute("user", user);
    			return "detail";
    		} catch (Exception e) {
    			logger.error(e);
    			return ERROR;
    		}
    	}
    
    	public String update() {
    		List<User> userList = userService.detailUser(id);
    		User user = userList.get(0);
    		HttpServletRequest request = ServletActionContext.getRequest();
    		request.setAttribute("user", user);
    		return "update";
    	}
    
    	public String updateUser() {
    		try {
    			User user = new User();
    			user.setId(id);
    			user.setUsername(userName);
    			user.setPassword(password);
    			user.setEmail(email);
    			userService.updateUser(user);
    			return SUCCESS;
    		} catch (Exception e) {
    			logger.error(e);
    			return ERROR;
    		}
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public void setEmail(String email) {
    		this.email = email;
    	}
    
    }
    

      3.service层,UserService接口和UserServiceImpl

     UserService.java

    package com.wporoad.app.service;
    
    import java.util.List;
    
    import com.wporoad.app.entity.User;
    
    public interface UserService {
    	/**
    	 * 添加用户
    	 * 
    	 * @param user
    	 */
    	public void addUser(User user);
    
    	/**
    	 * 列出所有的用户
    	 * 
    	 * @return
    	 */
    	public List<User> queryUsers();
    
    	/**
    	 * 删除用户
    	 * 
    	 * @param id
    	 */
    	public void delUser(String id);
    
    	/**
    	 * 详细信息
    	 * 
    	 * @param id
    	 */
    	public List<User> detailUser(String id);
    
    	/**
    	 * 修改信息
    	 * 
    	 * @param User
    	 */
    	public void updateUser(User User);
    }
    

      UserServiceImpl.java

    package com.wporoad.app.serviceImpl;
    
    import java.util.List;
    
    import com.wporoad.app.dao.UserMapper;
    import com.wporoad.app.entity.User;
    import com.wporoad.app.service.UserService;
    
    public class UserServiceImpl implements UserService {
    	private UserMapper userMapper;
    
    	public UserMapper getUserMapper() {
    		return userMapper;
    	}
    
    	public void setUserMapper(UserMapper userMapper) {
    		this.userMapper = userMapper;
    	}
    
    	/**
    	 * 添加用户
    	 */
    	public void addUser(User user) {
    		userMapper.addUser(user);
    	}
    
    	/**
    	 * 列出所有用户
    	 */
    	public List<User> queryUsers() {
    		List<User> userList = userMapper.queryUsers();
    		return userList;
    	}
    
    	/**
    	 * 删除用户
    	 */
    	public void delUser(String id) {
    		userMapper.delUser(id);
    	}
    
    	public List<User> detailUser(String id) {
    		return userMapper.detailUser(id);
    	}
    
    	@Override
    	public void updateUser(User User) {
    		userMapper.updateUser(User);
    	}
    
    }
    

      4. Dao层UserMapper.java和映射文件UserMaper.xml

    UserMapper.java

    package com.wporoad.app.dao;
    
    import java.util.List;
    
    import com.wporoad.app.entity.User;
    
    public interface UserMapper {
    	/**
    	 * 添加用户
    	 * @param user
    	 */
    	public void addUser(User user);
    	
    	/**
    	 * 列出所有用户
    	 * @return
    	 */
    	public List<User> queryUsers();
    	
    	/**
    	 * 删除用户
    	 * @param id
    	 */
    	public void delUser(String id);
    	
    	/**
    	 * 详细信息
    	 * @param id
    	 */
    	public List<User> detailUser(String id);
    	
    	/**
    	 * 修改信息
    	 * @param User
    	 */
    	public void updateUser(User User);
    }
    

      UserMapper.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="com.wporoad.app.dao.UserMapper">
    
    	<resultMap id="UserMap" type="com.wporoad.app.entity.User">
    		<result property="id" column="ID" />
    		<result property="userName" column="USERNAME" />
    		<result property="password" column="PASSWORD" />
    		<result property="email" column="EMAIL" />
    	</resultMap>
    
    	<insert id="addUser" parameterType="User">
    		INSERT INTO USER(
    		ID,
    		USERNAME,
    		PASSWORD,
    		EMAIL
    		)
    		VALUES (
    		#{id},
    		#{userName},
    		#{password},
    		#{email}
    		)
    	</insert>
    	
    	<select id="queryUsers" resultMap="UserMap" >
    		SELECT * FROM USER
    	</select>
    	
    	<!-- 删除信息 -->
    	<delete id="delUser" parameterType="string">
    		DELETE FROM USER WHERE ID = #{id}
    	</delete>
    	
    	<select id="detailUser" parameterType="String" resultMap="UserMap">
    		SELECT USERNAME,PASSWORD,EMAIL, ID
    		FROM USER WHERE ID = #{value}
    	</select>
    	
    	
    	<!-- 更新信息 -->
    	<update id="updateUser" parameterType="User">
    		UPDATE USER
    		<set>
    			<if test="userName != null ">USERNAME = #{userName},</if>
    			<if test="password != null ">PASSWORD = #{password},</if>
    			<if test="email != null ">EMAIL = #{email}</if>
    		</set>
    		WHERE ID = #{id}
    	</update>
    	
    	
    </mapper>
    

      下面就是几个页面了

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    添加记录
    <a href="user_list">查看信息</a>
    <form action="user_add" method="post">
    姓名<input type="text" id="xx" name="userName"><br>
    密码<input type="text" id="xx" name="password"><br>
    邮箱<input type="text" id="xx" name="email"><br>
    <input type="submit" value="添加"><input type="reset" value="重置">
    </form>
    </body>
    </html>
    

      detail.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    姓名:<span>${user.userName}</span><br>
    密码:<span>${user.password}</span><br>
    邮箱:<span>${user.email}</span><br>
    <a href="index.jsp">返回主页</a>
    </body>
    </html>
    

      error.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    操作失败!!!<br>
    <a href="index.jsp">主页</a>
    </body>
    </html>
    

      success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    添加数据成功!
    <br>
    <a href="user_list">查看数据库信息</a>
    <a href="index.jsp">返回</a>
    </body>
    </html>
    

      update.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    记录修改
    <a href="index.jsp">返回</a>
    <form action="update" method="post">
    <input type="hidden" id="xx" name="id" value="${user.id}"><br>
    姓名<input type="text" id="xx" name="userName" value="${user.userName}"><br>
    密码<input type="text" id="xx" name="password" value="${user.password}"><br>
    邮箱<input type="text" id="xx" name="email" value="${user.email}"><br>
    <input type="submit" value="添加"><input type="reset" value="重置">
    </form>
    </body>
    </html>
    

      UserList.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <table border="1">
    	<c:forEach items="${list}" var="s">
    		<tr>
    			<td><c:out value="${s.userName}"></c:out></td>
    			<td><c:out value="${s.password}"></c:out></td>
    			<td><c:out value="${s.email}"></c:out></td>
    			<td><a href="user_detail?id=${s.id}">记录详情</a></td>
    			<td><a href="user_update?id=${s.id}">修改信息</a></td>
    			<td><a href="user_del?id=${s.id}">删除记录</a></td>
    		</tr><br>
    	</c:forEach>
    </table>
    </body>
    </html>
    

      ok,整个项目就是这样的。

    源码分享(免积分下载,由于是在写博客之前上传的,所以增删改查功能还不完善哟!!!重新上传后,再更新地址~~~)

  • 相关阅读:
    Python-os
    Python-字典Dict
    Linux下使用Apache搭建Web网站服务器
    Linux中FTP安装与配置
    第16章 广域网
    第15章 IPv6
    第14章 思科无线技术
    第13章 网络地址转换NAT
    第12章 安全
    第11章 虚拟局域网
  • 原文地址:https://www.cnblogs.com/lgfeng/p/java.html
Copyright © 2020-2023  润新知