标签:
本人初学springMVC框架,如有写的不对地方,请指出,本人会非常感谢:
2.mybatis所需jar包,oracle驱动,阿里Druid数据源工具,及spring相关包
建立用eclipse建立Javaweb Dynamic web project项目
1.项目目录如图所示:
介绍配置文件
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>proj_springmvc</display-name>
<!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:com/it/config/applicationContext-*.xml</param-value>
</context-param>
<!-- Spring MVC配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring配置 -->
<!-- ====================================== -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 项目文件编码设置 -->
<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>
<!-- 项目启动时搜索加载的开始页面的顺序 -->
<!-- 静态资源加载 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!-- 首頁配置 -->
<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>
</web-app>
2.spring上下文配置文件applicationContext-core.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd ">
<!-- 引入数据库连接属性配置文件,给dataSource作参数 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<!-- 配置数据源 使用的是阿里Druid数据源 -->
<bean id="dataSource" name="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="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="33" />
<!-- 用来检测有效sql -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<property name="filters" value="mergeStat" />
</bean>
<!-- mybatis的连接sqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config.xml" />
<!-- 自动扫描 model目录中的映射xml文件,省去了在config中手工配置<mappers> -->
<property name="mapperLocations" value="classpath:com/it/mapping/*.xml" />
</bean>
<!-- mybatis扫描对应的接口层-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.it.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- Spring aop事务管理 -->
<aop:config>
<aop:pointcut id="transactionPointcut"
expression="execution(* com.it.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut"
advice-ref="transactionAdvice" />
</aop:config>
</beans>
3.springMVC配置基本配置文件(springmvc-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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />
<!--自动扫描含有@Service将其注入为bean -->
<context:component-scan base-package="com.it.serviceImpl" />
<!-- 自动扫描的controller包名 -->
<context:component-scan base-package="com.it.controller" />
<!-- 视图解释类 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
4.mybatis映射文件(userMapper.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.it.dao.UserMapper">
<!-- namespace和定义的Mapper接口对应,并实现其中的方法 -->
<resultMap type="com.it.bean.User" id="userResultMap">
<id property="id" column="ID" />
<result property="name" column="NAME"/>
<result property="age" column="AGE" />
</resultMap>
<select id="getUser" parameterType="String"
resultMap="userResultMap">
select * from users where id=#{id}
</select>
<select id="getAllUser"
resultType="list" resultMap="userResultMap">
select * from users
</select>
<select id="addUser" parameterType="com.it.bean.User">
insert into users values(#{id}, #{name},#{age})
</select>
<delete id="delUser" parameterType="String">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="com.it.bean.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
</mapper>
5.mybatis配置文件
<?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" />
<property name="url" value="jdbc:mysql://localhost:3306/test" /> -->
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="username" />
<property name="password" value="1234546" />
</dataSource>
</environment>
</environments>
<!-- <mappers>
注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml
<mapper resource="com/it/mapping/userMapper.xml"/>
</mappers> -->
</configuration>
6.数据库连接属性配置文件(jdbc.properties)
#mysql version database druid setting
validationQuery=SELECT 1
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=username
jdbc.password=123456
package com.it.bean;
public class User {
private String id;
private String name;
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2.接口dao层实现,接口层名称,方法名必须和映射文件的的空间名,方法名一致:
package com.it.dao;
import java.util.List;
import com.it.bean.User;
public interface UserMapper {
public User getUser(String id);
public List<User> getAllUser();
public void addUser(User user);
public boolean delUser(String id);
public boolean updateUser(User user);
}
3.service层的实现,包括两个文件接口文件(UserService.java)和实现文件(UserServiceImpl.java),UserService接口文件和dao层接口文件一致,在这里就不贴UserService.java 代码,UserServiceImpl.java实现层代码如下;
package com.it.serviceImpl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.it.bean.User;
import com.it.dao.UserMapper;
import com.it.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper usermapper;
@Override
public User getUser(String id) {
return usermapper.getUser(id);
}
@Override
public List<User> getAllUser() {
return usermapper.getAllUser();
}
@Override
public void addUser(User user) {
usermapper.addUser(user);
}
@Override
public boolean delUser(String id) {
return usermapper.delUser(id);
}
@Override
public boolean updateUser(User user) {
return usermapper.updateUser(user);
}
}
4.控制层com.it.controller(UserController.java),主要实现业务逻辑,页面跳转功能
package com.it.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.it.bean.User;
import com.it.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getAllUser")
public String getAllUser(HttpServletRequest request){
request.setAttribute("userList", userService.getAllUser());
System.out.println(">>>>>>>>>>>getAllUser>>>>>>>>>>>>>>>");
return "/Index";
}
@RequestMapping("/getUser")
public String getUser(String id,HttpServletRequest request){
request.setAttribute("user", userService.getUser(id));
return "/editUser";
}
@RequestMapping("/toAddUser")
public String toAddUser(){
return "/addUser";
}
@RequestMapping("/addUser")
public String addUser(User user,HttpServletRequest request){
System.out.println("用户名:======"+user.getName());
System.out.println("用户名:======"+user.getAge());
user.setId(String.valueOf(System.currentTimeMillis()));
userService.addUser(user);
return "redirect:/user/getAllUser";
}
@RequestMapping("/delUser")
public void delUser(String id,HttpServletResponse response){
String result = "{\"result\":\"error\"}";
if(userService.delUser(id)){
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");
try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/updateUser")
public String updateUser(User user,HttpServletRequest request){
System.out.println("------user.getId()------"+user.getId());
System.out.println("------user.getName()------"+user.getName());
System.out.println("------user.getAge()------"+user.getAge());
if(userService.updateUser(user)){
user = userService.getUser(user.getId());
request.setAttribute("user", user);
return "redirect:/user/getAllUser";
}else{
return "/error";
}
}
}
5.编写实现层应该注意的地方
@Autowired
private UserService userService;
@Service(“userService”)
Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。
- 主要页面
1.首页(Login.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
</head>
<body>
<h5><a href="/proj_springmvc/user/getAllUser">进入用户管理页</a></h5>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path%>/js/jquery-1.7.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function del(id){
$.get("/proj_springmvc/user/delUser?id=" + id,function(data){
if("success" == data.result){
alert("删除成功");
window.location.reload();
}else{
alert("删除失败");
}
});
}
</script>
</head>
<body>
<h6><a href="/proj_springmvc/user/toAddUser">添加用户</a></h6>
<table border="1">
<tbody>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:if test="${!empty userList }">
<c:forEach items="${userList }" var="user">
<tr>
<td>${user.name }</td>
<td>${user.age }</td>
<td>
<a href="/proj_springmvc/user/getUser?id=${user.id }">编辑</a>
<a href="javascript:del(‘${user.id }‘)">删除</a>
</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</body>
</html>
3.更新页面(editUser.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>编辑用户</h1>
<form action="/proj_springmvc/user/updateUser" name="userForm" method="post">
<input type="hidden" name="id" value="${user.id }">
姓名:<input type="text" name="name" value="${user.name }">
年龄:<input type="text" name="age" value="${user.age }">
<input type="submit" value="编辑" >
</form>
</body>
</html>
4.添加页面(addUser.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action = "/proj_springmvc/user/addUser";
form.method="post";
form.submit();
}
</script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
姓名:<input type="text" name="name">
年龄:<input type="text" name="age">
<input type="button" value="添加" onclick="addUser()">
</form>
</body>
</html>
标签:
原文地址:http://blog.csdn.net/beawesome/article/details/51480824