ssm整合和功能实现

这几天正在学习搭建ssm框架,再这里记录下中间出现的问题和成果。。。。

首先是整个工程的结构图:


其中,controller包下存放控制层文件,dao下存放各个model类相关的数据库操作接口,pojo下放置各种model类,mapper下放置各个dao对应的映射文件,service服务层就不说了,放置各种service接口,impl是其具体实现类。

ssm整合相关jar包下载地址http://download.csdn.net/download/a_crazydeveloper/10219807


各个xml配置问价的详细注解可以参考这篇博客(很详细):http://blog.csdn.net/qq_36367789/article/details/70991812

1.web.xml 文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<!-- 
在WEB-INF目录下新增加web.xml,这个web.xml有两个作用:
1. 通过ContextLoaderListener在web app启动的时候,获取contextConfigLocation配置文件的文件名applicationContext.xml,
并进行Spring相关初始化工作

2. 有任何访问,都被DispatcherServlet所拦截,这就是Spring MVC那套工作机制了。-->
 	<!-- spring的配置文件-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springMVC.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 </web-app>

2.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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  

	<!--1 自动扫描 将标注Spring注解的类自动转化Bean--> 
	<context:component-scan base-package="com.how2j.service"></context:component-scan>
	
	<!--2 加载数据资源属性文件 -->  
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:mysql.properties"></property>
	</bean>
	
	<!-- 3 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${jdbc.driver}" />  
        <property name="url" value="${jdbc.url}"  />  
        <property name="username" value="${jdbc.username}" />
         <property name="password" value="${jdbc.password}" />
	    <!-- 初始化连接大小 -->  
	  <!--   <property name="initialSize" value="${initialSize}"></property>  
	    连接池最大数量  
	    <property name="maxActive" value="${maxActive}"></property>  
	    连接池最大空闲  
	    <property name="maxIdle" value="${maxIdle}"></property>  
	    连接池最小空闲  
	    <property name="minIdle" value="${minIdle}"></property>  
	    获取连接最大等待时间  
	    <property name="maxWait" value="${maxWait}"></property>   -->
  	</bean>  
  	
  	<!-- 4   配置sessionfactory -->  
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!-- 自动扫描mapper文件 -->
		<property name="mapperLocations" value="classpath:com/how2j/mapper/*.xml"></property>
	</bean>
	
	<!-- 5  装配dao接口 --> 
	<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.how2j.dao"></property> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	
	<!-- 6、声明式事务管理 -->  
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

3.springMVC.xml 文件配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
          
 
    <!-- 1、配置映射器与适配器 --> 
    <mvc:annotation-driven></mvc:annotation-driven>
    
    <!-- 2、视图解析器 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="prefix" value="/WEB-INF/jsp/"></property>
    	<property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 3、自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器  --> 
    <context:component-scan base-package="com.how2j.controller"></context:component-scan>
    
    <mvc:default-servlet-handler/>

</beans>

4.mysql.properties 文件配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=Utf-8
jdbc.username=root
jdbc.password=root
initialSize=0  
#定义最大连接数  
maxActive=20  
#定义最大空闲  
maxIdle=20  
#定义最小空闲  
minIdle=1  
#定义最长等待时间  
maxWait=60000  
到此一个简单的ssm框架整合就完成了,接下来就再完成具体的功能实现。。


pojo 用户实体类

package com.how2j.pojo;

public class User {
	
	private Integer id;
	
	private String username;
	
	private String password;
	
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

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

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
}
dao层实现

package com.how2j.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.how2j.pojo.User;


public interface UserDao {
	
    public int addUser(User user) throws Exception;
    
    public int updateUser (User user) throws Exception;
    
    public int deleteUser(int id) throws Exception;
    
    public List<User> getUsers() throws Exception;
    
	String findAge(@Param("id")String id);
    
}
service 层和 实现类

package com.how2j.service;

import java.util.List;

import com.how2j.pojo.User;

public interface IuserService {

	public int addUser(User user)throws Exception;
	
	public int deleteUser(Integer id)throws Exception;
	
	public String findAge(String id) throws Exception;
	 
