练习ssm框架整合,做增删改查操作

来源:互联网 发布:腾讯足球数据库 编辑:程序博客网 时间:2024/06/09 10:57
我的开发环境:Windows10系统
开发工具:MyEclipse10,JDK1.8,MySQL5.0,Tomcat7.0
ssm框架整合
在MyEclipse里建一个web工程,然后搭建环境,就是导入jar包,我的jar包是管老师要的,里边有连接数据库驱动的,有spring的,有spring-mvc的和mybatis的,总之很多。把这些jar包放到工程里的WebRoot目录下的WEB-INF目录下的lib文件夹下,总之记住jar包都放lib文件夹下。然后依据我个人习惯,会先配置一个日志文件在src目录下建,这个日志文件在网上找一个粘过来就可以了,日志文件代码如下:
[html] view plain copy
  1. <span style="font-size:14px;">log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator</span>  
然后在src目录下建一个JDBC配置文件,这个文件里的内容可以写在数据源里,但是都写一起会显得乱,我的JDBC代码如下:
[plain] view plain copy
  1. <span style="font-size:14px;">jdbc.driver=com.mysql.jdbc.Driver  
  2. jdbc.username=root  
  3. jdbc.password=***  
  4. jdbc.url=jdbc:mysql://localhost:3306/***  
  5. jdbc.pool.maxldle=5  
  6. jdbc.pool.maxActive=40</span>  
password是数据库密码,我用***代替了,这里根据自己的数据库来写,URL连的是MySQL数据库,如果是其的数据库就写其他的URL(还有连接数据库的驱动也是),3306是端口号,它后面写数据库名,这里也用***代替了,下面是数据库连接池的上下限,什么等待时长,空闲什么的没设,就设了这两值。
接下来在src目录下建spring.xml配置文件,这个代码里都写注释了,最上面是一些约束。我用的是注解编程,这里有些对注解的配置,我的spring.xml代码如下:
[html] view plain copy
  1. <span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"  
  7.   
  8.     xsi:schemaLocation="  
  9.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  10.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  11.         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd  
  12.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  13.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  14.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  15.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd  
  16.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"  
  17.     default-lazy-init="true"><!-- 属性default-lazy-init是一个懒加载过程,设成true时,用到对象才实例化,不用时不实例化,false反之 -->  
  18.     <!-- 如果要使用自动注入等注解,需要一条一条配置,用下面这条标签就不用配置了,它会自动识别注解。 向 spring容器注册标签 -->  
  19.     <context:annotation-config/>  
  20.     <!-- 注解扫描包,base-package里是要扫描的路径===========================================需要改的 -->  
  21.     <context:component-scan base-package="com"/>  
  22.     <!-- 配置数据源,使用的是bonecp  bonecp的效率,速度要高于c3p0 -->  
  23.     <!-- 设置要读取的jdbc配置文件 -->  
  24.     <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>  
  25.     <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">  
  26.         <property name="driverClass" value="${jdbc.driver}"></property>  
  27.         <property name="jdbcUrl" value="${jdbc.url}"></property>  
  28.         <property name="username" value="${jdbc.username}"></property>  
  29.         <property name="password" value="${jdbc.password}"></property>  
  30.     </bean>  
  31.       
  32.     <!-- spring和mybatis整合,不用写mybatis主配置文件 -->  
  33.     <!-- 创建sqlSessionFactory会话工厂,用于生产工厂对象,固定的 -->  
  34.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  35.         <!-- 连接数据库的,ref里写配置数据源里的id名 -->  
  36.         <property name="dataSource" ref="dataSource"></property>  
  37.         <!-- 管理mybatis工具的,value里写mybatis的配置文件名:classpath:文件名.xml -->  
  38.         <property name="mapperLocations" value="classpath:mybatis/*mapper.xml"></property>  
  39.     </bean>  
  40.       
  41.     <!-- 配置DAO  让spring自动查找DAO并创建实例,这是扫描功能 -->  
  42.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  43.         <!-- value里是要扫描的路径========================================需要改的 -->  
  44.         <property name="basePackage" value="com.dao"></property>  
  45.         <!-- value里是创建会话工厂里的id -->  
  46.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
  47.     </bean>                                                 
  48.     <!-- 事务处理 -->  
  49.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  50.         <property name="dataSource" ref="dataSource"></property>  
  51.     </bean>  
  52. </beans>  
  53. </span>  
