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

我的开发环境: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目录下建,这个日志文件在网上找一个粘过来就可以了,日志文件代码如下:
<span style="font-size:14px;">log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator</span>
然后在src目录下建一个JDBC配置文件,这个文件里的内容可以写在数据源里,但是都写一起会显得乱,我的JDBC代码如下:
<span style="font-size:14px;">jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=***
jdbc.url=jdbc:mysql://localhost:3306/***
jdbc.pool.maxldle=5
jdbc.pool.maxActive=40</span>
password是数据库密码,我用***代替了,这里根据自己的数据库来写,URL连的是MySQL数据库,如果是其的数据库就写其他的URL(还有连接数据库的驱动也是),3306是端口号,它后面写数据库名,这里也用***代替了,下面是数据库连接池的上下限,什么等待时长,空闲什么的没设,就设了这两值。
接下来在src目录下建spring.xml配置文件,这个代码里都写注释了,最上面是一些约束。我用的是注解编程,这里有些对注解的配置,我的spring.xml代码如下:
<span style="font-size:14px;"><?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"

	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
	default-lazy-init="true"><!-- 属性default-lazy-init是一个懒加载过程,设成true时,用到对象才实例化,不用时不实例化,false反之 -->
	<!-- 如果要使用自动注入等注解,需要一条一条配置,用下面这条标签就不用配置了,它会自动识别注解。 向 spring容器注册标签 -->
	<context:annotation-config/>
	<!-- 注解扫描包,base-package里是要扫描的路径===========================================需要改的 -->
	<context:component-scan base-package="com"/>
	<!-- 配置数据源,使用的是bonecp  bonecp的效率,速度要高于c3p0 -->
	<!-- 设置要读取的jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
	<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
		<property name="driverClass" value="${jdbc.driver}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	
	<!-- spring和mybatis整合,不用写mybatis主配置文件 -->
	<!-- 创建sqlSessionFactory会话工厂,用于生产工厂对象,固定的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 连接数据库的,ref里写配置数据源里的id名 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 管理mybatis工具的,value里写mybatis的配置文件名:classpath:文件名.xml -->
		<property name="mapperLocations" value="classpath:mybatis/*mapper.xml"></property>
	</bean>
	
	<!-- 配置DAO  让spring自动查找DAO并创建实例,这是扫描功能 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- value里是要扫描的路径========================================需要改的 -->
		<property name="basePackage" value="com.dao"></property>
		<!-- value里是创建会话工厂里的id -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>												
	<!-- 事务处理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>
</span>
在这里,大多数都是固定的,需要改的都标出来了。这里数据源的配置就是连接JDBC配置文件的。管理mybatis工具的那行标签里的value里写的是mybatis配置文件的路径,建完mybatis配置文件在写这个value。
接下来在src目录下写spring-MVC配置文件,代码如下:
<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" xmlns:aop="http://www.springframework.org/schema/aop"
	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-4.0.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">
	<!-- 使springmvc支持注解  
	  mvc:annotation-driven:注解驱动标签,表示使用了注解映射器和注解适配器,就是加载映射器和适配器的 -->
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true"><!-- 消息转换器,属性:注册默认值 -->
            <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean><!-- 支持json 解决406 -->
        </mvc:message-converters>
	</mvc:annotation-driven>
	<!-- 使用默认的处理器 -->
	<mvc:default-servlet-handler/>
	<!-- 配置视图解析器  base-package扫描有注解的类-->
	<context:component-scan base-package="com.controller"></context:component-scan>
	