	public int updateUser(User user)throws Exception;
	
	public List<User> getUsers()throws Exception;

}
package com.how2j.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.how2j.dao.UserDao;
import com.how2j.pojo.User;
import com.how2j.service.IuserService;

@Service("userService")
@Transactional
public class userService implements IuserService{
	
	@Resource
	public UserDao userdao;

	@Override
	public String findAge(String id) throws Exception {
		// TODO Auto-generated method stub
		return userdao.findAge(id);
	}

	@Override
	public int updateUser(User user) throws Exception {
		// TODO Auto-generated method stub
		return userdao.updateUser(user);
	}

	@Override
	public int addUser(User user) throws Exception {
		// TODO Auto-generated method stub
		return userdao.addUser(user);
	}

	@Override
	public int deleteUser(Integer id) throws Exception {
		// TODO Auto-generated method stub
		return userdao.deleteUser(id);
	}

	@Override
	public List<User> getUsers() throws Exception {
		// TODO Auto-generated method stub
		return userdao.getUsers();
	}

}
数据库 SQL映射文件 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.how2j.dao.UserDao">

   <select id="findAge" parameterType="java.lang.String" resultType="java.lang.String">
       select age from t_user WHERE id=#{id} 
   </select>
   
   <update id="updateUser" parameterType="com.how2j.pojo.User">
   		update t_user set username = #{username},password = #{password},age = #{age} where id = #{id}
   </update>
   
   <insert id="addUser" parameterType="com.how2j.pojo.User" useGeneratedKeys="true" keyProperty="id">
   		insert into t_user (username,password,age) value(#{username},#{password},#{age})
   </insert>
   
   <delete id="deleteUser" parameterType="java.lang.Integer">
   		delete from t_user where id = #{id}
   </delete>
   
   <select id="getUsers" resultType="com.how2j.pojo.User">
   		select * from t_user
   </select> 
   
</mapper>
controller 控制层

package com.how2j.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

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

import com.how2j.pojo.User;
import com.how2j.service.impl.userService;

@Controller
public class UserController {
	
	@Autowired
	public userService userService;
	
	/*  添加用户  */
	@RequestMapping("addUser")
	public ModelAndView addUser(User user) throws Exception{
		ModelAndView mav = new ModelAndView();
		int flag = userService.addUser(user);
		mav.addObject("flag",flag);
		mav.setViewName("showUser");
		System.out.println("ddddddd "+flag);
		return mav;
	}
	
	@RequestMapping("deleteUser")
	public ModelAndView deleteUser(Integer id) throws Exception{
		ModelAndView mav = new ModelAndView();
		int flag = userService.deleteUser(id);
		mav.addObject("flag",flag);
		mav.setViewName("showUser");
		System.out.println("ddddddd "+flag);
		return mav;
	}
	
	@RequestMapping("getUsers")
	public ModelAndView getUsers() throws Exception{
		ModelAndView mav = new ModelAndView();
		List<User> list = new ArrayList<>();
		list = userService.getUsers();
		mav.addObject("list",list);
		mav.setViewName("showUser");
		System.out.println("ddddddd "+list);
		return mav;
	}
	
	@RequestMapping("findAge")
	public ModelAndView findAge(@RequestParam("id")String id) throws Exception{
		ModelAndView mav = new ModelAndView();
		String id_ = userService.findAge(id);
		mav.addObject("id",id_);
		mav.setViewName("showUser");
		System.out.println("ddddddd "+id_);
		return mav;
	}
	
	@RequestMapping("updaUser")
	public ModelAndView updateUser(User user) throws Exception{
		ModelAndView mav = new ModelAndView();
		int flag = userService.updateUser(user);
		mav.addObject("flag",flag);
		mav.setViewName("showUser");
		System.out.println("ddddddd "+flag);
		return mav;
	}
}
jsp视图显示效果

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${list[0].username }
</body>
</html>
数据库很简单这里就不放出来了,可以通过实体类了解表结构。

到此ssm框架整合 和一个简单的用户增删改查就完成了。。。


猜你喜欢

转载自blog.csdn.net/A_CrazyDeveloper/article/details/79127058
今日推荐