一、用myEclipse初始化Web项目
新建一个web project:
二、创建包
controller //控制类
service //服务接口
service.impl
//服务实现类
dao //data access object(接口)
dao.impl //实现类
domain //实体类
mappers //mybatis的配置映射文件
util //工具类
三、是maven方式引入类库
3.1启动tomcat服务
3.2给web项目添加maven支持(引入maven私服库)
将web项目转化为maven项目:
3.3引入依赖
spring
mybatis
spring mvc
c3p0类库
MySQL
.......
3.4主要是编写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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.liuhai</groupId>
- <artifactId>eshopSSM</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>war</packaging>
- <properties>
- <log4j.version>1.2.17</log4j.version>
- <slf4j.version>1.7.7</slf4j.version>
- </properties>
- <build>
- <sourceDirectory>src</sourceDirectory>
- <resources>
- <resource>
- <directory>src</directory>
- <excludes>
- <exclude>**/*.java</exclude>
- </excludes>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.1</version>
- <configuration>
- <source>1.7</source>
- <target>1.7</target>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-war-plugin</artifactId>
- <version>2.3</version>
- <configuration>
- <warSourceDirectory>WebRoot</warSourceDirectory>
- <failOnMissingWebXml>false</failOnMissingWebXml>
- <version>3.0</version>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <!-- webmvc -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>4.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>4.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>4.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>4.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>4.0.2.RELEASE</version>
- </dependency>
- <!-- 导入Mysql数据库链接jar包 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.17</version>
- </dependency>
- <!--c3p0 用来在applicationContext.xml中配置数据库 -->
- <dependency>
- <groupId>com.mchange</groupId>
- <artifactId>c3p0</artifactId>
- <version>0.9.5.2</version>
- </dependency>
- <!-- JSTL标签类 -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <!-- mybatis核心包 -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.1.1</version>
- </dependency>
- <!-- mybatis/spring包 -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.2.0</version>
- </dependency>
- <!-- 映入JSON 对象转json转换器,主要用来restful用-->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.4</version>
- </dependency>
- <!-- log start -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>${log4j.version}</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j.version}</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>${slf4j.version}</version>
- </dependency>
- <!-- log end -->
- <!-- 上传组件包begin -->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <!-- 上传组件包end -->
- <!-- json解析包 -->
- <dependency>
- <groupId>net.sf.json-lib</groupId>
- <artifactId>json-lib</artifactId>
- <version>2.4</version>
- </dependency>
- </dependencies>
- </project>
四、创建dao和service的基础类库
UserDao.Java如下:
- package com.liuhai.eshop.dao;
- import java.util.List;
- import java.util.Map;
- import com.liuhai.eshop.domain.User;
- /**
- * 用户DAO接口
- * @author Administrator
- *
- */
- public interface UserDao {
- /**
- * 用户登录
- * @param user
- * @return
- */
- public User login(User user);
- /**
- * 查询所有用户
- * @return
- */
- public List<User> getAll();
- /**
- * 根据条件查询用户
- * @param user
- * @return
- */
- public User getUser(User user);
- /**
- * 删除用户
- * @param user
- * @return
- */
- public int delete(int id);
- /**
- * 更新用户
- * @param user
- * @return
- */
- public int update(User user);
- /**
- * 添加用户
- * @param user
- * @return
- */
- public int add(User user);
- /**
- * 用户查询
- * @param map
- * @return
- */
- public List<User> find(Map<String,Object> map);
- /**
- * 获取总记录数
- * @param map
- * @return
- */
- public Long getTotal(Map<String,Object> map);
- /**
- * 根据id查询用户
- * @param id
- * @return
- */
- public User getUserById(int id);
- }
UserService.java 用户service层接口如下:
- package com.liuhai.eshop.service;
- import java.util.List;
- import java.util.Map;
- import com.liuhai.eshop.domain.User;
- public interface UserService {
- public List<User> getAll();
- public User getUser(User user);
- public int delete(int id);
- public int update(User user);
- public int add(User user);
- public List<User> find(Map<String,Object> map);
- public Long getTotal(Map<String,Object> map);
- public User getUserById(int id);
- }
UserServiceImpl.java 用户service实现层如下:
- package com.liuhai.eshop.service.impl;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- import com.liuhai.eshop.dao.UserDao;
- import com.liuhai.eshop.domain.User;
- import com.liuhai.eshop.service.UserService;
- @Service(value="userService")
- public class UserServiceImpl implements UserService {
- private UserDao userDao;
- @Resource
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- @Override
- public List<User> getAll() {
- return userDao.getAll();
- }
- @Override
- public User getUser(User user) {
- return userDao.getUser(user);
- }
- @Override
- public int delete(int id) {
- return userDao.delete(id);
- }
- @Override
- public int update(User user) {
- return userDao.update(user);
- }
- @Override
- public int add(User user) {
- return userDao.add(user);
- }
- @Override
- public List<User> find(Map<String, Object> map) {
- return userDao.find(map);
- }
- @Override
- public Long getTotal(Map<String, Object> map) {
- return userDao.getTotal(map);
- }
- public User getUserById(int id){
- return userDao.getUserById(id);
- }
- }
user实体类如下:
- package com.liuhai.eshop.domain;
- import java.io.Serializable;
- /**
- * 用户实体
- * @author Administrator
- *
- */
- public class User implements Serializable{
- private static final long serialVersionUID = 1L;
- private Integer id;
- private String userName;
- private String password;
- private Integer age;
- private String trueName;
- private String email;
- private String phone;
- private String roleName;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getTrueName() {
- return trueName;
- }
- public void setTrueName(String trueName) {
- this.trueName = trueName;
- }
- 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 String getRoleName() {
- return roleName;
- }
- <h1><a name="t8"></a> public void setRoleName(String roleName) {</h1> this.roleName = roleName;
- }
- }
五、配置spring配置文件、jdbc和日志属性文件、myBatis的mapper.xml文件
5.1 spring配置文件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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
- <!-- 属性配置文件 -->
- <context:property-placeholder location="classpath:jdbc.properties"/>
- <!-- 组件扫描,指定spring管理哪些bean -->
- <context:component-scan base-package="com.liuhai.eshop.dao.impl,com.liuhai.eshop.service.impl"></context:component-scan>
- <!-- 注解驱动 -->
- <tx:annotation-driven/>
- <!-- 创建数据源 -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- <property name="driverClass" value="${jdbc.driverclass}"></property>
- <property name="jdbcUrl" value="${jdbc.url}"></property>
- <property name="user" value="${jdbc.username}"></property>
- <property name="password" value="${jdbc.password}"></property>
- <property name="initialPoolSize" value="${c3p0.pool.size.init}"></property>
- <property name="minPoolSize" value="${c3p0.pool.size.min}"></property>
- <property name="maxPoolSize" value="${c3p0.pool.size.max}"></property>
- <property name="acquireIncrement" value="${c3p0.pool.size.increment}"></property>
- </bean>
- <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <!-- 自动扫描mapping.xml文件 -->
- <property name="mapperLocations" value="classpath:com/liuhai/eshop/mappers/*.xml"></property>
- </bean>
- <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.liuhai.eshop.dao"></property>
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
- </bean>
- <!-- 事务管理器,service层面上实现事务管理的 -->
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- </beans>
5.2 jdbc属性文件jdbc.properties如下:
- jdbc.driverclass=com.mysql.jdbc.Driver
- jdbc.url=jdbc\:mysql\://localhost\:3306/eshop
- jdbc.username=root
- jdbc.password=123456
- c3p0.pool.size.max=10
- c3p0.pool.size.min=2
- c3p0.pool.size.init=3
- c3p0.pool.size.increment=2
- hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
- hibernate.show_sql=true
- hibernate.hbm2ddl.auto=none
5.3 日志属性文件log4j.properties如下:
- log4j.rootLogger=INFO,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=[%c] - %m%n
- log4j.logger.java.sql.ResultSet=INFO
- log4j.logger.org.apache=INFO
- log4j.logger.java.sql.Connection=DEBUG
- log4j.logger.java.sql.Statement=DEBUG
- log4j.logger.java.sql.PreparedStatement=DEBUG
- #文件大小到达指定尺寸的时候产生一个新的文件
- log4j.appender.File = org.apache.log4j.RollingFileAppender
- #指定输出目录
- log4j.appender.File.File = logs/ssm.log
- #定义文件最大大小
- log4j.appender.File.MaxFileSize = 10MB
- # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
- log4j.appender.File.Threshold =INFO
- log4j.appender.File.layout = org.apache.log4j.PatternLayout
- log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
5.4 myBatis的mapper.xml文件(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.liuhai.eshop.dao.UserDao">
- <!-- 定义缓存 一般是一级缓存,如果用同一个sqlsession 那么相同查询直接会从缓存中查找 -->
- <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"></cache>
- <!-- 增加 -->
- <insert id="add" parameterType="com.liuhai.eshop.domain.User">
- insert into users values(null,#{userName},#{password},#{age},#{trueName},#{email},#{phone},#{roleName})
- </insert>
- <resultMap id="userResultMap" type="com.liuhai.eshop.domain.User" >
- <id property="id" column="id"/>
- <result property="userName" column="userName"/>
- <result property="password" column="password"/>
- <result property="age" column="age"/>
- <result property="trueName" column="trueName" />
- <result property="email" column="email" />
- <result property="phone" column="phone" />
- <result property="roleName" column="roleName" />
- </resultMap>
- <select id="getUserById" parameterType="Integer" resultMap="userResultMap">
- select * from users where id=#{id}
- </select>
- <select id="find" parameterType="com.liuhai.eshop.domain.User" resultMap="userResultMap">
- select * from users
- <where>
- <if test="userName!=null and userName!='' ">
- and userName like #{userName}
- </if>
- </where>
- <if test="start!=null and size!=null">
- limit #{start},#{size}
- </if>
- </select>
- <select id="getTotal" parameterType="Map" resultType="Long">
- select count(*) from users
- <where>
- <if test="userName!=null and userName!='' ">
- and userName like #{userName}
- </if>
- </where>
- </select>
- <!-- 用户删除 -->
- <delete id="delete" parameterType="Integer">
- delete from users where id = #{id}
- </delete>
- <!-- 用户修改 -->
- <update id="update" parameterType="com.liuhai.eshop.domain.User">
- update users
- <set>
- <if test="age != null and age != ''">age = #{age},</if>
- <if test="userName != null and userName != ''">userName = #{userName},</if>
- <if test="password != null and password != ''">password = #{password},</if>
- <if test="trueName != null and trueName != ''">trueName = #{trueName},</if>
- <if test="email != null and email != ''">email = #{email},</if>
- <if test="phone != null and phone != ''">phone = #{phone},</if>
- <if test="roleName != null and roleName != ''">roleName = #{roleName},</if>
- </set>
- where id = #{id}
- </update>
- </mapper>
六、创建测试类,测试数据源是否通了
以上spring框架及spring+mybatis配置基本完成,再就是创建测试类测试数据源是否通
首先创建一个mysql库的,再建立users表,创建测试类TestSpring.java如下:
- package com.liuhai.eshop;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.liuhai.eshop.domain.User;
- import com.liuhai.eshop.service.UserService;
- public class TestSpring {
- @Test
- public void TestUserService() throws Exception{
- @SuppressWarnings("resource")
- ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
- UserService us=(UserService) ac.getBean("userService");
- User user=new User();
- user.setAge(1);
- user.setUserName("zhangsan");
- user.setPassword("123456");
- user.setTrueName("张三");
- us.add(user);
- }
- }
最后查询users表中是否有新插入的数据。
七、整合SpringMVC
7.1、配置spring-mvc.xml
配置里面的注释也很详细,在此就不说了,主要是自动扫描控制器,视图模式,注解的启动这三个
- <span style="font-size:18px;"><?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:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
- <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
- <context:component-scan base-package="com.liuhai.eshop.controller"></context:component-scan>
- <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
- <bean id="mappingJacksonHttpMessageConverter"
- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
- <!-- 详细介绍:http://www.ibm.com/developerworks/cn/web/wa-restful/ -->
- <bean
- class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="mappingJacksonHttpMessageConverter" /> <!-- 对象转化为JSON转换器 -->
- </list>
- </property>
- </bean>
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/jsps/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 默认编码 -->
- <property name="defaultEncoding" value="utf-8"></property>
- <!-- 文件大小最大值 -->
- <property name="maxUploadSize" value="10485760000"></property>
- <!-- 内存中的最大值 -->
- <property name="maxInMemorySize" value="40960"></property>
- </bean>
- </beans></span>
7.2、配置web.xml文件
这里面对applicationContext.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。配置一样有详细注释,不多解释了。
- <?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"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- version="3.0">
- <display-name>web 测试页面</display-name>
- <!-- Spring和mybatis的配置文件 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml</param-value>
- </context-param>
- <!-- 编码过滤器 -->
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <async-supported>true</async-supported>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- Spring监听器:启动Web容器时,自动装配ApplicationContext的配置信息,即上面的:contextConfigLocation-->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 防止Spring内存溢出监听器 -->
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
- <!-- Spring MVC servlet -->
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- <async-supported>true</async-supported>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 也可以是/-->
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
- <!-- 解决由于采用spring的过滤器,导致页面引用的JS、images、CSS发生找不到的错误;也可以用使用spring mvc 的 <mvc:resources /> 注解 用来处理静态文件 -->
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.css</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.gif</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.png</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.jpg</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.js</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>/index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
7.3 新建控制类controller及jsp页面之间交互
在这里使用jsp页面引入easyui集成并实现增删改查功能
userManage.jsp如下:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'userManage.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.1/themes/default/easyui.css">
- <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/icon.css">
- <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.min.js"></script>
- <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
- <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js"></script>
- <script type="text/javascript">
- var url;
- function openUserAddDialog() {
- $("#dlg").dialog("open").dialog("setTitle", "添加用户信息");
- url = "${pageContext.request.contextPath}/user/save.do";
- }
- function saveUser() {
- $("#fm").form("submit", {
- url : url,
- onSubmit : function() {
- if ($("#roleName").combobox("getValue") == "") {
- $.messager.alert("系统提示", "请选择用户角色!");
- return false;
- }
- return $(this).form("validate");
- },
- success : function(result) {
- var result = eval('(' + result + ')');
- if (result.success) {
- $.messager.alert("系统提示", "保存成功!");
- resetValue();
- $("#dlg").dialog("close");
- $("#dg").datagrid("reload");
- } else {
- $.messager.alert("系统提示", "保存失败!");
- return;
- }
- }
- });
- }
- function searchUser() {
- $("#dg").datagrid('load', {
- "userName" : $("#s_userName").val()
- });
- }
- function resetValue() {
- $("#userName").val("");
- $("#password").val("");
- $("#trueName").val("");
- $("#email").val("");
- $("#phone").val("");
- $("#roleName").combobox("setValue", "");
- }
- function deleteUser() {
- var selectedRows = $("#dg").datagrid("getSelections");
- if (selectedRows.length == 0) {
- $.messager.alert("系统提示", "请选择要删除的数据!");
- return;
- }
- var strIds = [];
- for ( var i = 0; i < selectedRows.length; i++) {
- strIds.push(selectedRows[i].id);
- }
- var ids = strIds.join(",");
- $.messager.confirm("系统提示", "您确定要删除这<font color=red>"
- + selectedRows.length + "</font>条数据吗?", function(r) {
- if (r) {
- $.post("${pageContext.request.contextPath}/user/delete.do", {
- ids : ids
- }, function(result) {
- if (result.success) {
- $.messager.alert("系统提示", "数据已成功删除!");
- $("#dg").datagrid("reload");
- } else {
- $.messager.alert("系统提示", "数据删除失败,请联系系统管理员!");
- }
- }, "json");
- }
- });
- }
- function openUserModifyDialog() {
- var selectedRows = $("#dg").datagrid("getSelections");
- if (selectedRows.length != 1) {
- $.messager.alert("系统提示", "请选择一条要编辑的数据!");
- return;
- }
- var row = selectedRows[0];
- $("#dlg").dialog("open").dialog("setTitle", "编辑用户信息");
- $("#fm").form("load", row);
- url = "${pageContext.request.contextPath}/user/save.do?id=" + row.id;
- }
- </script>
- </head>
- <body style="margin: 1px">
- <table id="dg" title="用户管理" class="easyui-datagrid" fitColumns="true"
- pagination="true" rownumbers="true"
- url="${pageContext.request.contextPath}/user/list.do" fit="true"
- toolbar="#tb">
- <thead>
- <tr>
- <th field="cb" checkbox="true" align="center"></th>
- <th field="id" width="50" align="center">编号</th>
- <th field="userName" width="50" align="center">用户名</th>
- <th field="password" width="50" align="center">密码</th>
- <th field="trueName" width="50" align="center">真实姓名</th>
- <th field="email" width="50" align="center">邮件</th>
- <th field="phone" width="50" align="center">联系电话</th>
- <th field="roleName" width="50" align="center">角色</th>
- </tr>
- </thead>
- </table>
- <div id="tb">
- <a href="javascript:openUserAddDialog()" class="easyui-linkbutton"
- iconCls="icon-add" plain="true">添加</a> <a
- href="javascript:openUserModifyDialog()" class="easyui-linkbutton"
- iconCls="icon-edit" plain="true">修改</a> <a
- href="javascript:deleteUser()" class="easyui-linkbutton"
- iconCls="icon-remove" plain="true">删除</a>
- <div>
- 用户名: <input type="text" id="s_userName" size="20"
- onkeydown="if(event.keyCode == 13)searchUser()" /> <a
- href="javascript:searchUser()" class="easyui-linkbutton"
- iconCls="icon-search" plain="true">查询</a>
- </div>
- <div id="dlg-buttons">
- <a href="javascript:saveUser()" class="easyui-linkbutton"
- iconCls="icon-ok">保存</a> <a href="javascript:closeUserDialog()"
- class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
- </div>
- <div id="dlg" class="easyui-dialog"
- style="width: 730px;height:280px;padding:10px 10px;" closed="true"
- buttons="#dlg-buttons">
- <form method="post" id="fm">
- <table cellspacing="8px;">
- <tr>
- <td>用户名:</td>
- <td><input type="text" id="userName" name="userName"
- class="easyui-validatebox" required="true" /> <span
- style="color: red">*</span>
- </td>
- <td> </td>
- <td>密码:</td>
- <td><input type="password" id="password" name="password"
- class="easyui-validatebox" required="true" /> <span
- style="color: red">*</span>
- </td>
- </tr>
- <tr>
- <td>真实姓名:</td>
- <td><input type="text" id="trueName" name="trueName"
- class="easyui-validatebox" required="true" /> <span
- style="color: red">*</span>
- </td>
- <td> </td>
- <td>邮箱:</td>
- <td><input type="text" id="email" name="email"
- validType="email" class="easyui-validatebox" required="true" /> <span
- style="color: red">*</span>
- </td>
- </tr>
- <tr>
- <td>联系电话:</td>
- <td><input type="text" id="phone" name="phone"
- class="easyui-validatebox" required="true" /> <span
- style="color: red">*</span>
- </td>
- <td> </td>
- <td>用户角色:</td>
- <td><select name="roleName" class="easyui-combobox"
- id="roleName" style="width: 154px;" editable="false"
- panelHeight="auto">
- <option value="">请选择角色</option>
- <option value="系统管理员">系统管理员</option>
- <option value="销售主管">销售主管</option>
- <option value="客户经理">客户经理</option>
- <option value="高管">高管</option>
- </select> <span style="color: red">*</span>
- </td>
- </tr>
- </table>
- </form>
- </div>
- </div>
- </body>
- </html>
UserController.java
- package com.liuhai.eshop.controller;
- import java.io.File;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- import org.apache.commons.io.FileUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- import com.liuhai.eshop.domain.User;
- import com.liuhai.eshop.service.UserService;
- import com.liuhai.eshop.util.PageBean;
- import com.liuhai.eshop.util.ResponseUtil;
- import com.liuhai.eshop.util.StringUtil;
- @Controller
- @RequestMapping("/user")
- public class UserController {
- private static Logger log=LoggerFactory.getLogger(UserController.class);
- @Resource
- private UserService userService;
- @RequestMapping("/showUser.do")
- public String toIndex(HttpServletRequest request,Model model){
- System.out.println("liuhaitest");
- return "showUser";
- }
- // /user/test.do?id=1
- @RequestMapping(value="/test.do",method=RequestMethod.GET)
- public String test(HttpServletRequest request,Model model){
- int userId = Integer.parseInt(request.getParameter("id"));
- System.out.println("userId:"+userId);
- User user=null;
- if (userId==1) {
- user = new User();
- user.setAge(11);
- user.setId(1);
- user.setPassword("123");
- user.setUserName("javen");
- }
- log.debug(user.toString());
- model.addAttribute("user", user);
- return "index";
- }
- // /user/showUser.do?id=1
- @RequestMapping(value="/showUser.do",method=RequestMethod.GET)
- public String toindex(HttpServletRequest request,Model model){
- int userId = Integer.parseInt(request.getParameter("id"));
- System.out.println("userId:"+userId);
- User user = this.userService.getUserById(userId);
- log.debug(user.toString());
- model.addAttribute("user", user);
- return "showUser";
- }
- // /user/showUser2.do?id=1
- @RequestMapping(value="/showUser2.do",method=RequestMethod.GET)
- public String toIndex2(@RequestParam("id") String id,Model model){
- int userId = Integer.parseInt(id);
- System.out.println("userId:"+userId);
- User user = this.userService.getUserById(userId);
- log.debug(user.toString());
- model.addAttribute("user", user);
- return "showUser";
- }
- // /user/jsontype.do?id=1
- @RequestMapping(value="/jsontype.do",method=RequestMethod.GET)
- public @ResponseBody User getUserInJson(@RequestParam("id") String id,Map<String, Object> model){
- int userId = Integer.parseInt(id);
- System.out.println("userId:"+userId);
- User user = this.userService.getUserById(userId);
- log.info(user.toString());
- return user;
- }
- // /user/jsontype2.do?id=1
- @RequestMapping(value="/jsontype2.do",method=RequestMethod.GET)
- public ResponseEntity<User> getUserInJson2(@RequestParam("id") String id,Map<String, Object> model){
- int userId = Integer.parseInt(id);
- System.out.println("userId:"+userId);
- User user = this.userService.getUserById(userId);
- log.info(user.toString());
- return new ResponseEntity<User>(user,HttpStatus.OK);
- }
- //文件上传页面
- @RequestMapping(value="/upload.do")
- public String showUploadPage(){
- return "file";
- }
- //文件上传
- @RequestMapping(value="/doUpload.do",method=RequestMethod.POST)
- public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
- if (!file.isEmpty()) {
- log.info("Process file:{}",file.getOriginalFilename());
- }
- FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
- return "succes";
- }
- /**
- * 用户管理页面
- * @return
- */
- @RequestMapping(value="/userManage.do")
- public String userManagePage(){
- return "userManage";
- }
- /**
- * 添加或者修改
- * @param user
- * @param res
- * @return
- * @throws Exception
- */
- @RequestMapping("/save.do")
- public String save(User user,HttpServletResponse res) throws Exception{
- //操作记录条数,初始化为0
- int resultTotal = 0;
- if (user.getId() == null) {
- resultTotal = userService.add(user);
- }else{
- resultTotal = userService.update(user);
- }
- JSONObject jsonObject = new JSONObject();
- if(resultTotal > 0){ //说明修改或添加成功
- jsonObject.put("success", true);
- }else{
- jsonObject.put("success", false);
- }
- ResponseUtil.write(res, jsonObject);
- return null;
- }
- /**
- * 用户分页查询
- * @param page
- * @param rows
- * @param s_user
- * @param res
- * @return
- * @throws Exception
- */
- @RequestMapping("/list.do")
- public String list(@RequestParam(value="page",required=false) String page,@RequestParam(value="rows",required=false) String rows,User s_user,HttpServletResponse res) throws Exception{
- PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
- Map<String,Object> map=new HashMap<String,Object>();
- map.put("userName", StringUtil.formatLike(s_user.getUserName()));
- map.put("start", pageBean.getStart());
- map.put("size", pageBean.getPageSize());
- List<User> userList=userService.find(map);
- Long total=userService.getTotal(map);
- JSONObject result=new JSONObject();
- JSONArray jsonArray=JSONArray.fromObject(userList);
- result.put("rows", jsonArray);
- result.put("total", total);
- ResponseUtil.write(res, result);
- return null;
- }
- /**
- * 删除用户
- * @param ids
- * @param res
- * @return
- * @throws Exception
- */
- @RequestMapping("/delete.do")
- public String delete(@RequestParam(value="ids") String ids,HttpServletResponse res) throws Exception{
- String[] idStr = ids.split(",");
- JSONObject jsonObject = new JSONObject();
- for (String id : idStr) {
- userService.delete(Integer.parseInt(id));
- }
- jsonObject.put("success", true);
- ResponseUtil.write(res, jsonObject);
- return null;
- }
- }
7.4其它工具类及jsp页面
分页Model类PageBean.java
- package com.liuhai.eshop.util;
- /**
- * 分页Model类
- * @author Administrator
- *
- */
- public class PageBean {
- private int page; // 第几页
- private int pageSize; // 每页记录数
- private int start; // 起始页
- public PageBean(int page, int pageSize) {
- super();
- this.page = page;
- this.pageSize = pageSize;
- }
- public int getPage() {
- return page;
- }
- public void setPage(int page) {
- this.page = page;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public int getStart() {
- return (page-1)*pageSize;
- }
- }
用于返回json数据ResponseUtil.java
- package com.liuhai.eshop.util;
- import java.io.PrintWriter;
- import javax.servlet.http.HttpServletResponse;
- /***
- * 主要用于返回json数据
- * @author Administrator
- */
- public class ResponseUtil {
- public static void write(HttpServletResponse response,Object object)throws Exception{
- response.setContentType("text/html;charset=utf-8");
- PrintWriter out=response.getWriter();
- out.println(object);
- out.flush();
- out.close();
- }
- }
字符串工具类StringUtil.java如下:
- package com.liuhai.eshop.util;
- /***
- * 字符串工具类
- * @author Administrator
- *
- */
- public class StringUtil {
- /**
- * 判断是否是空
- * @param str
- * @return
- */
- public static boolean isEmpty(String str){
- if(str==null||"".equals(str.trim())){
- return true;
- }else{
- return false;
- }
- }
- /**
- * 判断是否不是空
- * @param str
- * @return
- */
- public static boolean isNotEmpty(String str){
- if((str!=null)&&!"".equals(str.trim())){
- return true;
- }else{
- return false;
- }
- }
- /**
- * 格式化模糊查询
- * @param str
- * @return
- */
- public static String formatLike(String str){
- if(isNotEmpty(str)){
- return "%"+str+"%";
- }else{
- return null;
- }
- }
- }
上传文件file.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>
- <h1>上传文件</h1>
- <form method="post" action="../user/doUpload.do" enctype="multipart/form-data">
- <input type="file" name="file"/>
- <input type="submit" value="上传文件"/>
- </form>
- </body>
- </html>