哈哈,第一篇blog.
从没用过maven的jar包管理,项目要上马了,学着网上的很多demo,自己模仿着做了一个,记录下来,和大家分享。
比较着重于实现,细节原理好多不懂。
准备工作:
jdk:1.6.0_18
tomcat:6.0.18
maven3.1.1
spring:3.2.4
mybatis:3.2.3
IDE: eclipse J2EE kepler
mysql:5.1.53(msi):
用到的User表结构:
Create TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
1.用官网下载的最新maven替代eclipse自带的maven
并指定maven的配置文件,这里我没有改变maven本地仓库的位置,因为我在setting.xml中用的就是这个地址,网上看到很多人都自定义本地仓库的位置。
2.新建maven project,artifactId选择webapp,点击next, 名称就取缩写MSM,子项目叫example,点击Finish.
3.新建好的project,不明白为什么已经指定用了最新版的maven,建出来的还是jre还是1.5的
4.改jre,加source folder
build path里修改test的compile目标路径
5.右键项目名称,选择末项Properties,进入面板选择Project Facets,把java版本改成1.6
记得改变之后点击apply,否则不生效。
因为jdk是1.6的,所以这里Dynamic Web Module可以选择到2.5。
如果碰到如下报错:
cannot change version of project facet dyname web module to 2.5
网上提供了两步解决办法:
1) 把java compile改成1.6,看看行不行,不行的话再走第2步.
2).进入example/.settings/org.eclipse.wst.common.project.facet.core.xml文件
<installed facet="jst.web" version="2.3"/>
把这里的version属性改成2.5,重启eclipse,简单粗暴。
现在再进入Project Facets界面,可以看到Dynamic Web Module=2.5了
6.右键项目名称,选择末项Properties,进入面板选择web deployment assembly.
因为项目部署时,不需要加入test,所以把和test有关的部署路径remove,如下图.
wtp(web tool platform)不懂是什么,学习中.
更改完后,记得点击apply.
7.添加jar包
双击项目下pom.xml,选择Denpendcies选项卡,点击add按钮搜索
我搜索时碰到搜索结果为0的情况,在网上搜索了一下解决办法,
这里还需要做些maven的设置
1).把download repository index updates on startup 勾选上,重启eclipse
2).window->show view :maven repositories,右键Global Repositories下的central
勾选Full Index Enabled,然后再选择Rebuild Index
再搜索spring-web应该就能看到搜索结果了.
搜索:
spring-web,spring-tx,spring-webmvc,,spring-jdbc获取当下最新3.2.4的jar包
需要定时器的可再搜索quartz, spring-context-support获取jar包
mybatis(3.2.3),mybatis-spring(1.2.1)
log4j, log4j-slf4j(转换用的实现类)
完成后如下图:
8.构建spring mvc
web.xml,最simple配置,这里不考虑img,css,js等静态资源过滤了.
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.5" >
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置spring mvc: dispatcher-servlet.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.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"
>
<context:annotation-config />
<context:component-scan base-package="example" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<!-- Support annotation -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
复制jdbc.proerties到src/main/resources/下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/schemaName?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
applicationContext.xml下有两个配置是spring和mybatis集成用的
1) 其中sqlSessionFactoryBean
sqlSessionFactoryBean下的typeAliasesPackage属性就是提供一个命名空间,比如我这里所有和数据库表中属性对应的实体类全在example.model类下,那么定义
<property name="typeAliasesPackage" value="example.model" />
我们在**Mapper.xml里配置各种方法返回值的时候就可以直接用
resultType="User"
而不是写类的全名:
resultType="example.model.User"
2)MapperScannerConfigurer扫描我们指定的包,自动创建映射器
<pre name="code" class="html"><pre name="code" class="java"><property name="basePackage" value="example.mapper" />
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource" destroy-method="forceCloseAll">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="example.model" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="example.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
下面是文件目录:注意这里我设置Mapper接口类和映射器配置xml文件同名且在同一目录下.就无需在Mybatis的配置文件Configuration.xml中通过mapper标签来指定映射器配置文件了.
例如原来是需要在Configuration.xml中指定的
<mappers>
<mapper resource="example/mapper/UserMapper.xml" />
</mappers>
因为现在把datasource配置在applicationContext.xml里了,mapper标签也不需要了,所以Configuration.xml这个文件我们暂时不需要了.
实体:User.java
package example.model;
public class User {
private int id;
private String userName;
private String userAge;
private String userAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
操作:userMapper.java
这里我把select的操作配置在了相应的xml文件里,
package example.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import example.model.User;
@Repository
public interface UserMapper {
public User selectUserById(int id);
@Insert("insert into user (userName, userAge, userAddress) values (#{userName},#{userAge},#{userAddress})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public void insertUser(User user);
@Delete("delete from user where id = #{id}")
public void deleteUser(int id);
@Update("update user set userName = #{userName}, userAge = #{userAge}, userAddress = #{userAddress} where id = #{id}")
public void updateUser(User user);
}
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="example.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
UserServiceImpl.java,这里就做个简单的查询操作
package example.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import example.mapper.UserMapper;
import example.model.User;
import example.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUser(int id) {
User user = userMapper.selectUserById(id);
return user;
}
}
UserController.java,给JSP返回数据
package example.controller;
import java.util.HashMap;
import java.util.Map;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import example.model.User;
import example.service.UserService;
@Controller
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public ModelAndView getUserDetail(@PathVariable("userId") int userId) {
User user = userService.getUser(userId);
ModelAndView mv = new ModelAndView();
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("user", user);
mv.addAllObjects(modelMap);
mv.setViewName("user_detail");
return mv;
}
}