在这里,大多数都是固定的,需要改的都标出来了。这里数据源的配置就是连接JDBC配置文件的。管理mybatis工具的那行标签里的value里写的是mybatis配置文件的路径,建完mybatis配置文件在写这个value。
接下来在src目录下写spring-MVC配置文件,代码如下:
[html] view plain copy
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  6.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  7.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
  8.     <!-- 使springmvc支持注解    
  9.       mvc:annotation-driven:注解驱动标签,表示使用了注解映射器和注解适配器,就是加载映射器和适配器的 -->  
  10.     <mvc:annotation-driven>  
  11.         <mvc:message-converters register-defaults="true"><!-- 消息转换器,属性:注册默认值 -->  
  12.             <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->  
  13.             <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">  
  14.                 <property name="supportedMediaTypes">  
  15.                     <list>  
  16.                         <value>application/json;charset=UTF-8</value>  
  17.                     </list>  
  18.                 </property>  
  19.             </bean><!-- 支持json 解决406 -->  
  20.         </mvc:message-converters>  
  21.     </mvc:annotation-driven>  
  22.     <!-- 使用默认的处理器 -->  
  23.     <mvc:default-servlet-handler/>  
  24.     <!-- 配置视图解析器  base-package扫描有注解的类-->  
  25.     <context:component-scan base-package="com.controller"></context:component-scan>  
  26.       
  27. </beans>  
这个文件上边也是约束,中间有一个对编码的配置,可以不写,可以用其他方式对编码进行配置,配置视图解析器里写的是有注解的类,多数指控制层的类,这里扫描的是controller类。
接下来就写mybatis配置文件,先在src目录下建一个mybatis包,再在mybatis包下建一个mybatis配置文件,这文件名随意起,但是必须以什么什么-mapper.xml结尾,例如我mybatis文件名叫:userinfo-mapper.xml。这里的代码是和dao层对应的,这里的代码在写dao层时展示。(建完mybatis配置文件后别忘了在spring配置文件里把管理mybatis工具的那行标签里的value写了)

到这,ssm的三大配置文件spring,spring-MVC,mybatis就建完了,之后spring和spring-MVC基本不用动了,在mybatis配置文件里写sql语句就行了。三大配置文件写完了,不要忘了还有一个web.xml,这个文件在WEB-INF目录下,这里我也都写注释了,格式基本固定,代码如下:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.  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_2_5.xsd">  
  4.    
  5. <!-- 配置spring -->  
  6.     <context-param>  
  7.        <param-name>contextConfigLocation</param-name>  
  8.        <param-value>  
  9.             classpath*:/spring.xml  
  10.         </param-value>  
  11.     </context-param>  
  12.     <context-param>  
  13.         <param-name>spring.profiles.default</param-name>  
  14.         <param-value>development</param-value>  
  15.     </context-param>  
  16.     <listener>  
  17.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  18.     </listener>  
  19.       
  20.     <!-- 字符编码集过滤器 -->  
  21.     <filter>  
  22.        <filter-name>encoding</filter-name>   
  23.        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  24.        <init-param>  
  25.          <param-name>encoding</param-name>  
  26.          <param-value>UTF-8</param-value>  
  27.        </init-param>    
  28.     </filter>  
  29.     <filter-mapping>  
  30.       <filter-name>encoding</filter-name>  
  31.       <url-pattern>/*</url-pattern>  
  32.     </filter-mapping>  
  33.   
  34.  <!-- spring mvc 的配置 -->  
  35.  <servlet>  
  36.   <servlet-name>springmvc</servlet-name>  
  37.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  38.   <init-param>  
  39.     <param-name>contextConfigLocation</param-name>  
  40.     <param-value>classpath:spring-mvc.xml</param-value>  
  41.   </init-param>  
  42.  </servlet>  
  43.  <servlet-mapping>  
  44.   <servlet-name>springmvc</servlet-name>  
  45.   <url-pattern>/</url-pattern>  
  46.  </servlet-mapping>  
  47.  <welcome-file-list>  
  48.   <welcome-file>index.jsp</welcome-file>  
  49.  </welcome-file-list>  
  50.  <login-config>  
  51.   <auth-method>BASIC</auth-method>  
  52.  </login-config>  
  53. </web-app>  
到这配置文件全部 搞定,接下来,开始写java代码了
先建一个pojo包,在包里写一个pojo类,也叫bean类,是映射数据库字段的。就是在pojo类里建的私有属性要与数据库里的字段名一一对应,并设置get和set方法,写成java bean的形式。属性的类型要和数据库里的字段类型要一致,这个类很简单,代码省略了!!!
接下来建一个dao包,在dao包里写一个dao接口,在接口里定义要实现的方法。dao层是持久层,是联系数据库的,dao层的代码如下:
[html] view plain copy
  1. package com.dao;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.po.UserinfoPO;  
  7.   
  8. /**  
  9.  * DAO接口  
  10.  * @author lenovo  
  11.  *  
  12.  */  
  13. public interface UserinfoDAO {  
  14.     //验证登录  
  15. //    public List<Map> login(Map map);  
  16.     public UserinfoPO login(UserinfoPO po);  
  17.     //查询用户列表  
  18.     public List<UserinfoPO> userList(UserinfoPO po);  
  19.     //查询修改用户信息的id  
  20.     public List<UserinfoPO> updateid(UserinfoPO po);  
  21.     //修改用户信息  
  22.     public int update(UserinfoPO po);  
  23.     //添加用户信息  
  24.     public int insert(UserinfoPO po);  
  25.     //删除用户  
  26.     public int delete(int userid);  
  27.     //根据用户名模糊查询,根据权限查询  
  28.     public List<Map> select(Map map);  
  29. }  
