前言
上一次复习搭建了SpringMVC+Mybatis,这次搭建一下SpringMVC,采用的是SpringJDBC,没有采用任何其他的ORM框架,SpringMVC提供了一整套的WEB框架,所以如果想搭建纯的SpringMVC的话,而且不必映入别的任何框架,SpringMVC都给我们提供了,下面试Spring + SpringMVC的详细搭建过程。
项目包含:数据库mysql(其实那个数据库都无所谓),连接池采用的是c3p0。
1、创建数据表
数据表很简单,user_info
2、搭建Maven项目
Maven项目搭建一笔带过(前面有介绍),其搭建后的webapp结构项目如下:
3、配置Maven的pom.xml文件
导入所需的spring,以及数据源,spring-mvc,json等依赖。
pom.xml
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.andy.springmvc</groupId>
- <artifactId>springmvc_demo</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>springmvc_demo Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <spring.version>4.1.4.RELEASE</spring.version>
- <jackson.version>2.5.0</jackson.version>
- </properties>
- <dependencies>
- <!-- junit -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <!-- spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- <!-- log4j -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- <!-- mysql连接 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.34</version>
- </dependency>
- <!-- c3p0数据源 -->
- <dependency>
- <groupId>com.mchange</groupId>
- <artifactId>c3p0</artifactId>
- <version>0.9.5-pre10</version>
- </dependency>
- <!-- json -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.3</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <!-- servlet -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>3.0-alpha-1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <!-- 文件上传 -->
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.2.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>springmvc_demo</finalName>
- <plugins>
- <!-- Run the JUnit unit tests in an isolated classloader -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.4.2</version>
- <configuration>
- <skipTests>true</skipTests>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-war-plugin</artifactId>
- <version>2.3</version>
- <configuration>
- <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
- </configuration>
- </plugin>
- <!-- generate java doc -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9.1</version>
- <configuration>
- <javadocDirectory>target/javadoc</javadocDirectory>
- <reportOutputDirectory>target/javadoc</reportOutputDirectory>
- <charset>UTF-8</charset>
- <encoding>UTF-8</encoding>
- <docencoding>UTF-8</docencoding>
- <show>private</show>
- </configuration>
- </plugin>
- <!-- 部署至本机 -->
- <plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>1.0</version>
- <configuration>
- <container>
- <containerId>tomcat6x</containerId>
- <home>D:\WebServer\apache-tomcat-6.0.39</home>
- </container>
- <configuration>
- <type>existing</type>
- <home>D:\WebServer\apache-tomcat-6.0.39</home>
- </configuration>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
4、搭建Spring
4.1、 创建配置文件,添加c3p0数据源配置信息
src/main/resources/applicationConfig.xml
- #application all config
- #jdbc c3p0
- jdbc.driver = com.mysql.jdbc.Driver
- jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
- jdbc.username = root
- jdbc.password = 12345
4.2、创建Spring配置文件
src/main/resources/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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- ">
- <!--引入配置属性文件 -->
- <context:property-placeholder location="classpath*:/applicationConfig.properties" />
- <!--扫描org.andy.work下文件,自动注入dao,entity,service为bean -->
- <context:component-scan base-package="org.andy.shop.dao.Impl,org.andy.shop.service.Impl" />
- <!-- c3p0数据源配置 -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
- destroy-method="close">
- <property name="driverClass" value="${jdbc.driver}" />
- <property name="jdbcUrl" value="${jdbc.url}" />
- <property name="user" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <!-- 请求超时时间 -->
- <property name="checkoutTimeout" value="30000" />
- <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
- <property name="idleConnectionTestPeriod" value="30" />
- <!-- 连接数据库连接池最大空闲时间 -->
- <property name="maxIdleTime" value="30" />
- <!-- 连接池初始化连接数 -->
- <property name="initialPoolSize" value="5" />
- <property name="minPoolSize" value="5" />
- <property name="maxPoolSize" value="20" />
- <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
- <property name="acquireIncrement" value="5" />
- </bean>
- <!-- spring jdbc -->
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <bean id="namedParameterJdbcTemplate"
- class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
- <constructor-arg ref="dataSource" />
- </bean>
- <!-- 配置事务管理 -->
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!-- 声明式事务,事务拦截器 -->
- <bean id="transactionInterceptor"
- class="org.springframework.transaction.interceptor.TransactionInterceptor">
- <property name="transactionManager" ref="transactionManager" />
- <!-- 配置事务属性 -->
- <property name="transactionAttributes">
- <!--下面定义事务传播属性 -->
- <props>
- <prop key="save*">PROPAGATION_REQUIRED</prop>
- <prop key="del*">PROPAGATION_REQUIRED</prop>
- <prop key="update">PROPAGATION_REQUIRED</prop>
- <prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
- <prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop>
- <prop key="*">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- <!-- Bean后处理器BeanNameAutoProxyCreator,根据List配置创建事务代理 -->
- <bean
- class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
- <!-- 下面是所有需要自动创建事务代理的bean -->
- <property name="beanNames">
- <list>
- <value>*Service</value>
- </list>
- </property>
- <!-- 下面定义BeanNameAutoProxyCreator所需的事务拦截器 -->
- <property name="interceptorNames">
- <list>
- <value>transactionInterceptor</value>
- </list>
- </property>
- </bean>
- </beans>
上面配置的详细功能已写出。
4.3、添加Log4j日志配置
src/main/resources/log4j.properties
- ### set log levels ###
- log4j.rootLogger = INFO , C , D , E
- ### console ###
- log4j.appender.C = org.apache.log4j.ConsoleAppender
- log4j.appender.C.Target = System.out
- log4j.appender.C.layout = org.apache.log4j.PatternLayout
- log4j.appender.C.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
- ### log file ###
- log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log
- log4j.appender.D.Append = true
- log4j.appender.D.Threshold = INFO
- log4j.appender.D.layout = org.apache.log4j.PatternLayout
- log4j.appender.D.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
- ### exception ###
- log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log
- log4j.appender.E.Append = true
- log4j.appender.E.Threshold = ERROR
- log4j.appender.E.layout = org.apache.log4j.PatternLayout
- log4j.appender.E.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
5、Entity,Dao,Service实现
创建如下包:
5.1、entity创建UserInfo实体
org.andy.shop.entity中添加
- package org.andy.shop.entity;
- import java.io.Serializable;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.Date;
- import org.springframework.jdbc.core.RowMapper;
- /**
- * 实现数据表与字段的映射
- *
- * @author andy
- *
- */
- public class UserInfo implements RowMapper<UserInfo>, Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8823504831198719837L;
- private Integer id;
- private String uname;
- private Integer unumber;
- private Date uRegisterTime;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUname() {
- return uname;
- }
- public void setUname(String uname) {
- this.uname = uname == null ? null : uname.trim();
- }
- public Integer getUnumber() {
- return unumber;
- }
- public void setUnumber(Integer unumber) {
- this.unumber = unumber;
- }
- public Date getuRegisterTime() {
- return uRegisterTime;
- }
- public void setuRegisterTime(Date uRegisterTime) {
- this.uRegisterTime = uRegisterTime;
- }
- @Override
- public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
- UserInfo userInfo = new UserInfo();
- userInfo.setId(rs.getInt("id"));
- userInfo.setUname(rs.getString("uname"));
- userInfo.setUnumber(rs.getInt("unumber"));
- userInfo.setuRegisterTime(rs.getDate("uregister_time"));
- return userInfo;
- }
- }
实现RowMapper接口是为了方便SpringJDBC管理实体与数据库字段的映射。
5.2、实现Dao层
org.andy.shop.dao添加通用Dao接口
GenericDao.java:
- package org.andy.shop.dao;
- import java.io.Serializable;
- import java.util.List;
- /**
- * 创建时间:2015-1-30 上午10:11:59
- *
- * @author andy
- * @version 2.2
- *
- * Dao通用接口
- */
- interface GenericDao<T, PK extends Serializable> {
- T getById(PK id);
- List<T> findAll();
- PK save(T entity);
- }
添加UserInfoDao.java
- package org.andy.shop.dao;
- import org.andy.shop.entity.UserInfo;
- /**
- * 创建时间:2015-1-30 上午11:22:37
- *
- * @author andy
- * @version 2.2
- *
- * UserInfoDao
- */
- public interface UserInfoDao extends GenericDao<UserInfo, Integer> {
- }
在org.andy.shop.dao.Impl包中添加UserInfoDao的Dao实现类
UserInfoDaoImpl.java
- package org.andy.shop.dao.Impl;
- import java.util.List;
- import org.andy.shop.dao.UserInfoDao;
- import org.andy.shop.entity.UserInfo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
- import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
- import org.springframework.stereotype.Repository;
- /**
- * 创建时间:2015-1-30 上午11:25:30
- *
- * @author andy
- * @version 2.2
- *
- * UserInfoDao实现类
- */
- @Repository("userInfoDao")
- public class UserInfoDaoImpl implements UserInfoDao {
- @Autowired
- private JdbcTemplate jdbcTemplate;
- @Autowired
- private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
- @Override
- public UserInfo getById(Integer id) {
- String sql = "SELECT * FROM user_info WHERE id = ?";
- UserInfo userInfo = jdbcTemplate.queryForObject(sql, new UserInfo(),
- new Object[] { id });
- return userInfo;
- }
- @Override
- public List<UserInfo> findAll() {
- String sql = "SELECT * FROM user_info";
- List<UserInfo> userInfos = jdbcTemplate.query(sql, new UserInfo());
- return userInfos;
- }
- @Override
- public Integer save(UserInfo entity) {
- String sql = "INSERT INTO user_info(uname, unumber, uregister_time) VALUES(:uname, :unumber, :uregister_time)";
- MapSqlParameterSource paramSource = new MapSqlParameterSource();
- paramSource.addValue("uname", entity.getUname());
- paramSource.addValue("unumber", entity.getUnumber());
- paramSource.addValue("uregister_time", entity.getuRegisterTime());
- int result = namedParameterJdbcTemplate.update(sql, paramSource);
- return result;
- }
- }
5.3、实现Service层
org.andy.shop.dao.service添加UserInfoService接口
UserInfoService.java
- package org.andy.shop.service;
- import java.util.List;
- import org.andy.shop.entity.UserInfo;
- /**
- * 创建时间:2015-1-30 上午11:31:34
- *
- * @author andy
- * @version 2.2
- *
- * UserInfoService 接口
- */
- public interface UserInfoService {
- // 通过Id查询UserInfo
- UserInfo getById(Integer id);
- // 查询全部的UserInfo
- List<UserInfo> findAll();
- // 添加UserInfo
- Integer save(UserInfo userInfo);
- }
实现UserInfoService接口
- package org.andy.shop.service.Impl;
- import java.util.List;
- import org.andy.shop.dao.UserInfoDao;
- import org.andy.shop.entity.UserInfo;
- import org.andy.shop.service.UserInfoService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- /**
- * 创建时间:2015-1-30 上午11:40:19
- *
- * @author andy
- * @version 2.2 实现接口
- */
- @Service("userInfoService")
- public class UserInfoServiceImpl implements UserInfoService {
- @Autowired
- private UserInfoDao userInfoDao;
- @Override
- public UserInfo getById(Integer id) {
- return userInfoDao.getById(id);
- }
- @Override
- public List<UserInfo> findAll() {
- return userInfoDao.findAll();
- }
- @Override
- public Integer save(UserInfo userInfo) {
- return userInfoDao.save(userInfo);
- }
- }
6、测试Spring搭建
单元测试Service中的方法,如果全部成功,Spring和数据连接池搭建完成。
- package org.andy.shop.test.service;
- import java.util.Date;
- import java.util.List;
- import org.andy.shop.entity.UserInfo;
- import org.andy.shop.service.UserInfoService;
- import org.apache.log4j.Logger;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import com.alibaba.fastjson.JSON;
- /**
- * 创建时间:2015-1-30 下午12:01:47
- *
- * @author andy
- * @version 2.2
- */
- // 引入Spring环境测试
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
- public class TestUserInfoService {
- private static final Logger LOGGER = Logger
- .getLogger(TestUserInfoService.class);
- @Autowired
- private UserInfoService userInfoService;
- @Test
- public void testGetById() {
- //测试查询对应的用户
- UserInfo userInfo = userInfoService.getById(1);
- LOGGER.info(JSON.toJSONStringWithDateFormat(userInfo,
- "yyyy-MM-dd HH:mm:ss"));
- }
- @Test
- public void testFindAll() {
- //测试查询全部用户
- List<UserInfo> userInfos = userInfoService.findAll();
- for (UserInfo userInfo : userInfos) {
- LOGGER.info(JSON.toJSONStringWithDateFormat(userInfo,
- "yyyy-MM-dd HH:mm:ss"));
- }
- }
- @Test
- public void testSave() {
- //测试保存用户数据
- UserInfo userInfo = new UserInfo();
- userInfo.setUname("xiaohonghong");
- userInfo.setUnumber(5);
- userInfo.setuRegisterTime(new Date());
- int result = userInfoService.save(userInfo);
- LOGGER.info("result = " + result);
- }
- }
7、搭建SpringMVC
src/main/resources/springMVC.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
- <!-- 自动扫描controller包下的所有类,如果@Controller注入为bean -->
- <context:component-scan base-package="org.andy.shop.controller" />
- <!-- 以下为SpringMVC配置 -->
- <mvc:annotation-driven>
- <!-- 返回json数据,@response使用 -->
- <mvc:message-converters register-defaults="true">
- <bean
- class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8</value>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/views" />
- <property name="suffix" value=".jsp" />
- </bean>
- <!-- 配置多文件上传 -->
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding">
- <value>UTF-8</value>
- </property>
- <property name="maxUploadSize">
- <!-- 上传文件大小限制为 -->
- <value>32505856</value>
- </property>
- <property name="maxInMemorySize">
- <value>4096</value>
- </property>
- </bean>
- </beans>
8、控制层Controller
添加UserInfoController控制层
- package org.andy.shop.controller;
- import java.util.List;
- import org.andy.shop.entity.UserInfo;
- import org.andy.shop.service.UserInfoService;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.ModelMap;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- /**
- * 创建时间:2015-2-1 下午9:40:03
- *
- * @author andy
- * @version 2.2
- *
- * userInfo的控制层
- */
- @Controller
- @RequestMapping("/user")
- public class UserInfoController {
- private static final Logger LOGGER = Logger
- .getLogger(UserInfoController.class);
- @Autowired
- private UserInfoService userInfoService;
- @RequestMapping("/showInfo/{userId}")
- public String showUserInfo(ModelMap modelMap, @PathVariable int userId) {
- LOGGER.info("查看用户:" + userId);
- UserInfo userInfo = userInfoService.getById(1);
- modelMap.addAttribute("userInfo", userInfo);
- return "/user/showInfo";
- }
- @RequestMapping("/showInfos")
- public @ResponseBody List<UserInfo> showUserInfos() {
- LOGGER.info("json返回全部用户的信息");
- List<UserInfo> userInfos = userInfoService.findAll();
- return userInfos;
- }
- }
9、视图层
在webapp/WEB-INF/views/user中创建showInfo.jsp文件。
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="<%=basePath%>" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
- <title>userInfo</title>
- </head>
- <body>
- 姓名: ${userInfo.uname}
- <br/>
- ajax显示全部用户信息:
- <div id="show_all_user"></div>
- </body>
- <script type="text/javascript">
- $.ajax({
- type : "get",
- url : "user/showInfos.htmls",
- dataType : "json",
- success : function(data) {
- $(data).each(
- function(i, user) {
- var p = "<p>username:" + user.uname + " unumber:"
- + user.unumber + " uregister:"
- + user.uRegisterTime + "</p>";
- $("#show_all_user").append(p);
- });
- },
- async : true
- });
- </script>
- </html>
10、配置web.xml容器
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- id="WebApp_ID" version="2.5">
- <display-name>springmvc_demo</display-name>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath*:/applicationContext.xml</param-value>
- </context-param>
- <filter>
- <filter-name>encodingFilter</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>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 防止spring内存溢出监听器 -->
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
- <servlet>
- <description>spring mvc servlet</description>
- <servlet-name>rest</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <!-- 此处配置的是SpringMVC的配置文件 -->
- <param-value>classpath*:/springMVC.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>rest</servlet-name>
- <url-pattern>*.htmls</url-pattern>
- </servlet-mapping>
- <!-- 配置session超时时间,单位分钟 -->
- <session-config>
- <session-timeout>30</session-timeout>
- </session-config>
- <welcome-file-list>
- <welcome-file>/index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
11、测试项目
maven编译打包部署到tomcat,测试:http://localhost:8080/springmvc_demo/user/showInfo/1.htmls分别测试添加的两个请求地址。
至此,SpringMVC搭建完毕。
相关推荐
《构建基于Maven、SpringMVC、Spring和MyBatis的Web应用框架V1.0详解》 在软件开发领域,高效且稳定的架构是项目成功的关键。本篇将深入探讨如何构建一个基于Maven、SpringMVC、Spring和MyBatis的Web应用框架V1.0,...
《Java开发中的SpringMVC + Spring + SpringJDBC整合详解》 在Java开发领域,Spring框架因其强大的功能和灵活性而备受推崇。SpringMVC、Spring和SpringJDBC是Spring框架中的核心组件,它们的整合使用可以构建出高效...
在本项目中,Maven负责下载和管理所需的库,如Spring、Spring MVC、MyBatis以及MySQL的JDBC驱动,同时也负责编译、测试、打包和部署整个应用。 2. Spring MVC:Spring MVC是Spring框架的一部分,用于构建Web应用...
《Spring MVC + Spring + Spring JDBC 技术栈与Maven配置详解》 在现代企业级应用开发中,Spring框架以其强大的功能和灵活的扩展性深受开发者喜爱。本篇将深入探讨一个基于Spring MVC、Spring JDBC的技术栈项目——...
这是一个基于Java技术栈的Web应用示例项目,主要采用了Spring、SpringMVC、MyBatis、Log4j和SpringTest等组件。以下是这些技术及其在项目中的应用详解: 1. **Spring**:Spring是一个全面的Java企业级应用开发框架...
【SpringMVC精品资源——Maven、Mysql、Shiro、SpringMVC与Spring整合详解】 在当前的Java Web开发领域,SpringMVC框架因其强大的功能和灵活性而被广泛使用。这个压缩包“SpringMVC精品资源--Maven + Mysql + Shiro...
【标题】"在Idea中基于Maven的SpringMVC+MyBatis框架的Demo"是一个实战教程,旨在展示如何在IntelliJ IDEA (Idea)集成开发环境中使用Maven构建一个结合SpringMVC和MyBatis的Java Web项目。这个项目可能是为了教学...
【标题】"maven+springmvc+mybatis"是一个常见的Java Web开发技术栈,它将Maven作为项目构建工具,Spring MVC作为控制器层框架,MyBatis作为持久层框架。这三个组件结合,能够帮助开发者高效地构建、管理和部署Java...
本项目旨在为新手提供一个基础的SSM框架搭建教程,并且加入了Maven管理和MySql数据库支持,以及分页功能的详细讲解,帮助初学者快速上手。 首先,我们来详细了解一下SSM框架的核心组件: 1. **Spring**:Spring 是...
**基于Maven的Spring+SpringMVC+Mybatis框架整合详解** 在Java Web开发中,Spring、SpringMVC和Mybatis是三个非常重要的组件,它们分别负责依赖注入、MVC架构和持久层操作。将这三个框架整合在一起可以构建出高效、...
这个压缩包文件包含了使用Maven进行SSM集成的基础配置和示例,旨在帮助开发者快速搭建项目结构,减少重复工作,提高开发效率。 1. **Maven**: Maven是一个项目管理和综合工具,它通过定义项目对象模型(Project ...
### 基于Maven的Spring + Spring MVC + MyBatis环境搭建详解 #### 一、项目背景与目标 在本篇文章中,我们将探讨如何基于Maven构建一个包含Spring、Spring MVC以及MyBatis框架的集成环境。项目的主要目的是为了...
Spring还提供了大量的模块,如Spring MVC用于Web开发,Spring JDBC和MyBatis集成用于数据库操作,以及Spring Boot用于快速开发现代Web应用。 ### SpringMVC SpringMVC是Spring框架的一部分,专为Web应用设计。它...
这个"springMVC+spring+mybatis(shiro+redis)框架样本"是一个综合性的项目实例,它整合了这五个关键组件,为开发者提供了一个全面的权限管理和数据访问解决方案。 1. **Spring框架**:Spring是Java企业级应用的...
**SpringMVC+Mybatis+Maven项目框架详解** 在现代Java Web开发中,SpringMVC、Mybatis和Maven是三个非常关键的组件,它们共同构建了一个高效、灵活且易于维护的项目框架。让我们深入了解一下这三个技术以及它们如何...
1. **引入依赖**:在项目中添加Spring、SpringMVC和Mybatis的依赖库,通常通过Maven或Gradle构建工具来管理。 2. **配置Spring**:创建Spring的配置文件,定义Bean的生命周期和依赖关系,包括数据源、...
### Maven+SSM(Spring+SpringMVC+MyBatis)整合框架详解 #### Maven 安装与配置 在深入SSM框架整合之前,首先需要确保Maven环境的正确安装与配置。 1. **安装Maven** - **前提条件**:安装 JDK 1.7 及以上版本并...
**SpringMVC+Spring3.2+Hibernate4整合详解** 在现代Java开发中,Spring框架以其模块化、可扩展性和企业级应用支持而备受青睐。本篇将详细讲解如何将SpringMVC、Spring3.2和Hibernate4进行整合,构建一个高效、灵活...
本文将详细介绍如何在Maven环境下搭建一个SpringMVC和MyBatis的最精简实例。 **一、项目结构** 在Maven项目中,我们通常遵循标准的目录结构,如下所示: - `src/main/java`:存放源代码,包括SpringMVC的...