轻松搭建SpringMVC、Spring和Mybatis框架

环境搭建是基于Myeclipse10,数据库用的是Mysql

1、创建web project,project name是ssm,在WEB-INF目录下的lib中添加相关架包和创建数据库(ssm)和表名称(t_user)(架包请见源码)

CREATE TABLE `t_user` (
  `id` varchar(36) NOT NULL default '',
  `name` varchar(32) default NULL,
  `password` varchar(32) default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、在src目录下面添加config.properties配置文件(配置数据库的相关信息),配置如下:

validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=zhenyao

3、在src目录下添加spring-mvc.xml,spring-mybatis.xml和spring.xml配置文件,配置如下:

spring.xml:







spring-mvc.xml:


xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">





class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />

spring-mybatis.xml:


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

init-method="init" destroy-method="close">














































class="org.springframework.jdbc.datasource.DataSourceTransactionManager">





























expression="execution(* com.zy.service..*Impl.*(..))" />
advice-ref="transactionAdvice" />



class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">

scope="prototype">


com.zy.service.*





pointcut-ref="druid-stat-pointcut" />

4、打开web.xml文件,引入spring.xml,spring-mvc.xml和spring-mybats.xml文件

web.xml:


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_3_0.xsd">


spring监听器
org.springframework.web.context.ContextLoaderListener


org.springframework.web.util.IntrospectorCleanupListener


contextConfigLocation
classpath:spring.xml;classpath:spring-mybatis.xml




字符集过滤器
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter

字符集编码
encoding
UTF-8



encodingFilter
/*




spring mvc servlet
springMvc
org.springframework.web.servlet.DispatcherServlet

spring mvc 配置文件
contextConfigLocation
classpath:spring-mvc.xml

1


springMvc
/


15


index.jsp


5、在src目录下创建com.zy.controller,com.zy.dao,com.zy.mapping,com.zy.model和com.zy.service五个package,

并在model包下创建实体User.java

User.java:

package com.zy.model;

public class User {
    private String id;

    private String name;

    private String password;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "Add [id=" + id + ", name=" + name + ", password=" + password
+ "]";
}

}

6、在dao包下创建接口UserMapper.java

UserMapper.java:

package com.zy.dao;

import java.util.List;
import com.zy.model.User;

public interface UserMapper {
    int deleteByPrimaryKey(String id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    
    List getAll();
}

7、在service包下创建接口UserService.java,

UserService.java:

package com.zy.service;

import java.util.List;
import com.zy.model.User;

public interface UserService {

String addInfo(User addInfo);

List getAll();

String delete(String id);

User findById(String id);

String update(User addInfo);

}

8、在service包下创建package(Impl),并在该包下创建UserServiceImpl.java

UserServiceImpl.java:

package com.zy.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zy.dao.UserMapper;
import com.zy.model.User;
import com.zy.service.UserService;

@Service("baseService")
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public String addInfo(User addInfo) {
if (userMapper.insertSelective(addInfo) == 1) {
return "添加成功";
}
return "添加失败";
}
@Override
public List getAll() {
return userMapper.getAll();
}
@Override
public String delete(String id) {
if (userMapper.deleteByPrimaryKey(id) == 1) {
return "删除成功";
}
return "删除失败";
}
@Override
public User findById(String id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public String update(User addInfo) {
if (userMapper.updateByPrimaryKeySelective(addInfo) == 1) {
return "更新成功";
}
return "更新失败";
}
}

9、在mapping包下创建UserMapper.xml

UserMapper.xml:




 
   
   
   
 

 
    id, name, password
 

 
 
    delete from t_user
    where id = #{id,jdbcType=VARCHAR}
 

 
    insert into t_user (id, name, password
      )
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
 

 
    insert into t_user
   
     
        id,
     

     
        name,
     

     
        password,
     

   

   
     
        #{id,jdbcType=VARCHAR},
     

     
        #{name,jdbcType=VARCHAR},
     

     
        #{password,jdbcType=VARCHAR},
     

   

 

 
    update t_user
   
     
        name = #{name,jdbcType=VARCHAR},
     

     
        password = #{password,jdbcType=VARCHAR},
     

   

    where id = #{id,jdbcType=VARCHAR}
 

 
    update t_user
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
 

  
 

10、在WebRoot目录下创建add.jsp,index.jsp,listAll.jsp,modify.jsp和result.jsp

add.jsp:



用户名:

密    码:




index.jsp:


    新增数据
    查看全部数据
 

listAll.jsp:


所有结果

















编号用户名密码操作
${list.id}${list.name}${list.password}更新    href="user/del?tid=${list.id}" title="删除">删除


modify.jsp:



用户名: 密码:type="password" name="password" value="${add.password }"> type="hidden" name="id" value="${add.id }"> type="submit" value="提交数据">


result.jsp:


${InfoMessage}
返回首页

11、在controller包下面创建UserController.java

UserController.java:

package com.zy.controller;

import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zy.model.User;
import com.zy.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

@Resource
private UserService userService;

@SuppressWarnings("finally")
@RequestMapping(value = "/addInfo")
public String addUser(@ModelAttribute User user, HttpServletRequest request) {
try {
user.setId(UUID.randomUUID().toString());
System.out.println(user.getId() + ":::::" + user.getName() + ":::::"
+ user.getPassword());
String str = userService.addInfo(user);
System.out.println(str);
request.setAttribute("InfoMessage", str);
} catch (Exception e) {
request.setAttribute("InfoMessage",
"添加信息失败!具体异常信息:" + e.getMessage());
} finally {
return "result";
}
}

@RequestMapping("/getAll")
public String getAddInfoAll(HttpServletRequest request) {
try {
List list = userService.getAll();
System.out.println(list);
request.setAttribute("addLists", list);
return "listAll";
} catch (Exception e) {
request.setAttribute("InfoMessage",
"信息载入失败!具体异常信息:" + e.getMessage());
return "result";
}
}


@SuppressWarnings("finally")
@RequestMapping("/del")
public String del(String tid, HttpServletRequest request) {
try {
String str = userService.delete(tid);
request.setAttribute("InfoMessage", str);
} catch (Exception e) {
request.setAttribute("InfoMessage",
"删除信息失败!具体异常信息:" + e.getMessage());
} finally {
return "result";
}
}


@RequestMapping("/modify")
public String modify(String tid, HttpServletRequest request) {
try {
User user = userService.findById(tid);
request.setAttribute("add", user);
return "modify";
} catch (Exception e) {
request.setAttribute("InfoMessage",
"信息载入失败!具体异常信息:" + e.getMessage());
return "result";
}
}


@SuppressWarnings("finally")
@RequestMapping("/update")
public String update(User user, HttpServletRequest request) {
try {
String str = userService.update(user);
request.setAttribute("InfoMessage", str);
} catch (Exception e) {
request.setAttribute("InfoMessage",
"更新信息失败!具体异常信息:" + e.getMessage());
} finally {
return "result";
}
}
}

12、把工程ssm部署到tomcat服务器中,在地址栏输入http://localhost:7770/ssm/index.jsp

注意,7770是我自己tomcat的端口号,请自己修改

至此,框架搭建完成,如有疑问,请回复,谢谢!


你可能感兴趣的:(心得)