</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目录下,这里我也都写注释了,格式基本固定,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
<!-- 配置spring -->
	<context-param>
	   <param-name>contextConfigLocation</param-name>
	   <param-value>
			classpath*:/spring.xml
		</param-value>
	</context-param>
  	<context-param>
    	<param-name>spring.profiles.default</param-name>
    	<param-value>development</param-value>
  	</context-param>
  	<listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  	</listener>
  	
  	<!-- 字符编码集过滤器 -->
  	<filter>
       <filter-name>encoding</filter-name> 
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
       </init-param> 	
  	</filter>
  	<filter-mapping>
  	  <filter-name>encoding</filter-name>
  	  <url-pattern>/*</url-pattern>
  	</filter-mapping>

 <!-- spring mvc 的配置 -->
 <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>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

到这配置文件全部 搞定,接下来,开始写java代码了
先建一个pojo包,在包里写一个pojo类,也叫bean类,是映射数据库字段的。就是在pojo类里建的私有属性要与数据库里的字段名一一对应,并设置get和set方法,写成java bean的形式。属性的类型要和数据库里的字段类型要一致,这个类很简单,代码省略了!!!
接下来建一个dao包,在dao包里写一个dao接口,在接口里定义要实现的方法。dao层是持久层,是联系数据库的,dao层的代码如下:
package com.dao;

import java.util.List;
import java.util.Map;

import com.po.UserinfoPO;

/**
 * DAO接口
 * @author lenovo
 *
 */
public interface UserinfoDAO {
    //验证登录
//    public List<Map> login(Map map);
    public UserinfoPO login(UserinfoPO po);
    //查询用户列表
    public List<UserinfoPO> userList(UserinfoPO po);
    //查询修改用户信息的id
    public List<UserinfoPO> updateid(UserinfoPO po);
    //修改用户信息
    public int update(UserinfoPO po);
    //添加用户信息
    public int insert(UserinfoPO po);
    //删除用户
    public int delete(int userid);
    //根据用户名模糊查询,根据权限查询
    public List<Map> select(Map map);
}


这里用po对象或是Map都可以,写完dao层后,在mybatis配置文件里写sql语句,sql语句里的id一定要和dao接口里的方法名一致,mybatis配置文件里的代码如下:
<?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标签开始,由/mapper结束,可以把它想成一个空间,是映射文件
属性namespace:空间名,主要在代理中使用。这个namespace是唯一的。
这里把mapper标签和接口联系在一起了,namespace=写接口路径,映射文件要和接口在同一目录下
 -->
