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

Spring 入门案例(含IOC、AOP、SpringMVC、Spring JDBC)

2015-05-11 16:04 639 查看
开发一个web应用,一般采用三层体系架构:web层、服务层、持久层。Spring也拥有这三层技术,分布为Spring MVC,声明式事务和Spring JDBC,接下来我们以一个简单的实现系统登陆功能例子来具体说明。

按照组件功能的不同,将类包划分为五个,分别com.dao(dao层)、com.domain(实体类)、com.service(服务层)、com.web(web层)、com.resource(配置文件),结构图(左边为结构图、右边为用到的jar包)如下:





1、首先在数据库(sql)中创建一张用户表(t_user),并插入一条记录,代码如下:

create table t_user(
id int identity,
username varchar(50),
password varchar(50)
)

insert into t_user(username,password) values('admin','12345')

2、Domain

创建一个用户对象(User),代码如下:

package com.domain;

import java.io.Serializable;

public class User implements Serializable {

private int id; //主键id
private String username; //用户名
private String password; //密码
public int getId() {
return id;
}

//省略get/setXxx方法

}

3、持久层

创建User的Dao,包括两个方法:

getMatchCount(String username,String password):根据用户名和密码获取匹配的用户数,返回值1位正确,否则用户名或密码错误。
findUserByUserName(String username):根据用户名获取User对象。

代码如下:

<pre class="java" name="code">package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.domain.User;

@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate; //自动注入JdbcTemplate的Bean

public int getMatchCount(String username,String password){
String sql="select count(*) from t_user "
+" where username=?  and password=?";
return jdbcTemplate.queryForInt(sql,new Object[]{username,password});
}

public User findUserByUserName(final String username){
String sql="select id,username,password from t_user where username=?";
final User user=new User();
jdbcTemplate.query(sql,new Object[]{username},new RowCallbackHandler(){

public void processRow(ResultSet rs) throws SQLException {
user.setId(rs.getInt("id"));
user.setUsername(username);
user.setPassword(rs.getString("password"));
}

});

return user;
}
}



4、业务层

创建UserService的Service,包含两个方法:

hasMatchUser(String username,String password):用于检查用户名和密码的正确性。
findUserByUserName(String username):根据用户名查找User对象。

代码如下:

package com.service;

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

import com.dao.UserDao;
import com.domain.User;

@Service//将UserService标记为一个服务层的Bean
public class UserService {
@Autowired
private UserDao userDao;

public boolean hasMatchUser(String username,String password){
int mathchCount=userDao.getMatchCount(username, password);
return mathchCount>0;
}

public User findUserByUserName(String username){
return userDao.findUserByUserName(username);
}
}

5、web层

创建一个LoginControlle,完成登陆的请求,并根据登陆是否成功转向显示用户信息或者失败界面。

代码如下:

package com.web;

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.servlet.ModelAndView;

import com.domain.User;
import com.service.UserService;

@Controller//标注成为一个Spring mvc的controller
public class LoginController {
@Autowired
private UserService userService;

//负责处理/index.html的请求
@RequestMapping(value="/index.html")
public String loginPage(){
return "login";
}

//负责处理/loginCheck.html的请求
@RequestMapping(value="/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request,User user){
boolean isValidUser=userService.hasMatchUser(user.getUsername(), user.getPassword());
if(!isValidUser)
return new ModelAndView("login", "error", "用户名或密码错误");
else{
User u=userService.findUserByUserName(user.getUsername());
request.setAttribute("u", u);
return new ModelAndView("main");
}
}
}


6、JSP页面

代码如下:

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户登录界面</title>
</head>

<body>
<c:if test="${!empty error }">
<font color="red"><c:out value="${error }"></c:out></font>
</c:if>
<form action='<c:url value="/loginCheck.html"/>'>
用户名:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>

main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户登录信息</title>
</head>

<body>
登录信息:<br>
id:${u.id }<br>
username:${u.username }<br>
password:${u.password }<br>
</body>
</html>


7、创建配置文件

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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!--扫描包类,将标注Spring注解的类自动转化Bean,同时完成Bean的注入  -->
<context:component-scan base-package="com.dao"/>
<context:component-scan base-package="com.service"/>
<!--定义一个使用DBCP实现的数据源  -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://127.0.0.1;databaseName=test"/>
<property name="username" value="sa"/>
<property name="password" value="12345"/>
</bean>
<!--定义Jdbc模板Bean  -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--配置事务管理器  -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--通过Aop配置提供事务增强,让Service包下的所有Bean的所有方法拥有事务  -->
<aop:config>
<aop:pointcut expression="execution(* com.service.UserService.*(..))" id="point"/>
<aop:advisor pointcut-ref="point" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
</beans>

springmvc-servlet.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 
<!--扫描web包,应用Spring的注解-->
<context:component-scan base-package="com.web"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<!--配置视图解析器,将ModelAndView及字符串解析为具体 的页面 -->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>


web.xml

<?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配置文件,classpath关键字特指类路径下加载  -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--负责启动Spring容器的监听器,将引用  contextConfigLocation 的上下文参数获得Spring配置文件地址-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
</web-app>

8、登陆验证

地址栏栏中输入:http://127.0.0.1:8081/spring/index.html(端口号改为本机对应的端口号),输入用户名和密码,完成对应的请求。

注:测试若有问题,请指出,谢谢~


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: