一、首先,SpringMVC框架使用分层开发,分层是为了实现“高内聚,低耦合”。采用“分而治之”的思想,把问题划分开来各个解决,易于控制,延展和分配资源,最重要的是有利于后期项目维护。MVC是指Model(模型)、View(视图)、Controller(控制器),在SpringMVC的编程中一般具有四层,分别是:
表示层:(jsp、html)主要就是界面的展示
控制层:(Contoller、Action)控制界面跳转
业务层:(Service)调用DAO层,实现解耦合目的,虽然不要它也可以运行项目,但是会使项目后期的延展和维护变得困难
持久层:(DAO)也叫数据访问层,实现对数据库的访问
二、然后,注解的使用,在SpringMVC中经常用到注解,使用注解可以极大的节省开发者的时间,下面是几个最重要的注解介绍:
@Repository:标注数据访问层,可以告诉SpringMVC这是一个数据访问层,并将其申明为一个bean,例如UserDao接口的实现类UserDaoImpl,在类上加注解@Repository(“userDao”),bean的名称为userDao
@Service:标注业务层,例如UserService接口的实现类,在类上加@Service(“userService”),bean的名称为userService
@Controller:控制层,在控制层类上加@Controller即可,确认其是一个控制层类
@Component:当不确定是属于哪层是用这个注解
三、说的再多,不如做一遍,下面是一个简单的跳转并实现登录功能的SpringMVC项目的介绍
1.项目环境搭建,在eclipse下点击左上角File→New→Dynamic Web Projiect,创建项目MySpringMVC,新建项目结构如下
在lib下导入jar包,在这里,需要的jar包有哪些就不介绍了,反正是能多不能少,多了不会报错,不明白就都弄进去吧。在WEB-INF下新建web.xml文件
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“
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\_3\_0.xsd“
id=”WebApp_ID” version=”3.0”>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在WebContent下建一个index.jsp
- <%@ page language=”java” contentType=”text/html; charset=UTF-8”
- pageEncoding=”UTF-8”%>
- <html>
- <head>
- <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
- <title>welcome</title>
- </head>
- <body>
- This is MySpringMVC!
- </body>
- </html>
用tomcat运行项目,最好做每一步都运行下,看能通过不,不然后面很难发现错误
接下来实现页面的跳转在index.jsp里加入
- <a href=”toLogin.do”>登录</a>
在WEB-INF下新建文件夹webPage,然后建立Login.jsp
<%@ page language=”java” contentType=”text/html; charset=UTF-8”
pageEncoding=”UTF-8”%>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
<title>登录界面</title>
</head>
<body>
<form action=”userLogin.do” method=”post”>
<div class=”login”>
<div class=”loginleft”>
<p class=”logotext”>MySpringMVC登录界面</p>
</div>
<div class=”loginright”>
<p class=”loginrighttit”>用户登录</p>
<ul>
<li><p>用 户 名:</p>
</li>
<li><p>密 码:</p>
</li>
</ul>
<p></p>
</div>
</div>
</form>
</body>
</html>
在WEB-INF下建立文件夹xmlConfig,创建webConfig.xml
<beans xmlns=”http://www.springframework.org/schema/beans“
xmlns:context=”http://www.springframework.org/schema/context“
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“
xsi:schemaLocation=”
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context/spring-context-3.0.xsd"\>
<bean id=”viewResolver”
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”viewClass”
value=”org.springframework.web.servlet.view.JstlView”/>
<property name=”prefix”>
<value>/WEB-INF/webPage/</value>
</property>
<property name=”suffix”>
<value>.jsp</value>
</property>
</bean>
</beans>
在web.xml中添加配置文件
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/xmlConfig/webConfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
在src中建立com.user.action包,创建UserAction类
package com.user.action;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserAction {
@RequestMapping(value = “/toLogin.do”)
public String login(ModelMap map){
return “/Login”;
}
}
在webConfig里添加
- <context:component-scan base-package=”com.user.action”></context:component-scan>
运行项目,结果如下
点击登录,界面跳转
2.以上是SpringMVC一个简单环境的配置,接下来是数据库的连接,需要在lib下导入mysql的jar包,下面是做一个简单的登录功能,采用mysql数据库,建立如下包结构,有利于分层开发
在WEB-INF下建立文件夹properties,建立db.properties,保存数据库配置信息,配置的信息一定不要错了,这里是我事先建好的一个test数据库,在里面建了个user表,id,name,password三个字段
- #myspring Mysql数据库配置
- driver=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/test
- user=root
- password=123456
在WEB-INF/xmlConfig文件夹下建立globalAppliacation.xml
<beans xmlns=”http://www.springframework.org/schema/beans“
xmlns:security=”http://www.springframework.org/schema/security“
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“ xmlns:p=”http://www.springframework.org/schema/p“
xmlns:aop=”http://www.springframework.org/schema/aop“ xmlns:tx=”http://www.springframework.org/schema/tx“
xmlns:context=”http://www.springframework.org/schema/context“
xmlns:jee=”http://www.springframework.org/schema/jee“ 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.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"\>
<context:component-scan base-package=”com.user.service”/>
<context:component-scan base-package=”com.user.dao”/>
<context:property-placeholder location=”/WEB-INF/properties/*.properties” />
<bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource”
destroy-method=”close”>
<property name=”driverClass” value=”${driver}”></property>
<property name=”jdbcUrl” value=”${url}”></property>
<property name=”user” value=”${user}”></property>
<property name=”password” value=”${password}”></property>
</bean>
<bean id=”film-template” class=”org.springframework.jdbc.core.JdbcTemplate”>
</bean>
</beans>
在web.xml中加入如下代码
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/xmlConfig/globalApplication.xml
</param-value>
</context-param>
在com.user.vo中建立类UserVo,这是一个实体类
package com.user.vo;
public class UserVo {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
然后在com.user.dao中建立接口UserDao
package com.user.dao;
import com.user.vo.UserVo;
public interface UserDao {
public UserVo login(UserVo u);
}
在com.user.dao.impl中实现这个接口,类UserDaoImpl
package com.user.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.user.dao.UserDao;
import com.user.vo.UserVo;
@Repository(“userDao”)
public class UserDaoImpl implements UserDao{
@Autowired
@Qualifier(“film-template”)
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public UserVo login(UserVo u) {
String sql=”select * from user where name=? and password=?”;
Object[] param = new Object[]{u.getName(),u.getPassword()};
List
la = jdbcTemplate.query(sql,param,new RowMapper () { public UserVo mapRow(ResultSet rs, int i)
throws SQLException {
UserVo vo = new UserVo();
vo.setId(rs.getInt(“id”));
vo.setName(rs.getString(“name”));
vo.setPassword(rs.getString(“password”));
return vo;
}
});
if(la!=null&&la.size()>0){
return la.get(0);
}else{
return null;
}
}
}
接口类UserService
package com.user.service;
import com.user.vo.UserVo;
public interface UserService {
public UserVo login(UserVo u);
}
实现类UserServiceImpl
package com.user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.user.dao.UserDao;
import com.user.service.UserService;
import com.user.vo.UserVo;
@Service(“userService”)
public class UserServiceImpl implements UserService{
@Autowired
@Qualifier(“userDao”)
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public UserVo login(UserVo u) {
return userDao.login(u);
}
}
在UserAction中新建一个方法
package com.user.action;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.user.service.UserService;
import com.user.vo.UserVo;
@Controller
public class UserAction {
@Autowired
@Qualifier(“userService”)
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
UserVo u=new UserVo();
@RequestMapping(value = “/toLogin.do”, method = {RequestMethod.GET,RequestMethod.POST })
public String login(ModelMap map,HttpServletRequest request) throws IOException{
return “/Login”;
}
@RequestMapping(value=”/userLogin”, method = {RequestMethod.GET,RequestMethod.POST })
public String loginCheck(ModelMap map,HttpServletRequest request) throws IOException{
String name=request.getParameter(“userName”);
String password=request.getParameter(“loginPassword”);
u.setName(name);
u.setPassword(password);
UserVo vo=userService.login(u);
if(vo==null)
return “/error”;
else
System.out.println(vo.getId());
map.addAttribute(“id”,vo.getId());
return “/success”;
}
}
在webPage下建一个success.jsp,登录成功跳转到该界面
- <%@ page language=”java” contentType=”text/html; charset=UTF-8”
- pageEncoding=”UTF-8”%>
- <html>
- <head>
- <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
- <title>Insert title here</title>
- </head>
- <body>
- 成功,用户的ID为${id}
- </body>
- </html>
再建一个error.jsp,登录失败跳转到该界面
- <%@ page language=”java” contentType=”text/html; charset=UTF-8”
- pageEncoding=”UTF-8”%>
- <html>
- <head>
- <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
- <title>Insert title here</title>
- </head>
- <body>
- 失败!
- </body>
- </html>
下面是数据库user表中的数据信息
输入用户名admin,密码123456.点击登录
获取参数用户ID是2,数据库连接成功,登录相当于一个查询操作,只要数据库能连通,其他删除,修改,添加操作都挺容易的