这里用po对象或是Map都可以,写完dao层后,在mybatis配置文件里写sql语句,sql语句里的id一定要和dao接口里的方法名一致,mybatis配置文件里的代码如下:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3.   
  4. <!-- ==================代理方式=================  
  5. 由mapper标签开始,由/mapper结束,可以把它想成一个空间,是映射文件  
  6. 属性namespace:空间名,主要在代理中使用。这个namespace是唯一的。  
  7. 这里把mapper标签和接口联系在一起了,namespace=写接口路径,映射文件要和接口在同一目录下  
  8.  -->  
  9. <mapper namespace="com.dao.UserinfoDAO">  
  10.     <!-- =============映射关系标签=============  
  11.     属性type:写po类的包名类名,由于之前定义了po类的别名,这里就写这个别名  
  12.     属性id:是这个映射标签的唯一标识  
  13.     id标签是查询结果集中的唯一标识  
  14.     属性column:查询出来的列名  
  15.     属性property:是po类里所指定的列名  
  16.     通常会在原列名后面加下划线,这是固定的,这里就是id后面_  
  17.      -->  
  18.     <resultMap type="com.po.UserinfoPO" id="userinfoMap">  
  19.         <result column="userid" property="userid"/>  
  20.         <result column="loginname" property="loginname"/>  
  21.         <result column="loginpass" property="loginpass"/>  
  22.         <result column="username" property="username"/>  
  23.         <result column="upower" property="upower"/>  
  24.         <result column="birthday" property="birthday"/>  
  25.         <result column="sex" property="sex"/>  
  26.     </resultMap>  
  27.     <!-- ==================定义sql片段==============  
  28.     sql:是sql片段标签  
  29.     属性id是该片段的唯一标识  
  30.      -->  
  31.     <sql id="zd">  
  32.         userid,loginname,loginpass,username,upower,birthday,sex  
  33.     </sql>  
  34.     <!-- 增删改查标签里的id:一定要和接口里对应的方法名一致,  
  35.          resultMap输出类型里写映射标签里的id   
  36.          parameterType:输入类型,规范输入数据类型,指明查询时使用的参数类型-->  
  37.     <!-- 验证登录 ,有严重问题-->  
  38.     <select id="login" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">   
  39.         <!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->  
  40.         select <include refid="zd"></include> from userinfo  
  41.         <where>             
  42.                 loginname=#{loginname} and loginpass=#{loginpass}  
  43.         </where>  
  44.     </select>  
  45.       
  46.     <!-- 查询用户列表 -->  
  47.     <select id="userList" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">  
  48.         <!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->  
  49.         select <include refid="zd"></include> from userinfo  
  50.     </select>  
  51.       
  52.     <!-- 查询修改用户信息的id -->  
  53.     <select id="updateid" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">  
  54.         <!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->  
  55.         select <include refid="zd"></include> from userinfo  
  56.         <where>userid=#{userid}</where>  
  57.     </select>  
  58.     <!-- 修改用户信息 -->  
  59.      <update id="update" parameterType="com.po.UserinfoPO">  
  60.         update userinfo set loginname=#{loginname},loginpass=#{loginpass},username=#{username},  
  61.         upower=#{upower},birthday=#{birthday},sex=#{sex}  
  62.         where userid=#{userid}     
  63.      </update>  
  64.        
  65.     <!-- 添加用户信息 -->  
  66.     <insert id="insert" parameterType="com.po.UserinfoPO">  
  67.         insert into userinfo(<include refid="zd"></include>)   
  68.         values(#{userid},#{loginname},#{loginpass},#{username},#{upower},#{birthday},#{sex})  
  69.     </insert>  
  70.           
  71.     <!-- 增删改查标签里的id:一定要和接口里对应的方法名一致 -->  
  72.     <delete id="delete" parameterType="int">  
  73.         delete from userinfo where userid=#{userid}  
  74.     </delete>  
  75.       
  76.     <!-- 根据用户名模糊查询,根据权限查询 -->  
  77.     <select id="select" resultMap="userinfoMap" parameterType="java.util.Map">  
  78.         <!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->  
  79.         select <include refid="zd"></include> from userinfo  
  80.         <!-- 当页面没有输入用户名和选择权限,就让它的条件永远为真,就变成全查询了 -->  
  81.         <where>  
  82.             <if test="username == null and username = '' and upower == -1">  
  83.                 and 1=1  
  84.             </if>  
  85.             <if test="username != null and username !=''">  
  86.                 and username LIKE '%${username}%'   
  87.             </if>           
  88.             <if test="upower != -1">  
  89.                 and upower=#{upower}   
  90.             </if>           
  91.         </where>  
  92.     </select>  
  93. </mapper>  
dao写完后写service,先建一个service包,在service包里写一个service接口,同样,在service接口里写上要实现的方法,代码如下:
[html] view plain copy
  1. package com.service;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.po.UserinfoPO;  
  7.   
  8. public interface UserInfoInterface {  
  9.     //验证登录  
  10. //    public List<Map> getlogin(Map map);  
  11.     public UserinfoPO getlogin(UserinfoPO po);  
  12.     //查询用户列表  
  13.     public List<UserinfoPO> getuserList(UserinfoPO po);  
  14.     //查询修改用户信息的id  
  15.     public List<UserinfoPO> getupdateid(UserinfoPO po);  
  16.     //修改用户信息  
  17.     public String getupdate(UserinfoPO po);  
  18.     //添加用户信息  
  19.     public String getinsert(UserinfoPO po);  
  20.     //删除用户  
  21.     public String getdelete(int userid);  
  22.     //根据用户名模糊查询,根据权限查询  
  23.     public List<Map> getselect(Map map);  
  24. }  
然后再在service包下建一个接口实现类的包,在这个包里写service接口的实现类,service层是业务层,一般写事务处理的。具体代码如下:
[html] view plain copy
  1. package com.service.impl;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import javax.annotation.Resource;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import org.springframework.stereotype.Service;  
  10. import org.springframework.web.servlet.ModelAndView;  
  11.   
  12. import com.dao.UserinfoDAO;  
  13. import com.po.UserinfoPO;  
  14. import com.service.UserInfoInterface;  
  15. @Service  //表示这是一个业务层,是service类, @Controller是用于标注控制层组件,Component是当某一个类不好归类的时候用 这个注解  
  16. public class UserInfoImpl implements UserInfoInterface{  
  17.     @Resource //自动装载,根据名称注入  
  18.     //定义dao类型的属性  
  19.     UserinfoDAO udao;  
  20.     /**  
  21.      * 验证登录  
  22.      */  
  23. //    public List<Map> getlogin(Map map) {  
  24. //        //调dao里的方法  
  25. //        List<Map> userlogin=udao.login(map);  
  26. //        return userlogin;  
  27. //    }  
  28.     public UserinfoPO getlogin(UserinfoPO po) {  
  29.         //调dao里的方法  
  30.         UserinfoPO userinfo = udao.login(po);  
  31.         return userinfo;  
  32.     }  
  33.       
  34.     /**  
  35.      * 根据用户名模糊查询,根据权限查询  
  36.      */  
  37.     public List<Map> getselect(Map map) {  
  38.         List<Map> selectUser = udao.select(map);  
  39.         return selectUser;  
  40.     }  
  41.       
  42.     /**  
  43.      * 查询用户列表  
  44.      */  
  45.     public List<UserinfoPO> getuserList(UserinfoPO po) {  
  46.         List<UserinfoPO> userinfo = udao.userList(po);  
  47.         return userinfo;  
  48.     }  
  49.     /**  
  50.      * 查询修改用户信息的id  
  51.      */  
  52.     public List<UserinfoPO> getupdateid(UserinfoPO po) {  
  53.         List<UserinfoPO> updateid = udao.updateid(po);  
  54.         return updateid;  
  55.     }  
  56.     /**  
  57.      * 修改用户信息  
  58.      */  
  59.     public String getupdate(UserinfoPO po) {  
  60.         //调dao里的方法  
  61.         int u = udao.update(po);  
  62.         String message="";  
  63.         //数据库会返回一个int类型的数据,根据影响条数来判断操作是否成功  
  64.         if(u > 0){  
  65.             message = "修改成功";  
  66.         }else{  
  67.             message = "修改失败";  
  68.         }  
  69.         return message;  
  70.     }  
  71.     /**  
  72.      * 添加用户信息  
  73.      */  
  74.     public String getinsert(UserinfoPO po) {  
  75.         int i = udao.insert(po);  
  76.         String message="";  
  77.         if(i > 0){  
  78.             message = "添加成功";  
  79.         }else{  
  80.             message = "添加失败";  
  81.         }  
  82.         return message;  
  83.     }  
  84.     /**  
  85.      * 删除用户  
  86.      */  
  87.     public String getdelete(int userid) {  
  88.         int d = udao.delete(userid);  
  89.         String message="";  
  90.         if(d > 0){  
  91.             message = "删除成功";  
  92.         }else{  
  93.             message = "删除失败";  
  94.         }  
  95.         return message;  
  96.     }      
  97. }  
service层写完写控制层,建一个Controller包,在包里写一个Controller类,在这个类里负责接收页面上提交上来的值,和把从数据库里取到的值传到页面上,还有负责控制页面的跳转等。代码如下:
[html] view plain copy
  1. package com.controller;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.servlet.http.HttpSession;  
  11.   
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.stereotype.Controller;  
  14. import org.springframework.web.bind.annotation.PathVariable;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestParam;  
  17. import org.springframework.web.servlet.ModelAndView;  
  18.   
  19. import com.po.UserinfoPO;  
  20. import com.service.UserInfoInterface;  
  21.   
  22. @Controller  //标注这是一个控制类,类名不能和注解名一样  
  23. @RequestMapping("/uc")   //设置访问路径  
  24. public class UserinfoController {  
  25.     /**  
  26.      * 验证登录  
  27.      */  
  28.     @Autowired  
  29.     //定义service类型的属性  
  30.     UserInfoInterface uservice;  
  31.     @RequestMapping("/login")//为方法设置访问路径  
  32.     //@RequestParam(required=false)指定一下,map的参数是从request作用域里取的  
  33.     //通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传  
  34.     // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有  
  35.     //例:public String filesUpload(@RequestParam(value="aa"required=true)  
  36. //    public ModelAndView mav(@RequestParam(required=false) Map map){  
  37. //        List<Map> ml=uservice.getlogin(map);  
  38. //        ModelAndView mav=new ModelAndView();  
  39. //        mav.addObject("ulist", ml);  
  40. //        mav.setViewName("/main.jsp");  
  41. //        return mav;  
  42. //    }  
  43.     //登录  
  44.     public String ulogin(HttpServletRequest request){      
  45.         //接收页面的值  
  46.         String loginname = request.getParameter("loginname");  
  47.         String loginpass = request.getParameter("loginpass");  
  48.         UserinfoPO po = new UserinfoPO();  
  49.         //把接收到的值放入po里  
  50.         po.setLoginname(loginname);  
  51.         po.setLoginpass(loginpass);  
  52.         //调service方法去数据库验证  
  53.         UserinfoPO pojo = uservice.getlogin(po);  
  54.         if(pojo!=null){  
  55.             return "/uc/user";  
  56.         }else{              
  57.             return "/index.jsp";  
  58.         }      
  59.     }  
  60.       
  61.     /**  
  62.      * 查询用户列表  
  63.      */  
  64.     @RequestMapping("/user")//为方法设置访问路径  
  65.     public String userList(HttpServletRequest request, UserinfoPO po){  
  66.         //调service里的方法  
  67.         List<UserinfoPO> ulist = uservice.getuserList(po);  
  68.         //把值存到request作用域里,传到页面上  
  69.         request.setAttribute("ulist", ulist);  
  70.         //跳转的mian.jsp页面  
  71.         return "/main.jsp";  
  72.     }  
  73.       
  74.     /**  
  75.      * 查询修改用户信息的id  
  76.      */  
  77.     @RequestMapping("/uid")//为方法设置访问路径  
  78.     public String updateid(HttpServletRequest request, UserinfoPO po){  
  79.         List<UserinfoPO> uid = uservice.getupdateid(po);  
  80.         request.setAttribute("uid", uid);  
  81.         return "/update.jsp";  
  82.     }  
  83.     /**  
  84.      * 修改用户信息  
  85.      */  
  86.     @RequestMapping(value="/update")//为方法设置访问路径  
  87.     public String update(HttpServletRequest request, UserinfoPO po){          
  88.         String updateUser = uservice.getupdate(po);          
  89.         request.setAttribute("updateUser", updateUser);  
  90.         //修改信息后留在当前页  
  91.         return "/uc/uid";          
  92.     }  
  93.       
  94.     /**  
  95.      * 添加用户信息  
  96.      */  
  97.     @RequestMapping("/insert")//为方法设置访问路径  
  98.     public String insert(HttpServletRequest request, UserinfoPO po){  
  99.         String inserUser = uservice.getinsert(po);  
  100.         request.setAttribute("inserUser", inserUser);  
  101.         return "/insert.jsp";  
  102.     }  
  103.       
  104.     /**  
  105.      * 删除用户 ,根据id删除  
  106.      */  
  107.     //后面传了一个要删除的id值,比如要删除id是30的用户,整体路径是/uc/delete/30  
  108.     @RequestMapping(value="/delete/{userid}")  
  109.     public ModelAndView delete(@PathVariable("userid")int userid){  
  110.         String deleteUser=uservice.getdelete(userid);  
  111.         ModelAndView mav=new ModelAndView();  
  112.         mav.addObject("deleteUser", deleteUser);  
  113.         //跳到提醒页,返回service里定义的方法,提醒删除成功还是失败  
  114.         mav.setViewName("/tx.jsp");  
  115.         return mav;  
  116.     }  
  117.       
  118.     /**  
  119.      * 根据用户名模糊查询,根据权限查询  
  120.      */  
  121.     @RequestMapping("/select")//为方法设置访问路径  
  122.     public ModelAndView mav(@RequestParam(required=false) Map map){  
  123.         List<Map> selectUser = uservice.getselect(map);  
  124.         ModelAndView mav=new ModelAndView();  
  125.         mav.addObject("ulist", selectUser);  
  126.         mav.setViewName("/main.jsp");  
  127.         return mav;  
  128.     }  
  129. }  
  130.   
  131.    
写到这后台就差不多了,接下来写视图层,也就是页面。我为了方便把页面写在了WebRoot目录下,正常应该在WEB-INF目录下建相应的文件夹,把页面写在这个文件夹里,因为在WEB-INF目录下的文件是受保护的。在页面的代码中也都有非常详细的注释,这里就不过多的讲解了。我的登录页面代码如下:
[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>登录页</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.   <!-- 引入jQuery文件 -->  
  23.     <script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>  
  24.     <script type="text/javascript">  
  25.     // 控制onsubmit提交的方法,方法名是vform()  
  26.         function vform(){  
  27.             //获取下面的id值  
  28.             var ln = $("#loginname").val();  
  29.             var lp = $("#loginpass").val();  
  30.             //判断上面的变量,如果为空字符串不能提交  
  31.             if(ln == ""){  
  32.                 alert("请输入登录名!");  
  33.                 return false;  
  34.             }  
  35.             if(lp == ""){  
  36.                 alert("请输入密码!");  
  37.                 return false;  
  38.             }  
  39.             //除以上结果的可以提交,返回true  
  40.             return true;  
  41.         }  
  42.     </script>  
  43.     
  44.   <body>  
  45.     <div>晨魅---练习ssm框架整合!</div>  
  46.    <hr>  
  47.    <!-- 用onsubmit调用上面的方法 -->  
  48.    <form action="uc/login" method="post" onsubmit="return vform()">  
  49.     <!-- 用po类,这个name值可以随意起,不受mybatis配置文件影响了 -->  
  50.         <div>用户名:<input type="text" id="loginname" name="loginname"></div>  
  51.         <div style="margin-left:16px">密码:<input type="password" id="loginpass" name="loginpass"></div>          
  52.         <div><input type="submit" value="登录"></div>  
  53.    </form>  
  54.   </body>  
  55. </html>  
用户列表页面代码如下:
[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>用户列表</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <!-- 
  21.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  22.     -->  
  23.     <!-- 引入jQuery文件 -->  
  24.     <script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>  
  25.     <style type="text/css">  
  26.         td{text-align: center;}  
  27.         div{height: 1.5em;}  
  28.     </style>  
  29.     <script type="text/javascript">  
  30.         //定义个方法提醒用户确定要删除吗?方法的参数就是要删除的id名  
  31.         function deleteUser(userid){              
  32.                     if(confirm("您确认删除吗?")){   
  33.                     //如果确定删除就访问servlet,这里超链接传值传的是方法里的参数           
  34.                     window.location.href="uc/delete/"+userid;  
  35.                 }  
  36.             }  
  37.               
  38.         //重置按钮方法  
  39.         function clearForm() {  
  40.             //获取uname的id,让它的值等于空字符串  
  41.             $("#username").val("");  
  42.             //document.getElementById("username").value = "";             
  43.             //获取upower的id,让它被选中的序号等于0,因为下面有好几项option,第0项就是第一个  
  44.             document.getElementById("upower").selectedIndex = 0;  
  45.         }             
  46.     </script>  
  47.   
  48.   </head>  
  49.     
  50.   <body>  
  51.   <div>晨魅---练习ssm框架整合!</div>  
  52.    <hr>  
  53.     <!-- 查询部分,给表单定义个name属性,通过js提交 -->  
  54.   <form name="sform" action="uc/select" method="post">          
  55.         <div><!-- 如果这里写个value,value值就会显示在页面上,但是我取不出来request作用域里的值,所以查询时,页面上就没有查询的内容了 -->          
  56.             用户名:<input type="text" id="username" name="username">   
  57.         </div>  
  58.         <div style="margin-left:16px ">  
  59.             权限:  
  60.             <select name="upower" id="upower">  
  61.                 <option value="-1">-请选择-</option>  
  62.                 <option value="99">管理员</option><!-- 这里的问题同用户名 -->  
  63.                 <option value="1">普通用户</option>  
  64.             </select>  
  65.             <input type="submit" value="查询">  
  66.             <!-- 重置按钮,调重置方法clearForm -->  
  67.             <input type="button" onclick="clearForm()" value="重置">  
  68.         </div>  
  69.   </form>  
  70.   <hr>  
  71.      <a href="/ssmpo/insert.jsp">添加用户</a>  
  72.     <table border="1" width="700">  
  73.         <tr>  
  74.             <th>ID</th>  
  75.             <th>登录名</th>  
  76.             <th>密码</th>  
  77.             <th>用户名</th>  
  78.             <th>权限</th>  
  79.             <th>生日</th>  
  80.             <th>性别</th>  
  81.             <th>操作</th>  
  82.         </tr>  
  83.         <c:forEach var="po" items="${ulist }">  
  84.         <tr>  
  85.             <!-- 和po类里的属性名一样 -->  
  86.             <td>${po.userid }</td>  
  87.             <td>${po.loginname }</td>  
  88.             <td>${po.loginpass }</td>  
  89.             <td>${po.username }</td>              
  90.             <td>  
  91.                 <c:choose>  
  92.                     <c:when test="${po.upower == 99 }">  
  93.                         管理员  
  94.                     </c:when>  
  95.                     <c:otherwise>  
  96.                         普通用户  
  97.                     </c:otherwise>  
  98.                 </c:choose>  
  99.             </td>  
  100.             <td>${po.birthday }</td>  
  101.             <td>  
  102.                 <c:choose>  
  103.                     <c:when test="${po.sex == 1 }">  
  104.                         男  
  105.                     </c:when>  
  106.                     <c:when test="${po.sex == 2 }">  
  107.                         女  
  108.                     </c:when>  
  109.                     <c:otherwise>  
  110.                         保密  
  111.                     </c:otherwise>  
  112.                 </c:choose>  
  113.             </td>               
  114.             <td><!-- 用超链接传值方式把userid的值传给控制层 -->  
  115.             <a href="/ssmpo/uc/uid?userid=${po.userid }">修改</a>   
  116.             <!-- javascript:void(0)没有返回值,鼠标点击什么也不发生,如果写#号,点击会跳到顶部。  
  117.                 onclick="deleteUser(${po.userid}):调javascript里的方法,并把要删除的id值传进来  
  118.              -->  
  119.             <a href="javascript:void(0)" onclick="deleteUser(${po.userid})">删除</a>    
  120.             </td>  
  121.         </tr>  
  122.         </c:forEach>   
  123.     </table>  
  124.   </body>  
  125. </html>  

添加用户页面代码如下:
[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>添加用户</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <!-- 
  21.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  22.     -->  
  23.     <!-- 引入jQuery文件 -->  
  24.     <script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>  
  25.     <script type="text/javascript">  
  26.     // 控制onsubmit提交的方法,方法名是vform()  
  27.         function vform(){  
  28.             //获取下面的id值  
  29.             var ln = $("#loginname").val();  
  30.             var lp = $("#loginpass").val();  
  31.             var un = $("#username").val();  
  32.             var up = $("#upower").val();  
  33.             var bir = $("#birthday").val();  
  34.             //判断上面的变量,如果为空字符串不能提交  
  35.             if(ln == ""){  
  36.                 alert("请输入登录名!");  
  37.                 return false;  
  38.             }  
  39.             if(lp == ""){  
  40.                 alert("请输入密码!");  
  41.                 return false;  
  42.             }  
  43.             if(un == ""){  
  44.                 alert("请输入用户名!");  
  45.                 return false;  
  46.             }  
  47.             if(up == -1){  
  48.                 alert("请选择权限!");  
  49.                 return false;  
  50.             }  
  51.             if(bir == ""){  
  52.                 alert("请输入生日!");  
  53.                 return false;  
  54.             }             
  55.             //除以上结果的可以提交,返回true  
  56.             return true;  
  57.         }  
  58.     </script>  
  59.   
  60.   </head>  
  61.     
  62.   <body>  
  63.     <!-- 用onsubmit调用上面的方法 -->  
  64.     <form action="uc/insert" method="post" onsubmit="return vform()">   
  65.      <table width="1000" border="1">  
  66.         <tr>  
  67.             <th>登录名</th>  
  68.             <th>密码</th>  
  69.             <th>用户名</th>  
  70.             <th>权限</th>  
  71.             <th>生日</th>  
  72.             <th>性别</th>  
  73.         </tr>           
  74.         <tr>  
  75.             <td><input type="text" id="loginname" name="loginname"/></td>  
  76.             <td><input type="text" id="loginpass" name="loginpass"/></td>  
  77.             <td><input type="text" id="username" name="username"/></td>             
  78.             <td>  
  79.                 <select id="upower" name="upower" >  
  80.                     <option value="-1">=请选择=</option>  
  81.                     <option value="99">管理员</option>  
  82.                     <option value="1">普通用户</option>  
  83.                 </select>  
  84.             </td>              
  85.             <td><input type="text" id="birthday" name="birthday"></td>                      
  86.             <td>性别:  
  87.                 男<input type="radio" name="sex" value="1">  
  88.                 女<input type="radio" name="sex" value="2">  
  89.                 保密<input type="radio" name="sex" value="3" checked="checked">  
  90.             </td>   
  91.         </tr>  
  92.     </table>  
  93.     <input type="submit" value="提交">  
  94.      ${inserUser }<br>  
  95.       <a href="uc/user">返回</a>  
  96.    </form>  
  97.   </body>  
  98. </html>  

修改用户信息页面代码如下:
[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>修改用户信息</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <!-- 
  21.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  22.     -->  
  23.     <!-- 引入jQuery文件 -->  
  24.     <script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>  
  25.     <script type="text/javascript">  
  26.     // 控制onsubmit提交的方法,方法名是vform()  
  27.         function vform(){  
  28.             //获取下面的id值  
  29.             var ln = $("#loginname").val();  
  30.             var lp = $("#loginpass").val();  
  31.             var un = $("#username").val();  
  32.             var up = $("#upower").val();  
  33.             var bir = $("#birthday").val();  
  34.             //判断上面的变量,如果为空字符串不能提交  
  35.             if(ln == ""){  
  36.                 alert("请输入登录名!");  
  37.                 return false;  
  38.             }  
  39.             if(lp == ""){  
  40.                 alert("请输入密码!");  
  41.                 return false;  
  42.             }  
  43.             if(un == ""){  
  44.                 alert("请输入用户名!");  
  45.                 return false;  
  46.             }  
  47.             if(up == -1){  
  48.                 alert("请选择权限!");  
  49.                 return false;  
  50.             }  
  51.             if(bir == ""){  
  52.                 alert("请输入生日!");  
  53.                 return false;  
  54.             }             
  55.             //除以上结果的可以提交,返回true  
  56.             return true;  
  57.         }  
  58.     </script>  
  59.   </head>  
  60.     
  61.   <body>  
  62.     <!-- 用onsubmit调用上面的方法 -->  
  63.     <form action="uc/update" method="post" onsubmit="return vform()">      
  64.     <c:forEach var="po" items="${uid }">      
  65.         <input type="hidden"  name="userid" value="${po.userid}"/><br/>     
  66.         <table width="1000" border="1">  
  67.             <tr>                
  68.                 <th>登录名</th>  
  69.                 <th>密码</th>  
  70.                 <th>用户名</th>  
  71.                 <th>权限</th>  
  72.                 <th>生日</th>  
  73.                 <th>性别</th>  
  74.             </tr>           
  75.             <tr>  
  76.                 <td><input type="text" id="loginname" name="loginname" value="${po.loginname}"></td>  
  77.                 <td><input type="text" id="loginpass" name="loginpass" value="${po.loginpass}"></td>  
  78.                 <td><input type="text" id="username" name="username" value="${po.username }"></td>  
  79.                 <td>  
  80.                     <select id="upower" name="upower" >  
  81.                         <option value="-1">=请选择=</option>  
  82.                         <option value="99">管理员</option>  
  83.                         <option value="1">普通用户</option>  
  84.                     </select>  
  85.                 </td>                   
  86.                 <td><input type="text" id="birthday" name="birthday" value="${po.birthday }"></td>      
  87.                 <td>性别:  
  88.                     男<input type="radio" name="sex" value="1">  
  89.                     女<input type="radio" name="sex" value="2">  
  90.                     保密<input type="radio" name="sex" value="3" checked="checked">  
  91.                 </td>  
  92.            </tr>  
  93.     </table>  
  94.     </c:forEach>  
  95.     <input type="submit" value="提交"/>  
  96.     ${updateUser }<br><!-- 操作提醒 -->  
  97.       <a href="uc/user">返回</a>  
  98.     </form>  
  99.   </body>  
  100. </html>  

删除页是在用户列表页上操作的,我单独建了一个删除提醒页,提醒删除成功或是删除失败的,代码如下:
[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3.   
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.   <head>  
  12.     <base href="<%=basePath%>">  
  13.       
  14.     <title>删除提醒</title>  
  15.       
  16.     <meta http-equiv="pragma" content="no-cache">  
  17.     <meta http-equiv="cache-control" content="no-cache">  
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.     <meta http-equiv="description" content="This is my page">  
  21.     <!-- 
  22.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  23.     -->  
  24.     <style type="text/css">  
  25.         div{text-align: center;}  
  26.         div{height: 50px;width: 200px}  
  27.     </style>  
  28.   
  29.   </head>  
  30.     
  31.   <body>  
  32.     <div>  
  33.      ${deleteUser }<br>  
  34.     <a href="uc/user">返回</a>  
  35.     </div>  
  36.   </body>  
  37. </html>  
我这里有用到jQuery,需要找一个js文件,然后粘贴到WebRoot目录下,在页面里引入这个文件即可。
到这,练习ssm框架整合,做增删改查操作就全部写完了!!!
0 0