<mapper namespace="com.dao.UserinfoDAO">
	<!-- =============映射关系标签=============
	属性type:写po类的包名类名,由于之前定义了po类的别名,这里就写这个别名
	属性id:是这个映射标签的唯一标识
	id标签是查询结果集中的唯一标识
	属性column:查询出来的列名
	属性property:是po类里所指定的列名
	通常会在原列名后面加下划线,这是固定的,这里就是id后面_
	 -->
	<resultMap type="com.po.UserinfoPO" id="userinfoMap">
		<result column="userid" property="userid"/>
		<result column="loginname" property="loginname"/>
		<result column="loginpass" property="loginpass"/>
		<result column="username" property="username"/>
		<result column="upower" property="upower"/>
		<result column="birthday" property="birthday"/>
		<result column="sex" property="sex"/>
	</resultMap>
	<!-- ==================定义sql片段==============
	sql:是sql片段标签
	属性id是该片段的唯一标识
	 -->
	<sql id="zd">
		userid,loginname,loginpass,username,upower,birthday,sex
	</sql>
	<!-- 增删改查标签里的id:一定要和接口里对应的方法名一致,
		 resultMap输出类型里写映射标签里的id 
		 parameterType:输入类型,规范输入数据类型,指明查询时使用的参数类型-->
	<!-- 验证登录 ,有严重问题-->
	<select id="login" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">	
		<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
		select <include refid="zd"></include> from userinfo
		<where>			
				loginname=#{loginname} and loginpass=#{loginpass}
		</where>
	</select>
	
	<!-- 查询用户列表 -->
	<select id="userList" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">
		<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
		select <include refid="zd"></include> from userinfo
	</select>
	
	<!-- 查询修改用户信息的id -->
	<select id="updateid" resultMap="userinfoMap" parameterType="com.po.UserinfoPO">
		<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
		select <include refid="zd"></include> from userinfo
		<where>userid=#{userid}</where>
	</select>
	<!-- 修改用户信息 -->
	 <update id="update" parameterType="com.po.UserinfoPO">
	 	update userinfo set loginname=#{loginname},loginpass=#{loginpass},username=#{username},
	 	upower=#{upower},birthday=#{birthday},sex=#{sex}
	 	where userid=#{userid}	 
	 </update>
	 
	<!-- 添加用户信息 -->
	<insert id="insert" parameterType="com.po.UserinfoPO">
		insert into userinfo(<include refid="zd"></include>) 
		values(#{userid},#{loginname},#{loginpass},#{username},#{upower},#{birthday},#{sex})
	</insert>
		
	<!-- 增删改查标签里的id:一定要和接口里对应的方法名一致 -->
	<delete id="delete" parameterType="int">
		delete from userinfo where userid=#{userid}
	</delete>
	
	<!-- 根据用户名模糊查询,根据权限查询 -->
	<select id="select" resultMap="userinfoMap" parameterType="java.util.Map">
		<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
		select <include refid="zd"></include> from userinfo
		<!-- 当页面没有输入用户名和选择权限,就让它的条件永远为真,就变成全查询了 -->
		<where>
			<if test="username == null and username = '' and upower == -1">
				and 1=1
			</if>
			<if test="username != null and username !=''">
				and username LIKE '%${username}%' 
			</if>			
			<if test="upower != -1">
				and upower=#{upower} 
			</if>			
		</where>
	</select>
</mapper>

dao写完后写service,先建一个service包,在service包里写一个service接口,同样,在service接口里写上要实现的方法,代码如下:
package com.service;

import java.util.List;
import java.util.Map;

import com.po.UserinfoPO;

public interface UserInfoInterface {
    //验证登录
//    public List<Map> getlogin(Map map);
    public UserinfoPO getlogin(UserinfoPO po);
    //查询用户列表
    public List<UserinfoPO> getuserList(UserinfoPO po);
    //查询修改用户信息的id
    public List<UserinfoPO> getupdateid(UserinfoPO po);
    //修改用户信息
    public String getupdate(UserinfoPO po);
    //添加用户信息
    public String getinsert(UserinfoPO po);
    //删除用户
    public String getdelete(int userid);
    //根据用户名模糊查询,根据权限查询
    public List<Map> getselect(Map map);
}


然后再在service包下建一个接口实现类的包,在这个包里写service接口的实现类,service层是业务层,一般写事务处理的。具体代码如下:
package com.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.dao.UserinfoDAO;
import com.po.UserinfoPO;
import com.service.UserInfoInterface;
@Service  //表示这是一个业务层,是service类, @Controller是用于标注控制层组件,Component是当某一个类不好归类的时候用 这个注解
public class UserInfoImpl implements UserInfoInterface{
    @Resource //自动装载,根据名称注入
    //定义dao类型的属性
    UserinfoDAO udao;
    /**
     * 验证登录
     */
//    public List<Map> getlogin(Map map) {
//        //调dao里的方法
//        List<Map> userlogin=udao.login(map);
//        return userlogin;
//    }
    public UserinfoPO getlogin(UserinfoPO po) {
        //调dao里的方法
        UserinfoPO userinfo = udao.login(po);
        return userinfo;
    }
    
    /**
     * 根据用户名模糊查询,根据权限查询
     */
    public List<Map> getselect(Map map) {
        List<Map> selectUser = udao.select(map);
        return selectUser;
    }
    
    /**
     * 查询用户列表
     */
    public List<UserinfoPO> getuserList(UserinfoPO po) {
        List<UserinfoPO> userinfo = udao.userList(po);
        return userinfo;
    }
    /**
     * 查询修改用户信息的id
     */
    public List<UserinfoPO> getupdateid(UserinfoPO po) {
        List<UserinfoPO> updateid = udao.updateid(po);
        return updateid;
    }
    /**
     * 修改用户信息
     */
    public String getupdate(UserinfoPO po) {
        //调dao里的方法
        int u = udao.update(po);
        String message="";
        //数据库会返回一个int类型的数据,根据影响条数来判断操作是否成功
        if(u > 0){
            message = "修改成功";
        }else{
            message = "修改失败";
        }
        return message;
    }
    /**
     * 添加用户信息
     */
    public String getinsert(UserinfoPO po) {
        int i = udao.insert(po);
        String message="";
        if(i > 0){
            message = "添加成功";
        }else{
            message = "添加失败";
        }
        return message;
    }
    /**
     * 删除用户
     */
    public String getdelete(int userid) {
        int d = udao.delete(userid);
        String message="";
        if(d > 0){
            message = "删除成功";
        }else{
            message = "删除失败";
        }
        return message;
    }    
}


service层写完写控制层,建一个Controller包,在包里写一个Controller类,在这个类里负责接收页面上提交上来的值,和把从数据库里取到的值传到页面上,还有负责控制页面的跳转等。代码如下:
package com.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.po.UserinfoPO;
import com.service.UserInfoInterface;

@Controller  //标注这是一个控制类,类名不能和注解名一样
@RequestMapping("/uc")   //设置访问路径
public class UserinfoController {
    /**
     * 验证登录
     */
    @Autowired
    //定义service类型的属性
    UserInfoInterface uservice;
    @RequestMapping("/login")//为方法设置访问路径
    //@RequestParam(required=false)指定一下,map的参数是从request作用域里取的
    //通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传
    // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
    //例:public String filesUpload(@RequestParam(value="aa", required=true)
//    public ModelAndView mav(@RequestParam(required=false) Map map){
//        List<Map> ml=uservice.getlogin(map);
//        ModelAndView mav=new ModelAndView();
//        mav.addObject("ulist", ml);
//        mav.setViewName("/main.jsp");
//        return mav;
//    }
    //登录
    public String ulogin(HttpServletRequest request){    
        //接收页面的值
        String loginname = request.getParameter("loginname");
        String loginpass = request.getParameter("loginpass");
        UserinfoPO po = new UserinfoPO();
        //把接收到的值放入po里
        po.setLoginname(loginname);
        po.setLoginpass(loginpass);
        //调service方法去数据库验证
        UserinfoPO pojo = uservice.getlogin(po);
        if(pojo!=null){
            return "/uc/user";
        }else{            
            return "/index.jsp";
        }    
    }
    
    /**
     * 查询用户列表
     */
    @RequestMapping("/user")//为方法设置访问路径
    public String userList(HttpServletRequest request, UserinfoPO po){
        //调service里的方法
        List<UserinfoPO> ulist = uservice.getuserList(po);
        //把值存到request作用域里,传到页面上
        request.setAttribute("ulist", ulist);
        //跳转的mian.jsp页面
        return "/main.jsp";
    }
    
    /**
     * 查询修改用户信息的id
     */
    @RequestMapping("/uid")//为方法设置访问路径
    public String updateid(HttpServletRequest request, UserinfoPO po){
        List<UserinfoPO> uid = uservice.getupdateid(po);
        request.setAttribute("uid", uid);
        return "/update.jsp";
    }
    /**
     * 修改用户信息
     */
    @RequestMapping(value="/update")//为方法设置访问路径
    public String update(HttpServletRequest request, UserinfoPO po){        
        String updateUser = uservice.getupdate(po);        
        request.setAttribute("updateUser", updateUser);
        //修改信息后留在当前页
        return "/uc/uid";        
    }
    
    /**
     * 添加用户信息
     */
    @RequestMapping("/insert")//为方法设置访问路径
    public String insert(HttpServletRequest request, UserinfoPO po){
        String inserUser = uservice.getinsert(po);
        request.setAttribute("inserUser", inserUser);
        return "/insert.jsp";
    }
    
    /**
     * 删除用户 ,根据id删除
     */
    //后面传了一个要删除的id值,比如要删除id是30的用户,整体路径是/uc/delete/30
    @RequestMapping(value="/delete/{userid}")
    public ModelAndView delete(@PathVariable("userid")int userid){
        String deleteUser=uservice.getdelete(userid);
        ModelAndView mav=new ModelAndView();
        mav.addObject("deleteUser", deleteUser);
        //跳到提醒页,返回service里定义的方法,提醒删除成功还是失败
        mav.setViewName("/tx.jsp");
        return mav;
    }
    
    /**
     * 根据用户名模糊查询,根据权限查询
     */
    @RequestMapping("/select")//为方法设置访问路径
    public ModelAndView mav(@RequestParam(required=false) Map map){
        List<Map> selectUser = uservice.getselect(map);
        ModelAndView mav=new ModelAndView();
        mav.addObject("ulist", selectUser);
        mav.setViewName("/main.jsp");
        return mav;
    }
}

 
写到这后台就差不多了,接下来写视图层,也就是页面。我为了方便把页面写在了WebRoot目录下,正常应该在WEB-INF目录下建相应的文件夹,把页面写在这个文件夹里,因为在WEB-INF目录下的文件是受保护的。在页面的代码中也都有非常详细的注释,这里就不过多的讲解了。我的登录页面代码如下:
<%@ 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>登录页</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="styles.css">
	-->
  </head>
  <!-- 引入jQuery文件 -->
	<script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>
	<script type="text/javascript">
	// 控制onsubmit提交的方法,方法名是vform()
		function vform(){
			//获取下面的id值
			var ln = $("#loginname").val();
			var lp = $("#loginpass").val();
			//判断上面的变量,如果为空字符串不能提交
			if(ln == ""){
				alert("请输入登录名!");
				return false;
			}
			if(lp == ""){
				alert("请输入密码!");
				return false;
			}
			//除以上结果的可以提交,返回true
			return true;
		}
	</script>
  
  <body>
    <div>晨魅---练习ssm框架整合!</div>
   <hr>
   <!-- 用onsubmit调用上面的方法 -->
   <form action="uc/login" method="post" οnsubmit="return vform()">
   	<!-- 用po类,这个name值可以随意起,不受mybatis配置文件影响了 -->
   		<div>用户名:<input type="text" id="loginname" name="loginname"></div>
   		<div style="margin-left:16px">密码:<input type="password" id="loginpass" name="loginpass"></div>  		
   		<div><input type="submit" value="登录"></div>
   </form>
  </body>
</html>
用户列表页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>用户列表</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="styles.css">
	-->
	<!-- 引入jQuery文件 -->
	<script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>
	<style type="text/css">
		td{text-align: center;}
		div{height: 1.5em;}
	</style>
	<script type="text/javascript">
		//定义个方法提醒用户确定要删除吗?方法的参数就是要删除的id名
		function deleteUser(userid){			
					if(confirm("您确认删除吗?")){	
					//如果确定删除就访问servlet,这里超链接传值传的是方法里的参数			
					window.location.href="uc/delete/"+userid;
				}
			}
			
		//重置按钮方法
		function clearForm() {
			//获取uname的id,让它的值等于空字符串
			$("#username").val("");
			//document.getElementById("username").value = "";			
			//获取upower的id,让它被选中的序号等于0,因为下面有好几项option,第0项就是第一个
			document.getElementById("upower").selectedIndex = 0;
		}			
	</script>

  </head>
  
  <body>
  <div>晨魅---练习ssm框架整合!</div>
   <hr>
   	<!-- 查询部分,给表单定义个name属性,通过js提交 -->
  <form name="sform" action="uc/select" method="post">  		
  		<div><!-- 如果这里写个value,value值就会显示在页面上,但是我取不出来request作用域里的值,所以查询时,页面上就没有查询的内容了 -->		
  			用户名:<input type="text" id="username" name="username"> 
  		</div>
  		<div style="margin-left:16px ">
  			权限:
  			<select name="upower" id="upower">
  				<option value="-1">-请选择-</option>
  				<option value="99">管理员</option><!-- 这里的问题同用户名 -->
  				<option value="1">普通用户</option>
  			</select>
  			<input type="submit" value="查询">
  			<!-- 重置按钮,调重置方法clearForm -->
  			<input type="button" οnclick="clearForm()" value="重置">
  		</div>
  </form>
  <hr>
     <a href="/ssmpo/insert.jsp">添加用户</a>
    <table border="1" width="700">
   		<tr>
   			<th>ID</th>
   			<th>登录名</th>
   			<th>密码</th>
   			<th>用户名</th>
   			<th>权限</th>
   			<th>生日</th>
   			<th>性别</th>
   			<th>操作</th>
   		</tr>
   		<c:forEach var="po" items="${ulist }">
  		<tr>
  			<!-- 和po类里的属性名一样 -->
  			<td>${po.userid }</td>
  			<td>${po.loginname }</td>
  			<td>${po.loginpass }</td>
  			<td>${po.username }</td> 			
  			<td>
				<c:choose>
	   				<c:when test="${po.upower == 99 }">
	   					管理员
	   				</c:when>
	   				<c:otherwise>
	   					普通用户
	   				</c:otherwise>
	   			</c:choose>
			</td>
			<td>${po.birthday }</td>
  			<td>
				<c:choose>
	   				<c:when test="${po.sex == 1 }">
	   					男
	   				</c:when>
	   				<c:when test="${po.sex == 2 }">
	   					女
	   				</c:when>
	   				<c:otherwise>
	   					保密
	   				</c:otherwise>
	   			</c:choose>
			</td>  			
  			<td><!-- 用超链接传值方式把userid的值传给控制层 -->
			<a href="/ssmpo/uc/uid?userid=${po.userid }">修改</a> 
			<!-- javascript:void(0)没有返回值,鼠标点击什么也不发生,如果写#号,点击会跳到顶部。
				οnclick="deleteUser(${po.userid}):调javascript里的方法,并把要删除的id值传进来
			 -->
			<a href="javascript:void(0)" οnclick="deleteUser(${po.userid})">删除</a>	
			</td>
   		</tr>
   		</c:forEach> 
   	</table>
  </body>
</html>

添加用户页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>添加用户</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="styles.css">
	-->
	<!-- 引入jQuery文件 -->
	<script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>
	<script type="text/javascript">
	// 控制onsubmit提交的方法,方法名是vform()
		function vform(){
			//获取下面的id值
			var ln = $("#loginname").val();
			var lp = $("#loginpass").val();
			var un = $("#username").val();
			var up = $("#upower").val();
			var bir = $("#birthday").val();
			//判断上面的变量,如果为空字符串不能提交
			if(ln == ""){
				alert("请输入登录名!");
				return false;
			}
			if(lp == ""){
				alert("请输入密码!");
				return false;
			}
			if(un == ""){
				alert("请输入用户名!");
				return false;
			}
			if(up == -1){
				alert("请选择权限!");
				return false;
			}
			if(bir == ""){
				alert("请输入生日!");
				return false;
			}			
			//除以上结果的可以提交,返回true
			return true;
		}
	</script>

  </head>
  
  <body>
  	<!-- 用onsubmit调用上面的方法 -->
    <form action="uc/insert" method="post" οnsubmit="return vform()"> 
     <table width="1000" border="1">
    	<tr>
	    	<th>登录名</th>
	    	<th>密码</th>
	    	<th>用户名</th>
	    	<th>权限</th>
	    	<th>生日</th>
	    	<th>性别</th>
   		</tr>   		
  		<tr>
  			<td><input type="text" id="loginname" name="loginname"/></td>
	    	<td><input type="text" id="loginpass" name="loginpass"/></td>
	    	<td><input type="text" id="username" name="username"/></td>	    	
	    	<td>
	    		<select id="upower" name="upower" >
	    			<option value="-1">=请选择=</option>
    				<option value="99">管理员</option>
    				<option value="1">普通用户</option>
    			</select>
   			</td>	  		   
	   		<td><input type="text" id="birthday" name="birthday"></td>			   		
	    	<td>性别:
	   			男<input type="radio" name="sex" value="1">
	    		女<input type="radio" name="sex" value="2">
	    		保密<input type="radio" name="sex" value="3" checked="checked">
	        </td>	
	   	</tr>
    </table>
    <input type="submit" value="提交">
     ${inserUser }<br>
      <a href="uc/user">返回</a>
   </form>
  </body>
</html>

修改用户信息页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>修改用户信息</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="styles.css">
	-->
	<!-- 引入jQuery文件 -->
	<script src="/ssmpo/js/jquery-1.11.2.min.js" language="javascript"></script>
	<script type="text/javascript">
	// 控制onsubmit提交的方法,方法名是vform()
		function vform(){
			//获取下面的id值
			var ln = $("#loginname").val();
			var lp = $("#loginpass").val();
			var un = $("#username").val();
			var up = $("#upower").val();
			var bir = $("#birthday").val();
			//判断上面的变量,如果为空字符串不能提交
			if(ln == ""){
				alert("请输入登录名!");
				return false;
			}
			if(lp == ""){
				alert("请输入密码!");
				return false;
			}
			if(un == ""){
				alert("请输入用户名!");
				return false;
			}
			if(up == -1){
				alert("请选择权限!");
				return false;
			}
			if(bir == ""){
				alert("请输入生日!");
				return false;
			}			
			//除以上结果的可以提交,返回true
			return true;
		}
	</script>
  </head>
  
  <body>
  	<!-- 用onsubmit调用上面的方法 -->
    <form action="uc/update" method="post" οnsubmit="return vform()">    
    <c:forEach var="po" items="${uid }">    
        <input type="hidden"  name="userid" value="${po.userid}"/><br/>   
    	<table width="1000" border="1">
	    	<tr>		    	
		    	<th>登录名</th>
		    	<th>密码</th>
		    	<th>用户名</th>
		    	<th>权限</th>
		    	<th>生日</th>
		    	<th>性别</th>
	   		</tr>  		
   			<tr>
		    	<td><input type="text" id="loginname" name="loginname" value="${po.loginname}"></td>
		    	<td><input type="text" id="loginpass" name="loginpass" value="${po.loginpass}"></td>
		    	<td><input type="text" id="username" name="username" value="${po.username }"></td>
		    	<td>
		    		<select id="upower" name="upower" >
		    			<option value="-1">=请选择=</option>
	    				<option value="99">管理员</option>
	    				<option value="1">普通用户</option>
	    			</select>
    			</td>	    			
	    		<td><input type="text" id="birthday" name="birthday" value="${po.birthday }"></td>	
		    	<td>性别:
		   			男<input type="radio" name="sex" value="1">
		    		女<input type="radio" name="sex" value="2">
		    		保密<input type="radio" name="sex" value="3" checked="checked">
		        </td>
		   </tr>
    </table>
    </c:forEach>
    <input type="submit" value="提交"/>
    ${updateUser }<br><!-- 操作提醒 -->
      <a href="uc/user">返回</a>
    </form>
  </body>
</html>

删除页是在用户列表页上操作的,我单独建了一个删除提醒页,提醒删除成功或是删除失败的,代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
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>删除提醒</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="styles.css">
	-->
	<style type="text/css">
		div{text-align: center;}
		div{height: 50px;width: 200px}
	</style>

  </head>
  
  <body>
    <div>
     ${deleteUser }<br>
    <a href="uc/user">返回</a>
    </div>
  </body>
</html>
我这里有用到jQuery,需要找一个js文件,然后粘贴到WebRoot目录下,在页面里引入这个文件即可。
到这,练习ssm框架整合,做增删改查操作就全部写完了!!!
下面是运行的效果图,初学ssm框架,做了一个小demo,没有做UI美化,这个样例仅供参考。 数据库文件在工程目录的最下方。

源码下载链接:  http://download.csdn.net/download/chenmeixxl/10213347   










  • 42
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 37
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 37
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值