ssm搭建一些笔记
本文最后更新于 2633 天前,其中的信息可能已经有所发展或是发生改变。

如果springmvc-config.xml文件和web.xml文件一样,都放在WEB-INF目录下的话。

在web.xml中springmvc最好这样配置一下

	<!-- SpringMVC配置 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/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>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

如果<param-value>/WEB-INF/springmvc.xml</param-value>

改为<param-value>classpath:springmvc.xml</param-value>

可能会出现->classpath指向的地址,与需要的文件不一致,报错很明显了。文件不存在

  1. 警告: No mapping found for HTTP request with URI
  2. class path resource [springmvc.xml] cannot be opened because it does not exist

那么就顺便记录下web.xml中或者spring配置文件中classpath和classpath*的区别吧

  1. 【classpath:】此配置表示告诉web容器去classpath(WEB-INF/classes和WEB-INF/lib)中去加载指定名称的配置文件,若是有同名文件,则只会加载一个。
  2. 【classpath*:】此配置表示告诉web容器去classpath(WEB-INF/classes和WEB-INF/lib)中去加载指定名称的配置文件,若是有同名文件则会全部加载。

  • classpath:只会到你的class路径中查找找文件;
  • classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找.

可以理解成就在/WEB-INF/classes/

因此classpath或者classpath*,编译之后会在/项目名/build/classes下找你的文件

而当你在WEB-INF目录下放置springmvc-config.xml文件和web.xml文件。

那么需要写成<param-value>/WEB-INF/springmvc.xml</param-value>

注意:

  1. 用classpath*:需要遍历所有的classpath,所以加载速度是很慢的,因此,在规划的时候,应该尽可能规划好资源文件所在的路径,尽量避免使用classpath*。
  2. 在多个classpath中存在同名资源时候,都需要加载,但是用classpath:只会加载第一个。
  3. lib和classes下文件访问优先级的问题:? lib>classes

总结的有点乱…希望日后自己可以理解一半吧


基于(spring+springmvc+mybatis)ssm搭建测试(不是基于maven搭建)

  • 创建表
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(18) DEFAULT NULL,
  `sex` char(2) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'admin', '女', '21');
INSERT INTO `tb_user` VALUES ('3', '修改后的', '女', '21');
INSERT INTO `tb_user` VALUES ('4', 'admin', '女', '21');
INSERT INTO `tb_user` VALUES ('2', 'update', '女', '21');
  • db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/ssm?characterEncoding=utf8
jdbc.username=root
jdbc.password=root
  • pojo
package com.glj.pojo;

import java.io.Serializable;

public class User implements Serializable{
	private Integer id;
	private String name;
	private String sex;
	private Integer age;
//省略set和get...
}
  • UserMapper
<?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.glj.dao.UserMapper">
	<!-- 	public List<User> getUser(); --> 
	<select id="getUserList" resultType="com.glj.pojo.User">
		select * from tb_user
	</select>
 </mapper>
  • UserMapper接口
package com.glj.dao;

import java.util.List;

import com.glj.pojo.User;

public interface UserMapper {
	public List<User> getUserList();
}	
  • UserService
package com.glj.service;

import java.util.List;

import com.glj.pojo.User;

public interface UserService {
	List<User> getUserList();
}
  • UserServiceImpl
package com.glj.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glj.dao.UserMapper;
import com.glj.pojo.User;
import com.glj.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public List<User> getUserList() {
		return userMapper.getUserList();
	}
	
}
  • UserController
package com.glj.controller;

import java.util.List;

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.servlet.ModelAndView;

import com.glj.pojo.User;
import com.glj.service.UserService;

@Controller
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/listUser")
	public ModelAndView listToUser(){
		ModelAndView mav = new ModelAndView();
		List<User> users = userService.getUserList();
		mav.addObject("users", users);
		return mav;
	}
//	@RequestMapping(value="/{fromName}")
//	public String fromName(@PathVariable String fromName){
//		return "fromName";
//	}
	
}	
  • 在WEB-INF目录下新增加web.xml,这个web.xml有两个作用:
  1. 通过ContextLoaderListener在web app启动的时候,获取contextConfigLocation配置文件的文件名applicationContext.xml,并进行Spring相关初始化工作
  2. 有任何访问,都被DispatcherServlet所拦截,这就是Spring MVC那套工作机制了。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	
	  <!--Spring配置: needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- SpringMVC配置 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/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>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>
  • 在src目录下新建applicationContext.xml文件,这是Spring的配置文件,其作用
  1. 通过注解,将com.glj.*的生命周期纳入Spring的管理
  2. ?配置数据源
  3. 扫描存放SQL语句的UserMapper.xml
  4. 扫描Mapper接口,并将其生命周期纳入Spring的管理
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
	<!-- Spring希望管理所有的业务逻辑组件,等。。。 -->
	<context:annotation-config />
	<context:component-scan base-package="com.glj">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!-- 引入数据库的配置文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- Spring用来控制业务逻辑。数据源、事务控制、aop -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="driverClass" value="${jdbc.driver}"></property>
		<property name="user" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- spring事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 开启基于注解的事务 -->
	<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
	<!--创建出SqlSessionFactory对象  -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="typeAliasesPackage" value="com.glj.pojo" />
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<property name="mapperLocations" value="classpath:com/glj/mapper/*.xml" />
	</bean>
	<!-- 扫描所有的mapper接口的实现自动注入;
		<mybatis-spring:scan base-package="com.glj.dao"/>
	 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <!-- 可以不用指定,因为MapperScannerConfigurer会自动装配
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  -->
		<property name="basePackage" value="com.glj.dao"></property>
	</bean>
</beans>
  • 在src目录下新建mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>
  • 在WEB-INF目录下新建springMVC.xml(也可以在src目录下创建,然后就可以用classpath:springMVC.xml即可)
  1. ?扫描Controller,并将其生命周期纳入Spring管理
  2. 注解驱动
  3. 静态页面,如html,css,js,images可以访问
  4. 视图定位到/WEB/INF/jsp 这个目录下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 只扫描Controller,并将其生命周期纳入Spring管理 -->
	<context:component-scan base-package="com.glj" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<context:annotation-config/>
	<!-- 注解驱动 -->
	<mvc:annotation-driven />
	<!--静态页面,如html,css,js,images可以访问   -->
	<mvc:default-servlet-handler /> 
	<!-- 视图定位 -->
	<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>
  • 在WEB-INF下创建jsp目录,并创建文件listUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${users}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

 

评论

  1. Windows Chrome 55.0.2883.87
    7 年前
    2017-10-23 9:51:56

    朋友 交换链接吗

    • 博主
      godaddy
      Windows Chrome 50.0.2661.102
      7 年前
      2017-10-25 13:41:10

      不好意思,我最近在考虑换域名了.所以会有些问题不好互链了.抱歉

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