springMVC注解方式+easyUI+MYSQL配置实例

时间:2023-03-08 18:01:38
springMVC注解方式+easyUI+MYSQL配置实例

  刚接触springMVC,使用的注解方式,也在学习阶段,所以把自己学习到的记下来。本文利用springMVC从数据库读取用户信息为例,分享一下。

1.准备相关架包及资源。因为使用springMVC+easyUI+MYSQL的方式构建项目,所以要下载spring的jar包、easyUI资源、mysql包。

2.新建空项目名称为test,将架包导入项目。即把下载来的spring-framework-3.1.1.RELEASE/libs中的对应jar包复制到项目的/WebRoot/WEB-INF/lib目录中。这里只用到如下图中这些包。为了方便后继开发,也可以将下载来的所有jar包都导入项目。

springMVC注解方式+easyUI+MYSQL配置实例

3.在/WebRoot/WEB-INF中添加web.xml配置文件,文件内容如下:

 <?xml version="1.0" encoding="UTF-8"?>

 <web-app version="2.5" 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"> <display-name>Spring3MVC</display-name> <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

其中,classpath:applicationContext.xml指定具体配置文件为applicationContext.xml。

<servlet-mapping>用来配置拦截哪些请求到servlet,这里表示拦截所有.do结尾的请求。

4.在/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: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"
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/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
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.0.xsd
">
<!-- 加入数据库连接配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.mvc" /> <!--
配置数据源 destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<!--连接池中保留的最小连接数。 -->
<property name="minPoolSize">
<value>3</value>
</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize">
<value>10</value>
</property>
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize">
<value>5</value>
</property>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">
<value>60</value>
</property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement">
<value>5</value>
</property>
<!--
JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 058
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
-->
<property name="maxStatements">
<value>0</value>
</property>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod">
<value>60</value>
</property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts">
<value>10</value>
</property>
<!--
获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 071
获取连接失败后该数据源将申明已断开并永久关闭。Default: false
-->
<property name="breakAfterAcquireFailure">
<value>true</value>
</property>
<!--
因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 076
等方法来提升连接测试的性能。Default: false
-->
<property name="testConnectionOnCheckout">
<value>false</value>
</property>
</bean>
<!-- 配置Jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

其中,<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />开启注解功能,会将带有注解标签的类自动注入。

<context:component-scan base-package="com.mvc" />开启类的注解支持,让springMVC扫描类,将标有注解的类自动转化为bean,完成注入。

<bean id="viewResolver">用来配置视图解析器,指定视图文件所在的文件夹,将ModelAndView及字符串解析为具体的页面。

springMVC注解配置就只有以上三个部分,文件其余部分,如<bean id="dataSource" >用来配置jdbc方式的数据源的连接。

5.在/src中添加jdbc.properties配置文件,用来配置jdbc连接,文件内容如下:

 jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost/testdb
jdbc.username=root
jdbc.password=123123

6.在/src中添加com.mvc.po包,在包中添加一个User类,用于存放用户实体,类中内容如下:

 package com.mvc.po;

 public class User {
private int id;
private String name;
private String password;
private int age; public User() { }
public User(int id, String name, String password, int age) {
this.id = id;
this.name = name;
this.password = password;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

7.在/src中添加com.mvc.controller包,在包中添加一个UserController类,类中内容如下:

 package com.mvc.controller;

 import java.util.List;

 import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON;
import com.mvc.po.User;
import com.mvc.service.UserService; @Controller
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "/query.do")
public @ResponseBody String query() {
List<User> list = this.userService.query();
return JSON.toJSONString(list);
}
}

其中,@Controller 注解用于表示控制层,把该class指定为controller,方法上的@RequestMapping 注解的value值指定该方法所映射的请求路径。属性加上@Autowired 注解可以免去getter()、setter()方法,spring会自动注入。@Responsebody 注解指定该方法的返回结果直接写入HTTP response body中。这里以json的格式返回查询结果,所以需要使用@Responsebody 注解。

8.在/src中添加com.mvc.service包,在包中添加一个接口类UserService和实现类UserServiceImpl,类中内容如下:

 package com.mvc.service;

 import java.util.List;
import com.mvc.po.User; public interface UserService {
List<User> query();
}
 package com.mvc.service;

 import java.util.List;

 import com.mvc.dao.UserDAO;
import com.mvc.po.User;
import com.mvc.service.UserService; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserDAO userDAO; public List<User> query() {
return this.userDAO.query();
}
}

其中,@Service 注解用于表示业务层。

9.在/src中添加com.mvc.dao包,在包中添加一个接口类UserDAO和实现类UserDAOImpl,类中内容如下:

 package com.mvc.dao;

 import java.util.List;
import com.mvc.po.User; public interface UserDAO {
List<User> query();
}
 package com.mvc.dao;

 import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException; import com.mvc.dao.UserDAO;
import com.mvc.po.User; import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; @Repository
public class UserDAOImpl implements UserDAO { @Autowired
private JdbcTemplate jdbcTemplate; public List<User> query() {
return this.jdbcTemplate.query("select * from student",
new RowMapper<User>() {
public User mapRow(ResultSet rs, int arg1)
throws SQLException {
return new User(rs.getInt("sId"),
rs.getString("sName"), rs.getString("sPwd"), rs
.getInt("sAge"));
}
});
}
}

其中,@Repository 注解用于表示数据访问层。

10.启动部署项目后,直接键入地址http://127.0.0.1/test/query.do就可以查看数据库返回的json格式的数据,如下图所示。其中,127.0.0.1表示本机地址,test是项目名称,query.do是方法的映射路径,就是我们在Controller中对应方法上RequestMapping的值。因为这里还没有设置前台页面,所以,这个访问方式就是直接调用的action,这个方式在实际应用中调试特定action的时候还蛮方便好用的。

springMVC注解方式+easyUI+MYSQL配置实例

到这一步,springMVC的配置已经完成,下面是在此基础上加入easyUI。

11.在/WebRoot下添加前台页面index.jsp,页面内容如下:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SpringMVC demo</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
<script type="text/javascript" src="easyui/jquery.min.js"></script>
<script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script>
</head> <body>
<table id="tb1">
</table> <script type="text/javascript">
$(document).ready(function() {
$('#tb1').datagrid({
url : 'query.do',
remoteSort : false,
custom : true,
iconCls : 'icon-edit',
nowrap : true,
striped : true,
collapsible : true,
pagination : true,
rownumbers : true,
fitColumns : true,
fit : true,
title : 'DataGrid with Info',
pageSize : 15,
pageList : [ 5, 15, 20, 30, 100 ],
columns : [ [ {
field : 'id',
title : '用户id',
hidden : true
}, {
field : 'name',
title : '用户姓名',
align : 'center'
}, {
field : 'password',
title : '密码',
align : 'center'
}, {
field : 'age',
title : '年龄',
align : 'center'
} ] ]
});
});
</script>
</body>
</html>

这个页面包含2个部分。第一部分是将下载来的easyUI资源引入到页面,如下。

 <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
<script type="text/javascript" src="easyui/jquery.min.js"></script>
<script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script>

第二部分,就是将数据绑定到datagrid对应的列上面,即参数columns部分。

效果如下:

springMVC注解方式+easyUI+MYSQL配置实例

  这样springMVC注解方式+easyUI+MYSQL配置实例就完成了。之后就很方便了,实际项目中只要根据需求,在Controller、Service、Repository增加对应的方法就行了,而页面只要在网上找easyUI的demo,里面有各种控件的样式及参数设置,只要根据自己项目需要设置并绑定下数据就ok了。