您的位置:首页 > 编程语言 > Java开发

springMVC框架搭建

2015-08-12 13:07 507 查看

springMVC框架搭建

随着spring功能越来越强大实用,越来越多的公司使用springMVC来搭建自己的底层架构,今天我们来讲下springMVC框架搭建流程

项目源码下载地址:http://download.csdn.net/detail/u014316026/9001489

首先我们创建一个java Web项目:springMVC_demo

项目的结构如下:



1.在web.xml文件中定义spring核心servlet和监听器等

<?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"> 
<!--
配置spring核心servlet
servlet-name的值需要与WEB-INF下的xml文件名保持一致,所以WEB-INF下的xml文件名是:spring-servlet.xml
-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<!-- 拦截所有请求 -->
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring不拦截处理js、image、css等静态文件 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/js/*</url-pattern>
<url-pattern>/img/*</url-pattern>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>

<!-- 监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring*.xml</param-value>
</context-param>
<!-- 解决中文乱码问题 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- Spring 刷新Introspector防止内存泄露 -->
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!--
session超时定义,单位为分钟,清除服务端我们存储在Session中的对象,不清除Tomcat容器存储在Session中的对象
-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>


2.然后定义spring核心servlet,servlet的名字取决于web.xml文件中servlet标签下的servlet-name的值加上-servlet.xml,本文中的名称是spring,所以spring的核心servlet的文
4000
件名是spring-servlet.xml,核心servlet中主要定义了数据库的连接以及控制事务等操作

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 开启spring的Annotation支持 -->
<context:annotation-config/>
<!-- 启动包扫描功能,以便将带有@Controller @Repository @Service @Component等注解的类注入到spring的核心容器中 -->
<context:component-scan base-package="com.liuns"/>

<!-- 设置前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 连接数据库 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置连接池的初始值 -->
<property name="initialSize" value="${jdbc.initialSize}"></property>
<!-- 配置连接池的最大值 -->
<property name="maxActive" value="${jdbc.maxActive}"></property>
<!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${jdbc.maxIdle}"></property>
<!-- 最小空闲时,当连接少于minIdle时会自动申请一些连接 -->
<property name="minIdle" value="${jdbc.minIdle}"/>

<property name="maxWait" value="${jdbc.maxWait}"/>
</bean>

<!-- 声明jdbc模板 -->
<bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean>

<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.liuns.model.User</value>
</list>
</property>
</bean>
<!-- 事务 -->
<bean id="myTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="myTransactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="bizMethod"  expression="execution(* com.liuns.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="bizMethod" />
</aop:config>

</beans>


通过定义jdbc.properties文件连接数据库,本文是mysql数据库,文件在src下

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/liun?characterEncoding\=UTF-8
jdbc.username=root
jdbc.password=root

#配置连接池的初始值#
jdbc.initialSize=1
#配置连接池的最大值#
jdbc.maxActive=500
#最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止#
jdbc.maxIdle=20
#最小空闲时,当连接少于minIdle时会自动申请一些连接#
jdbc.minIdle=1
jdbc.maxWait=100


然后定义实体类entity层,在springMVC中叫model层

package com.liuns.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* 用户对象
* @author liuns
* @data 2015-8-12 上午09:32:11
* @version V1.0
*/
@SuppressWarnings("serial")
@Entity
@Table(name="LIUN_USER")
public class User implements Serializable{

@Id
@Column(name="ID",length=32)
private String id;
/**
* 用户名
*/
@Column(name="U_NAME",length=30)
private String u_name;
/**
* 密码
*/
@Column(name="U_PASSWORD",length=20)
private String u_password;
/**
* 绑定的手机号
*/
@Column(name="TELPHONE",length=11)
private String telphone;
/**
* 绑定的邮箱
*/
@Column(name="EMAIL",length=40)
private String email;
/**
* 常用地址
*/
@Column(name="ADDRESS",length=100)
private String address;
/**
* 出生日期
*/
@Column(name="BIRTHDAY")
private Date birthday;
/**
* 创建日期
*/
@Column(name="CREATE_DATE")
private Date create_date;

public User(){

}

public User(String id, String u_name, String u_password, String telphone,
String email, String address, Date birthday, Date create_date) {
this.id = id;
this.u_name = u_name;
this.u_password = u_password;
this.telphone = telphone;
this.email = email;
this.address = address;
this.birthday = birthday;
this.create_date = create_date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getU_name() {
return u_name;
}
public void setU_name(String u_name) {
this.u_name = u_name;
}
public String getU_password() {
return u_password;
}
public void setU_password(String u_password) {
this.u_password = u_password;
}
public String getTelphone() {
return telphone;
}
public void setTelphone(String telphone) {
this.telphone = telphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}

}


model层定义完了之后,就需要对dao层进行定义了,需要注意的是dao层的类需要通过继承org.springframework.jdbc.core.support.JdbcDaoSupport来对数据库进行操作,继承JdbcDaoSupport之后还需为其注入JdbcTemplate。dao层的注解是@Repository

package com.liuns.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.liuns.model.User;

/**
* @author liuns
* @data 2015-8-12 上午09:33:48
* @version V1.0
*/
@Repository
public class UserDao extends JdbcDaoSupport{

public void add(User user){
StringBuffer sql = new StringBuffer("insert into LIUN_USER (id,u_name,u_password,telphone,email,address,birthday,create_date) values ");
sql.append("('").append(user.getId()).append("','").append(user.getU_name()).append("','").append(user.getU_password()).append("'");
if(user.getTelphone() == null){
sql.append(",null");
}else{
sql.append(",'").append(user.getTelphone()).append("'");
}
if(user.getEmail() == null){
sql.append(",null");
}else{
sql.append(",'").append(user.getEmail()).append("'");
}
if(user.getAddress() == null){
sql.append(",null");
}else{
sql.append(",'").append(user.getAddress()).append("'");
}
if(user.getBirthday() == null){
sql.append(",null");
}else{
sql.append(",'").append(user.getBirthday()).append("'");
}
if(user.getCreate_date() == null){
sql.append(",null");
}else{
sql.append(",'").append(user.getCreate_date()).append("'");
}
sql.append(")");
System.out.println(sql.toString());
super.getJdbcTemplate().execute(sql.toString());
}

public void modify(User user){
StringBuffer sql = new StringBuffer("update LIUN_USER set ");
if(user.getTelphone() == null){
sql.append(" telphone = null ");
}else{
sql.append(" telphone = '").append(user.getTelphone()).append("' ");
}
if(user.getEmail() == null){
sql.append(" ,email = null ");
}else{
sql.append(" ,email = '").append(user.getEmail()).append("' ");
}
if(user.getAddress() == null){
sql.append(" ,address = null ");
}else{
sql.append(" ,address = '").append(user.getAddress()).append("' ");
}
if(user.getBirthday() == null){
sql.append(" ,birthday = null ");
}else{
sql.append(" ,birthday = '").append(user.getBirthday()).append("' ");
}
if(user.getCreate_date() == null){
sql.append(" ,create_date = null ");
}else{
sql.append(" ,create_date = '").append(user.getCreate_date()).append("' ");
}
sql.append(" where id = '").append(user.getId()).append("' ");
System.out.println(sql.toString());
super.getJdbcTemplate().execute(sql.toString());
}

public void delete(String id){
String sql = "delete from LIUN_USER where id = '" + id + "'";
System.out.println(sql);
super.getJdbcTemplate().execute(sql);
}

@SuppressWarnings("unchecked")
public User findById(String id){
String sql = "select * from LIUN_USER where id = '" + id + "'";
System.out.println(sql);
List<User> list = super.getJdbcTemplate().query(sql, new BeanPropertyRowMapper(User.class));
if(list != null && list.size() > 0){
return list.get(0);
}else{
return null;
}
}
/**
* 继承JdbcDaoSupport需为其注入JdbcTemplate类
*/
@Resource
public void setJdbcDaoSupport(JdbcTemplate jdbcTemplate){
super.setJdbcTemplate(jdbcTemplate);
}
}


然后是定义service层,我们先来创建一个service层的接口

package com.liuns.service;

import com.liuns.model.User;

/**
* @author liuns
* @data 2015-8-12 上午10:14:00
* @version V1.0
*/
public interface IUserService {
/**
* 新增用户
* @param user
*          用户对象
* @return void
*/
void add(User user);
/**
* 修改用户信息
* @param user
*          用户对象
* @return void
*/
void modify(User user);
/**
* 注销用户
* @param id
*          主键ID
* @Return void
*/
void delete(String id);
/**
* 查询用户基本信息
* @param id
*      主键ID
* @return User
*      用户对象
*/
User findById(String id);
}


然后定义接口的实现类,此类中需要添加@Service注解,以便进行事务管理

package com.liuns.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.liuns.dao.UserDao;
import com.liuns.model.User;
import com.liuns.service.IUserService;

/**
* @author liuns
* @data 2015-8-12 上午10:17:26
* @version V1.0
*/
@Service("userService")
public class UserServiceImpl implements IUserService{

@Autowired
private UserDao userDao;

public void add(User user) {
userDao.add(user);
}

public void delete(String id) {
userDao.delete(id);
}

public User findById(String id) {
return userDao.findById(id);
}

public void modify(User user) {
userDao.modify(user);
}

}


最后就是Action层了,在springMVC中又叫Controller层,Controller层需要添加@Controller注解和@RequestMapping注解,@RequestMapping是指请求Controller时拦截开头是/user的请求,而里面的方法也需要有@RequestMapping,value值是指请求到具体的方法名,而method值是指请求类型(get/post)

package com.liuns.controller;

import javax.servlet.http.HttpServletRequest;

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 com.liuns.model.User;
import com.liuns.service.IUserService;

/**
* @author liuns
* @data 2015-8-12 上午10:19:09
* @version V1.0
*/
@Controller
@RequestMapping(value="/user")
public class UserController {

@Autowired
private IUserService userService;

@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(HttpServletRequest request,String name, String password){
User user = new User();
user.setId("1234567890");
user.setU_name(name);
user.setU_password(password);
userService.add(user);
request.setAttribute("user", user);
return "/modify";
}

@RequestMapping(value="/modify",method=RequestMethod.POST)
public String modify(HttpServletRequest request, String id, String telphone, String email, String address){
User user = userService.findById(id);
user.setTelphone(telphone);
user.setEmail(email);
user.setAddress(address);
userService.modify(user);
//重定向时需要在url后面拼接上参数和值
return "redirect:/user/find?id="+id;
}

@RequestMapping(value="/delete",method=RequestMethod.GET)
public String delete(String id){
userService.delete(id);
return "/index";
}

@RequestMapping(value="/find",method=RequestMethod.GET)
public String find(HttpServletRequest request, String id){
User user = userService.findById(id);
request.setAttribute("user", user);
return "/user";
}
}


OK,后台代码已经完事儿了,现在就差前台jsp代码了,我们先创建一个添加用户的jsp(index.jsp),代码如下。需要注意的是请求是post,因为UserContoller中定义的add方法是post请求,还要额外注意form标签中action的值,user/add的意思是:请求@RequestMapping的值为user的controller,然后找其里面定义的add方法,

对应的contoller的注解就是@RequestMapping(value=”/user”)

以及方法的注解@RequestMapping(value=”/add”,method=RequestMethod.POST)

<body>
<form name="lnform" action="user/add" method="post">
用户名:<input type="text" name="name"  />
密  码:<input type="password" name="password" />
<input type="submit" value="提交" />
</form>
</body>


然后我们返回来看下UserController.java中的add()方法

@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(HttpServletRequest request,String name, String password){
User user = new User();
user.setId("1234567890");
user.setU_name(name);
user.setU_password(password);
userService.add(user);
request.setAttribute("user", user);
//返回到modify.jsp页面
return "/modify";
}


当用户点击提交后请求add()方法,添加成功后会返回到modify.jsp页面,有人就会问了,这样怎么能返回到modify.jsp页面呢?其实是我们在spring核心servlet中对请求路径进行了编辑,让我们再看下spring-servlet.xml文件

<!-- 设置前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>


你会发现有这样一段代码,这是指spring拦截器在拦截时会给你的请求路径后面加上“.jsp”,请求路径前面加上“/”,所有你在返回时只需要写“/modify”即可,意思是指请求到WEB-INF文件夹下的modify.jsp文件

写不动了,还有一些细节部分,这部分你们可以下载项目源码去看一下。源码下载地址已经给你们了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息