spring+springmvc+mbatis+maven+velocity构建javaEE项目
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring+springmvc+mbatis+maven+velocity构建javaEE项目相关的知识,希望对你有一定的参考价值。
开发工具eclipse(Mars) jdk版本1.7 maven版本:3.2.1
步骤:
1.1创建maven项目
1.2.红色框中的选中
1.3.由于是web项目,所以选择war。其他的参考maven的知识详解
1.4.pom.xml报了这个错,web.xml is missing and <failOnMissingWebXml> is set to true
这是在项目中缺少web.xml文件
添加web.xml即可
项目结构如图
****注:看不懂的同学可以看看maven的相关知识
1.5.接下来是配置pom文件
详细介绍在pom文件里面
2.1.spring集成mybatis
在web.xml文件中
配置spring监听器和编码过滤器
2.2.spring集成mybatis的配置文件地址
2.3编写相应的包
2.4.相应的类讲解
2.4.1.User
package com.ssm.entities;
public class User {
private Integer id;
private String userName;
private String password;
private Integer age;
}
**相应的get set省略
2.4.2 UserMapper
package com.ssm.mapper;
import java.util.List;
import com.ssm.entities.User;
public interface UserMapper {
int deleteById(Integer id);
int insert(User user);
User getUserById(Integer id);
int updateById(User user);
List<User> getUserList();
}
2.4.3.UserService
package com.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssm.entities.User;
import com.ssm.mapper.UserMapper;
@Transactional
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Integer id){
return userMapper.getUserById(id);
}
public List<User> getUserList(){
return userMapper.getUserList();
}
public int deleteById(Integer id){
return userMapper.deleteById(id);
}
public int insert(User user){
return userMapper.insert(user);
}
public int updateById(User user){
return userMapper.updateById(user);
}
}
2.4.4 UserController
package com.ssm.controller;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ssm.annotations.UserAnnotation;
import com.ssm.entities.User;
import com.ssm.enums.ExecuteType;
import com.ssm.service.UserService;
@RequestMapping("/user")
@Controller
public class UserController {
public static Logger log=LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@UserAnnotation(operatorName="ch")
@RequestMapping("/showAllUsers")
public ModelAndView getAllUser(Integer id){
List<User> users=userService.getUserList();
ModelAndView mv=new ModelAndView("showUser");
mv.addObject("users", users);
System.out.println(users);
log.info("显示所有用户");
return mv;
}
/**
* initAdd
* @param i
* @return
*/
@UserAnnotation(operatorName="ch")
@RequestMapping("/initAdd")
public ModelAndView initAdd(){
ModelAndView mv=new ModelAndView("initAdd");
log.info("初始化用户");
return mv;
}
@RequestMapping("/save")
public String insert(User user){
if(user!=null && user.getId()!=null){
userService.updateById(user);
}else{
userService.insert(user);
}
log.info("保存用户");
return "redirect:/user/showAllUsers";
}
@UserAnnotation(operatorName="ch")
@RequestMapping("/initUpdate")
public String initUpdate(Integer id,Map<String, Object> map){
User u=userService.getUserById(id);
map.put("u", u);
log.info("初始化更新");
return "initAdd";
}
//删除
@UserAnnotation(operatorName="ch",executeType=ExecuteType.DELETE)
@RequestMapping("/delete")
public String delete(Integer id){
userService.deleteById(id);
log.info("删除用户");
return "redirect:/user/showAllUsers";
}
//ajax删除用户
@RequestMapping("deleteUserById")
@UserAnnotation(operatorName="ch",executeType=ExecuteType.DELETE)
@ResponseBody
public Object deleteUserById(Integer id){
int count=userService.deleteById(id);
log.info("使用Ajax删除用户");
if(count>0){
return "success";
}
return "fail";
}
}
2.5 配置spring-mybatis.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">
<!-- 自动扫描 -->
<context:component-scan base-package="com.ssm" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${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>
<!-- spring和MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.ssm.entities"></property>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 下面一句话也可以 -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
2.6编写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.ssm.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base" >
id, user_name, password, age
</sql>
<select id="getUserById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="getUserList" resultMap="BaseResultMap" >
select
<include refid="Base" />
from user
</select>
<delete id="deleteById" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="User" >
insert into user ( user_name, password,
age)
values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<update id="updateById" parameterType="User" >
update user
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id=#{id,jdbcType=INTEGER}
</update>
</mapper>
2.7数据库的设计
2.8springmvc的配置
2.8.1 web.xml文件中加入springmvc的配置文件
<!-- Spring MVC DispatcherServlet -->
<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>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
2.8.2配置springmvc文件
<?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">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.ssm.controller" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
${pageContext.request.contextPath}
可以替换成${rc.contextPath}
<property name="requestContextAttribute" value="rc" />
</bean> -->
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 定义velocity视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="prefix" value="" />
<property name="suffix" value=".html" />
<!-- <property name="exposeSpringMacroHelpers" value="true" /> -->
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="dateToolAttribute" value="dateTool" />
<property name="numberToolAttribute" value="numberTool" />
<!-- 下面一句话设置contextPath
${pageContext.request.contextPath}
可换成${rc.contextPath} -->
<property name="requestContextAttribute" value="rc"></property>
</bean>
<!-- 配置velocity的配置信息 -->
<bean class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
</props>
</property>
<property name="resourceLoaderPath" value="/WEB-INF/templates"></property>
</bean>
</beans>
3.1编写页面
1.index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="user/showAllUsers">
<input type="submit" value="Submit" />
</form>
</body>
</html>
2.showUser.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${rc.contextPath}/extjs/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var url=this.href;
var $tr=$(this).parent().parent();
var args={"time":new Date()};
var flag=confirm("确定要删除吗?");
if(flag){
$.post(url,args,function(data){
if(data=="success"){
alert("删除成功");
$tr.remove();
}else{
alert("删除失败");
}
});
}
return false;
});
})
</script>
</head>
<body>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>UserName</th>
<th>Password</th>
<th>Age</th>
<th>Delete</th>
<th>Update</th>
</tr>
#foreach($u in $users)
<tr>
<td>$!u.id </td>
<td>$!u.userName </td>
<td>$!u.password </td>
<td>$!u.age </td>
<td><a href=‘${rc.contextPath}/user/delete?id=$u.id+‘ confirm("确定要删除吗?")‘>Delete </a></td>
<!-- 使用ajax提交 -->
<!-- <td><a href="deleteUserById?id=$u.id" class="delete">Delete</a></td> -->
<td><a href="${rc.contextPath}/user/initUpdate?id=$u.id">Update</a></td>
</tr>
#end
</table>
<a href="${rc.contextPath}/user/initAdd">Add</a>
</body>
</html>
3.initAdd.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${rc.contextPath}/user/save" method="post">
<input type="hidden" name="id" value="$!u.id ">
UserName:<input type="text" name="userName" value="$!u.userName"/><br>
Password:<input type="text" name="password" value="$!u.password"/><br>
Age:<input type="text" name="age" value="$!u.age"/><br>
<input type="submit" value="Submit"/><br>
</form>
</body>
</html>
运行测试即可(经本人测试可行)
有问题可以发邮件[email protected]
第一次写博客,谢谢捧场
以上是关于spring+springmvc+mbatis+maven+velocity构建javaEE项目的主要内容,如果未能解决你的问题,请参考以下文章