zoukankan      html  css  js  c++  java
  • 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包都导入项目。

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

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 
     3 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     6 
     7     <display-name>Spring3MVC</display-name>
     8 
     9     <servlet>
    10         <servlet-name>spring</servlet-name>
    11         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    12         <init-param>
    13             <param-name>contextConfigLocation</param-name>
    14             <param-value>classpath:applicationContext.xml</param-value>
    15         </init-param>
    16     </servlet>
    17 
    18     <servlet-mapping>
    19         <servlet-name>spring</servlet-name>
    20         <url-pattern>*.do</url-pattern>
    21     </servlet-mapping>
    22 
    23     <welcome-file-list>
    24         <welcome-file>index.jsp</welcome-file>
    25     </welcome-file-list>
    26 </web-app>

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

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

    4.在/src中添加applicationContext.xml配置文件,文件内容如下:

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <beans xmlns="http://www.springframework.org/schema/beans"
      3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
      4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
      5     xmlns:tx="http://www.springframework.org/schema/tx"
      6     xmlns:mvc="http://www.springframework.org/schema/mvc"
      7     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      8         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      9         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     10         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     11         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
     12     ">
     13     <!--    加入数据库连接配置文件    -->
     14     <context:property-placeholder location="classpath:jdbc.properties" />
     15     <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
     16     <context:component-scan base-package="com.mvc" />
     17     
     18     <!--
     19         配置数据源 destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
     20     -->
     21     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
     22         destroy-method="close">
     23         <property name="driverClass">
     24             <value>${jdbc.driverClassName}</value>
     25         </property>
     26         <property name="jdbcUrl">
     27             <value>${jdbc.url}</value>
     28         </property>
     29         <property name="user">
     30             <value>${jdbc.username}</value>
     31         </property>
     32         <property name="password">
     33             <value>${jdbc.password}</value>
     34         </property>
     35         <!--连接池中保留的最小连接数。 -->
     36         <property name="minPoolSize">
     37             <value>3</value>
     38         </property>
     39         <!--连接池中保留的最大连接数。Default: 15 -->
     40         <property name="maxPoolSize">
     41             <value>10</value>
     42         </property>
     43         <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
     44         <property name="initialPoolSize">
     45             <value>5</value>
     46         </property>
     47         <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
     48         <property name="maxIdleTime">
     49             <value>60</value>
     50         </property>
     51         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
     52         <property name="acquireIncrement">
     53             <value>5</value>
     54         </property>
     55         <!--
     56             JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
     57             属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 058
     58             如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
     59         -->
     60         <property name="maxStatements">
     61             <value>0</value>
     62         </property>
     63         <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
     64         <property name="idleConnectionTestPeriod">
     65             <value>60</value>
     66         </property>
     67         <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
     68         <property name="acquireRetryAttempts">
     69             <value>10</value>
     70         </property>
     71         <!--
     72             获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
     73             保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 071
     74             获取连接失败后该数据源将申明已断开并永久关闭。Default: false
     75         -->
     76         <property name="breakAfterAcquireFailure">
     77             <value>true</value>
     78         </property>
     79         <!--
     80             因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
     81             时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 076
     82             等方法来提升连接测试的性能。Default: false
     83         -->
     84         <property name="testConnectionOnCheckout">
     85             <value>false</value>
     86         </property>
     87     </bean>
     88     <!-- 配置Jdbc模板 -->
     89     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     90         <property name="dataSource" ref="dataSource" />
     91     </bean>    
     92     <!-- 配置事务管理器 -->
     93      <bean id="transactionManager"
     94         class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
     95         p:dataSource-ref="dataSource" />
     96 
     97     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
     98     <bean
     99         class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    100 
    101     <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
    102     <bean id="viewResolver"
    103         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    104         <property name="prefix" value="/" />
    105         <property name="suffix" value=".jsp" />
    106     </bean>    
    107 </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连接,文件内容如下:

    1 jdbc.driverClassName=com.mysql.jdbc.Driver
    2 jdbc.url=jdbc:mysql://localhost/testdb
    3 jdbc.username=root
    4 jdbc.password=123123

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

     1 package com.mvc.po;
     2 
     3 public class User {
     4     private int id;
     5     private String name;
     6     private String password;
     7     private int age;
     8 
     9     public User() {
    10 
    11     }
    12     public User(int id, String name, String password, int age) {
    13         this.id = id;
    14         this.name = name;
    15         this.password = password;
    16         this.age = age;
    17     }
    18     public int getId() {
    19         return id;
    20     }
    21     public void setId(int id) {
    22         this.id = id;
    23     }
    24     public String getName() {
    25         return name;
    26     }
    27     public void setName(String name) {
    28         this.name = name;
    29     }
    30     public String getPassword() {
    31         return password;
    32     }
    33     public void setPassword(String password) {
    34         this.password = password;
    35     }
    36     public int getAge() {
    37         return age;
    38     }
    39     public void setAge(int age) {
    40         this.age = age;
    41     }
    42 }

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

     1 package com.mvc.controller;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.stereotype.Controller;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.ResponseBody;
     9 
    10 import com.alibaba.fastjson.JSON;
    11 import com.mvc.po.User;
    12 import com.mvc.service.UserService;
    13 
    14 @Controller
    15 public class UserController {
    16 
    17     @Autowired
    18     private UserService userService;
    19 
    20     @RequestMapping(value = "/query.do")
    21     public @ResponseBody String query() {
    22         List<User> list = this.userService.query();
    23         return JSON.toJSONString(list);
    24     }
    25 }

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

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

    1 package com.mvc.service;
    2 
    3 import java.util.List;
    4 import com.mvc.po.User;
    5 
    6 public interface UserService {
    7     List<User> query();
    8 }
     1 package com.mvc.service;
     2 
     3 import java.util.List;
     4 
     5 import com.mvc.dao.UserDAO;
     6 import com.mvc.po.User;
     7 import com.mvc.service.UserService;
     8 
     9 import org.springframework.beans.factory.annotation.Autowired;
    10 import org.springframework.stereotype.Service;
    11 
    12 @Service
    13 public class UserServiceImpl implements UserService {
    14 
    15     @Autowired
    16     private UserDAO userDAO;
    17 
    18     public List<User> query() {
    19         return this.userDAO.query();
    20     }
    21 }

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

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

    1 package com.mvc.dao;
    2 
    3 import java.util.List;
    4 import com.mvc.po.User;
    5 
    6 public interface UserDAO {
    7     List<User> query();    
    8 }
     1 package com.mvc.dao;
     2 
     3 import java.util.List;
     4 import java.sql.ResultSet;
     5 import java.sql.SQLException;
     6 
     7 import com.mvc.dao.UserDAO;
     8 import com.mvc.po.User;
     9 
    10 import org.springframework.stereotype.Repository;
    11 import org.springframework.beans.factory.annotation.Autowired;
    12 import org.springframework.jdbc.core.JdbcTemplate;
    13 import org.springframework.jdbc.core.RowMapper;
    14 
    15 @Repository
    16 public class UserDAOImpl implements UserDAO {
    17 
    18     @Autowired
    19     private JdbcTemplate jdbcTemplate;
    20 
    21     public List<User> query() {
    22         return this.jdbcTemplate.query("select * from student",
    23                 new RowMapper<User>() {
    24                     public User mapRow(ResultSet rs, int arg1)
    25                             throws SQLException {
    26                         return new User(rs.getInt("sId"),
    27                                 rs.getString("sName"), rs.getString("sPwd"), rs
    28                                         .getInt("sAge"));
    29                     }
    30                 });
    31     }
    32 }

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

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

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

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

     1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     2 
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5 <head>
     6 <title>SpringMVC demo</title>
     7 <meta http-equiv="pragma" content="no-cache">
     8 <meta http-equiv="cache-control" content="no-cache">
     9 <meta http-equiv="expires" content="0">
    10 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    11 <meta http-equiv="description" content="This is my page">
    12 
    13 <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
    14 <link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
    15 <script type="text/javascript" src="easyui/jquery.min.js"></script>
    16 <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>
    17 <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script>
    18 </head>
    19 
    20 <body>
    21     <table id="tb1">
    22     </table>
    23 
    24     <script type="text/javascript">
    25         $(document).ready(function() {
    26             $('#tb1').datagrid({
    27                 url : 'query.do',
    28                 remoteSort : false,
    29                 custom : true,
    30                 iconCls : 'icon-edit',
    31                 nowrap : true,
    32                 striped : true,
    33                 collapsible : true,
    34                 pagination : true,
    35                 rownumbers : true,
    36                 fitColumns : true,
    37                 fit : true,
    38                 title : 'DataGrid with Info',
    39                 pageSize : 15,
    40                 pageList : [ 5, 15, 20, 30, 100 ],
    41                 columns : [ [ {
    42                     field : 'id',
    43                     title : '用户id',
    44                     hidden : true
    45                 }, {
    46                     field : 'name',
    47                     title : '用户姓名',
    48                     align : 'center'
    49                 }, {
    50                     field : 'password',
    51                     title : '密码',
    52                     align : 'center'
    53                 }, {
    54                     field : 'age',
    55                     title : '年龄',
    56                     align : 'center'
    57                 } ] ]
    58             });
    59         });
    60     </script>
    61 </body>
    62 </html>

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

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

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

    效果如下:

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

  • 相关阅读:
    bWAPP练习--injection篇SQL Injection (GET/Search)
    利用gmpy2破解rsa
    Linux 下安装gmpy2
    Linux下安装scapy-python3
    python升级带来的yum异常:File "/usr/bin/yum", line 30
    CentOS7 安装Python3.6.4
    bWAPP练习--injection篇之HTML Injection
    kali2.0安装VMware Tools
    Lombok插件看法浅谈
    记一次Java动态代理实践【首发自高可用架构公众号】
  • 原文地址:https://www.cnblogs.com/pcheng/p/4624942.html
Copyright © 2011-2022 走看看