前言:有比这个更简单易懂的例子?发出来我吃掉,哈哈~~~

我也是这个初学者,如有歧义,请各路大神多担待,指出错误,以免误人子弟,文档开头整理下情绪,下面我们开始正题。

一,为了读者更能理解,我们从顺序讲解该例子

1.先看我整个目录菜单吧:



2.做java
的都知道第一部是新建项目,导入jar包(非maven项目),这一点也是很重要的,因为我一个版本不对,我弄了半天才弄好。我用的是spring3.20,mybatis-3.2.5,别忘了还有mybatis-spring-1.2.0
这个包,到时我会吧项目放到Github上。

3.把改建的目录包全部建好,下面我们开始jsp,新建一个main.jsp,代码如下,用的是ajax post访问。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%> <%@page import="java.util.*"%> <% String path =
request.getContextPath().replace("/", ""); String basePath =
request.getScheme() + "://" + request.getServerName() + ":" +
request.getServerPort() + "/" + path; %> <% Random random = new Random(); int
rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000; %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> <html> <script
type="text/javascript"src="<%=basePath%>/jquery-2.1.4.min.js"></script> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title> </head> <body> <input type="hidden" id="path"
value="<%=basePath%>"> <div id= "username"> </div> </body> <!-- Initialize
Swiper --> <script type="text/javascript"> var path = $('#path').val(); var id
=1; $.ajax({ type:"post", data:{"id":id}, url:path+"/queryUser/user",
dataType:"json", success:function(result){ $(result).each(function(index){
console.log(result[index].userName);
$('#username').html(result[index].userName); }) } }); </script> </html>
4.编写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"> <!-- 加载spring容器 --> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value> </context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- springmvc前端控制器 --> <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:springmvc.xml</param-value> </init-param>
<load-on-startup>1</load-on-startup> </servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern>
</servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern> </servlet-mapping> </web-app>
5.根据web.xml可见,我们第一部访问的是applicationContext.xml
这个配置文件,新建applicationContext.xml,特别提醒:里面有几个引用到了包目录和xml文件的地方。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--扫描Service里面的注解--> <context:component-scan
base-package="com.Service"></context:component-scan> <!-- 数据库连接池配置文件Dao层 -->
<!-- 加载配置文件 --> <context:property-placeholder
location="classpath:db.properties"/> <!-- 数据库连接池,使用dbcp --> <bean
id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close"> <property name="url"
value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/> <property name="maxActive"
value="10"/> <property name="maxIdle" value="5"/> </bean> <!--
SqlSessionFactory配置 --> <bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource"
ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="mapperLocations"
value="classpath:resource/userMapper.xml" /> </bean> <!-- mapper扫描器 --> <bean
class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--
扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 --> <property name="basePackage" value="com.Dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
<!-- 事务管理器--> <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/> </bean> </beans>
6.配置文件可以看出有一段:<context:property-placeholder
location="classpath:db.properties"/>,是取数据库配置的,新建一个db.properties,
jdbc.url=jdbc\:oracle\:thin\:@localhost\:8080\:orcl jdbc.username=admin
jdbc.password=pass123
7.下面开始加载springMVC文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!--
开启controller注解支持 --> <!--
注意事项请参考:http://jinnianshilongnian.iteye.com/blog/1762632 -->
<context:component-scan base-package="com.Controller"
use-default-filters="false"> <context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan> <!--使用mvc:annotation-driven代替上边注解映射器和注解适配器 配置
如果使用mvc:annotation-driven就不用配置上面的
RequestMappingHandlerMapping和RequestMappingHandlerAdapter-->
<mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器 --> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置jsp路径的前缀 --> <property name="prefix" value="/view/"/> <!--配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/> </bean> </beans>
8.mybatis关键点:userMapper.xml 文件,相当于代替了老式写法的Dao接口的实现,
<?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.Dao.UserDao" >
<!--resultType注意这个返回类型,resultMap返回类型写法不一样,可以参考别的教程--> <select id="getUser"
resultType="com.Entity.User" parameterType="java.lang.Integer" > SELECT * FROM
usertest where id =#{id} </select> </mapper>
9.好了,到这里配置已经完成 了,下面开始编写java文件。为了不报错,我们从dao层写到controlle层,

首先是实体类:User.java
package com.Entity; public class User { private Integer id; private String
userName; private String password; private Integer age; public Integer getId()
{ return id; } public void setId(Integer id) { this.id = id; } public String
getUserName() { return userName; } public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim(); } public String
getPassword() { return password; } public void setPassword(String password) {
this.password = password == null ? null : password.trim(); } public Integer
getAge() { return age; } public void setAge(Integer age) { this.age = age; }
@Override public String toString() { return "User [id=" + id + ", userName=" +
userName + ", password=" + password + ", age=" + age + "]"; } }
10.Dao类:UserDao.java
package com.Dao; import java.util.List; import com.Entity.User; public
interface UserDao { public List<User> getUser(Integer id); }
11.Service类:UserService.java
package com.Service; import java.util.List; import com.Entity.User; public
interface UserService { public List<User> getUserService(int id); }
12.Service实现类:UserServiceImpl.java
package com.Service.Impl; import java.util.List; import
org.springframework.beans.factory.annotation.Autowired; import
org.springframework.stereotype.Service; import com.Dao.UserDao; import
com.Entity.User; import com.Service.UserService; @Service public class
UserServiceImpl implements UserService{ @Autowired private UserDao userdao;
@Override public List<User> getUserService(int id) { List<User> username =
userdao.getUser(id); return username; } }
13.Controlle类:UserController.java
package com.Controller; import java.util.List; 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.RequestMethod; import
org.springframework.web.bind.annotation.ResponseBody; import com.Entity.User;
import com.Service.UserService; @Controller @RequestMapping("/queryUser")
public class UserController{ @Autowired private UserService userService;
@ResponseBody @RequestMapping(value="/user",method = RequestMethod.POST) public
List<User> QueryUser(int id){ List<User> username =
userService.getUserService(id); System.out.println(username); return username;
} }
14.创建数据库表,我用的是oracle: SELECT * FROM usertest
create table USERTEST ( id NUMBER, username VARCHAR2(20), password
VARCHAR2(20), age NUMBER )
查询出来的结果,自己插入的值:



15.访问地址http://localhost:8080/FamilyNOB/view/main.jsp
<http://localhost:8080/FamilyNOB/view/main.jsp>如果现实如下,恭喜你,成功了!



二,OJBK ,到这里基本上写完了,写博客真累,预览了一下,感觉和别人写的还差得多,说的容易,写着难。但希望能帮助

到初学者吧,

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信