首页 > 代码库 > Java Web开发SpringMVC和MyBatis框架开发环境搭建和简单实用
Java Web开发SpringMVC和MyBatis框架开发环境搭建和简单实用
1、下载SpringMVC框架架包,下载地址:
点击下载
点击打开地址如图所示,点击下载即可
然后把相关的jar复制到lib下导入
2、MyBatis(3.4.2)下载
点击下载
MyBatis中文文档地址
点击查看
下载解压之后把jar复制到lib下导入,大概是这样子的
3、jdbc连接库还没有下载。。。这个是5.1.41版本的。。。
点击下载
解压之后这样子。。。
4、fastjson 阿里巴巴的json解析库
点击下载
版本是1.2.24 这个是托管到了github上面的,地址是:点击进入
5、创建WebProject
注意下一步有个选项,如果不勾选,默认是不会生成web.xml的
6、项目创建完毕,把之前的包都弄进来。。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>CoolWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>CoolWeb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- <param-value>classpath:application-context.xml</param-value> -->
<param-value>classpath:CoolWeb-servlet.xml</param-value>
</init-param><!-- classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找. -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 如果不配置servlet-mapping服务器就无法响应/请求 -->
<servlet-mapping>
<servlet-name>CoolWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
7、在src下创建CoolWeb-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: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.3.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.3.xsd">
<!-- 开启SpringMVC注解 -->
<context:component-scan base-package="com.vincent.lwx"/>
<mvc:annotation-driven/>
</beans>
8、在src下编写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: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.3.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.3.xsd">
<context:component-scan base-package="com.vincent.lwx"/>
<mvc:annotation-driven/>
<!-- User实体类 -->
<bean id="user" class="com.vincent.lwx.bean.User"/>
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- max size:10M -->
<property name="maxUploadSize" value="10485760"/>
</bean>
</beans>
User实体类要在这里注册
9、在src下编写mybatis.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<!-- 注意3306后面是数据库名称 autoReconnect自动重连-->
<property name="url" value="jdbc:mysql://localhost:3306/cool?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/vincent/lwx/dao/UserMapping.xml" />
</mappers>
</configuration>
10、log4j.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="debug">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
</Console>
<RollingFile name="RollingFile" fileName="D:logs/schoolmallapi.log"
filePattern="log/$${date:yyyy-MM}yimoServiceRun-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd ‘at‘ HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n" />
<SizeBasedTriggeringPolicy size="15MB" />
</RollingFile>
</appenders>
<loggers>
<root level="DEBUG">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</root>
</loggers>
<!-- 下面是打印 mybatis语句的配置 -->
<logger name="com.ibatis" additivity="true">
<level value="DEBUG" />
</logger>
<logger name="java.sql.Connection" additivity="true">
<level value="DEBUG" />
</logger>
<logger name="java.sql.Statement" additivity="true">
<level value="DEBUG" />
</logger>
<logger name="java.sql.PreparedStatement" additivity="true">
<level value="DEBUG" />
</logger>
<logger name="java.sql.ResultSet" additivity="true">
<level value="DEBUG" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="CONSOLE" />
<!-- <appender-ref ref="FILE" /> -->
<!-- <appender-ref ref="framework" /> -->
</root>
</configuration>
这个配置貌似有点问题,虽然不影响使用,不过我也没有去深入研究还,最近还要准备面试Android哎。。。
现在差不多是这样子咯
11、环境搭建差不多了,现在开始撸代码,写一个注册的动能吧
简历一个实体类User.java
package com.vincent.lwx.bean;
import java.io.Serializable;
/**
* @Title: User.java
* @Package com.vincent.lwx.bean
* @Description: TODO(用一句话描述该文件做什么)
* @author Vincent
* @date 2017年3月3日 下午6:36:58
* @version V1.0
*/
public class User implements Serializable{
/**
* 序列化id
*/
private static final long serialVersionUID = -6375697395831845246L;
/**
* 用户id
*/
private String user_id;
/**
* 用户手机号码
*/
private String phone;
/**
* 密码
*/
private String password;
/**
* 用户名
*/
private String nickname;
/**
* 用户头像地址
*/
private String head;
/**
* 性别
*/
private String sex;
/**
* 生日
*/
private String birthday;
/**
* 生活状态(发表的说说)
*/
private String live_status;
public String getUser_id() {
return user_id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getLive_status() {
return live_status;
}
public void setLive_status(String live_status) {
this.live_status = live_status;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "User [user_id=" + user_id + ", nickname=" + nickname + ", phone=" + phone + ", password=" + password
+ ", head=" + head + ", sex=" + sex + ", birthday=" + birthday + ", live_status=" + live_status
+ "]";
}
}
编写MyBatis的实体类映射xml文件,就写个UserMapping.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.vincent.lwx.mapping.UserMapping">
<!-- 根据手机号码查询用户是否存在 -->
<select id="selectUser" parameterType="String" resultType="com.vincent.lwx.bean.User">
select * from user where phone = #{phone}
</select>
</mapper>
我这里只写了一个,别的还没写,注册之前先查询一下手机号码是否已注册。。
注意这里的id 不能重复,要具有唯一性。parameterType是传入的参数类型,这里是String类型的phone,如果要传入多个参数可以使用User对象,或者Map,resultType返回结果类型,我这里是直接返回一个User对象,之前用jdbc直接连接数据库,返回的东西还要手动封装,这个快多了。。。
创建MyBatisUtils.java类,用来从数据库获取SqlSession对象的,SqlSession执行sql语句,和jdbc的Statement对象差不多感觉。。。也可能我的感觉是错的,哈哈,还没看源码。。。
package com.vincent.lwx.db;
import java.io.IOException;
import java.io.Reader;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.vincent.lwx.util.EatTimerTask;
/**
* @Title: MyBatisUtils.java
* @Package com.vincent.julie.config
* @Description: TODO(????仰?????????????)
* @author Vincent
* @date 2017??2??18?? ????12:05:35
* @version V1.0
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
private static SqlSession sqlSession;
private static long timeInterval;//上一次运行的时间
private static TimerTask task =null;
static {
String resource = "mybatis.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
System.out.println(e.getMessage());
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
/**
*
* @return
*/
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
/**
* ???sqlSession????
* @return
*/
public static SqlSession getSqlSession(){
if (task != null){
task.cancel(); //将原任务从队列中移除
}
task = new EatTimerTask();
timeInterval = System.currentTimeMillis();
//间隔??1小时
long period = 1000 * 60 * 60;
//测试时间每分钟一??
//period = 1000 * 60;
Timer timer = new Timer();
timer.schedule(task, timeInterval, period);
if(sqlSessionFactory == null){
sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
}
sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
这里有个计时器,我发现Tomcat运行一段时间之后(听说是10小时)如果没有连接数据库,会出现异常。。
好,现在来写UserController.java类,处理客户端的请求
package com.vincent.lwx.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.vincent.lwx.bean.ServiceStatus;
import com.vincent.lwx.bean.User;
import com.vincent.lwx.db.MyBatisUtils;
import com.vincent.lwx.util.ResponseUtils;
/**
* @Title: UserControl.java
* @Package com.vincent.lwx.mapping
* @Description: TODO(????仰?????????????)
* @author Vincent
* @date 2017??3??3?? ????6:28:37
* @version V1.0
*/
@Controller
public class UserController {
private static final Logger logger = LogManager.getLogger(UserController.class);
/**
* 注册
* @param phone
* @param password
* @param request
* @param response
*/
@RequestMapping(value = http://www.mamicode.com/"register", method = RequestMethod.POST)
public void registerUser(@RequestParam("phone")String phone,@RequestParam("password")String password,HttpServletRequest request,HttpServletResponse response){
if(hasUserPhone(phone)){
//用户已存在,无须再次注册
ResponseUtils.renderJsonDataFail(response, ServiceStatus.RUNTIME_EXCEPTION, "该号码已被注册");
return;
}
}
/**
* 根据手机号码查询用户是否存在
* @param phone
* @return
*/
public boolean hasUserPhone(String phone){
/**sql 语句 完整的包名类名和方法id,*/
String sql = "com.vincent.lwx.mapping.UserMapping.selectUser";
SqlSession session = MyBatisUtils.getSqlSession();
/**返回一个User对象*/
User user = session.selectOne(sql, phone);
if(user!=null){
//用户已存在
return true;
}else{
//用户不存在
return false;
}
}
}
10、最后一步,让Tomcat跑起来,好吧,下载Tomcat、点击下载
这个版本是Tomcat9.0的
Tomcat8.5 点击下载
Tomcat8.5 点击下载
Tomcat7.0 点击下载
如果不会部署的话可以看这里的 部署Tomcat
11、东西写完了不叫最后一步,最后一步应该自己测试一下,google浏览器自带Postman检查一下接口的正确性
因为我的数据库我已经自己注册了,所以提示是正确的,另外附上user表的sql语句:
2017年3月3日18:31:53
CREATE DETABASE cool;
//创建数据库并指定字符编码集
CREATE DATABASE cool DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
//创建表
create table user(
user_id int(10) not null primary key auto_increment,
phone varchar(11) not null,
password varchar(16) not null,
nickname varchar(36),
head varchar(50),
sex varchar(3),
birthday varchar(10) default ‘1992-01-01‘,
live_status varchar(255)
)engine = InnoDB default charset=utf8;
//限制最小id=10000
alter table user AUTO_INCREMENT=10000;设置已经存在的表的默认值
//限制手机号码唯一性
alter table user add unique(phone); 字段值唯一性约束
insert into user(phone,password) values(
‘18696855784‘,
‘555555‘);
CoolWeb源码点击下载
Github地址 进入
2017年3月3日23:52:34
Java Web开发SpringMVC和MyBatis框架开发环境搭建和简单实用