0%

一、首先,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文件

  1. <web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance

  2.     xmlns=”http://java.sun.com/xml/ns/javaee

  3.     xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd

  4.     xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd

  5.     id=”WebApp_ID” version=”3.0”>

  6.   <filter>

  7.     <filter-name>encodingFilter</filter-name>

  8.     <filter-class>

  9.             org.springframework.web.filter.CharacterEncodingFilter    

  10.         </filter-class>

  11.     <init-param>

  12.       <param-name>encoding</param-name>

  13.       <param-value>UTF-8</param-value>

  14.     </init-param>

  15.     <init-param>

  16.       <param-name>forceEncoding</param-name>

  17.       <param-value>true</param-value>

  18.     </init-param>

  19.   </filter>

  20.   <filter-mapping>

  21.     <filter-name>encodingFilter</filter-name>

  22.     <url-pattern>/*</url-pattern>

  23.   </filter-mapping>

  24. <welcome-file-list>

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

  26. </welcome-file-list>

  27. </web-app>

在WebContent下建一个index.jsp

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8”
  2.     pageEncoding=”UTF-8”%>
  3. <html>
  4. <head>
  5. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
  6. <title>welcome</title>
  7. </head>
  8. <body>
  9.     This is MySpringMVC!  
  10. </body>
  11. </html>

用tomcat运行项目,最好做每一步都运行下,看能通过不,不然后面很难发现错误

接下来实现页面的跳转在index.jsp里加入

  1. <a href=”toLogin.do”>登录</a>

在WEB-INF下新建文件夹webPage,然后建立Login.jsp

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8”

  2.     pageEncoding=”UTF-8”%>

  3. <html>

  4. <head>

  5. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>

  6. <title>登录界面</title>

  7. </head>

  8. <body>

  9. <form action=”userLogin.do” method=”post”>

  10. <div class=”login”>

  11.   <div class=”loginleft”>

  12.      <p class=”logotext”>MySpringMVC登录界面</p>

  13.    </div>

  14.    <div class=”loginright”>

  15.      <p class=”loginrighttit”>用户登录</p>

  16.      <ul>

  17.        <li><p>用  户  名:</p> 

  18.        </li>

  19.        <li><p>密       码:</p> 

  20.        </li>

  21. </ul>

  22.      <p></p>

  23.    </div>

  24. </div>

  25. </form>

  26. </body>

  27. </html>

在WEB-INF下建立文件夹xmlConfig,创建webConfig.xml

  1. <beans xmlns=”http://www.springframework.org/schema/beans

  2.     xmlns:context=”http://www.springframework.org/schema/context

  3.     xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance

  4.     xsi:schemaLocation=”

  5.         http://www.springframework.org/schema/beans       

  6.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

  7.         http://www.springframework.org/schema/context   

  8.         http://www.springframework.org/schema/context/spring-context-3.0.xsd"\>

  9.     <bean id=”viewResolver”

  10.         class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>

  11.         <property name=”viewClass”

  12.         value=”org.springframework.web.servlet.view.JstlView”/>

  13.         <property name=”prefix”>

  14.             <value>/WEB-INF/webPage/</value>

  15.         </property>

  16.         <property name=”suffix”>

  17.             <value>.jsp</value>

  18.         </property>

  19.     </bean>

  20. </beans>

在web.xml中添加配置文件

  1. <servlet>

  2.     <servlet-name>spring</servlet-name>

  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  4.     <init-param>

  5.         <param-name>contextConfigLocation</param-name>

  6.         <param-value>/WEB-INF/xmlConfig/webConfig.xml</param-value>

  7.     </init-param>

  8.     <load-on-startup>1</load-on-startup>

  9. </servlet>

  10. <servlet-mapping>

  11.     <servlet-name>spring</servlet-name>

  12.     <url-pattern>*.do</url-pattern>

  13. </servlet-mapping>

在src中建立com.user.action包,创建UserAction类

  1. package com.user.action;

  2. import org.springframework.stereotype.Controller;

  3. import org.springframework.ui.ModelMap;

  4. import org.springframework.web.bind.annotation.RequestMapping;

  5. @Controller

  6. public class UserAction {

  7.     @RequestMapping(value = “/toLogin.do”)

  8.     public String login(ModelMap map){

  9.         return “/Login”;

  10.     }  

  11. }

  

在webConfig里添加

  1.    <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三个字段

  1. #myspring Mysql数据库配置  
  2. driver=com.mysql.jdbc.Driver
  3. url=jdbc:mysql://localhost:3306/test
  4. user=root
  5. password=123456

在WEB-INF/xmlConfig文件夹下建立globalAppliacation.xml

  1. <beans xmlns=”http://www.springframework.org/schema/beans

  2.     xmlns:security=”http://www.springframework.org/schema/security

  3.     xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“ xmlns:p=”http://www.springframework.org/schema/p

  4.     xmlns:aop=”http://www.springframework.org/schema/aop“ xmlns:tx=”http://www.springframework.org/schema/tx

  5.     xmlns:context=”http://www.springframework.org/schema/context

  6.     xmlns:jee=”http://www.springframework.org/schema/jee“ xmlns:mvc=”http://www.springframework.org/schema/mvc

  7.     xsi:schemaLocation=”

  8.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  

  9.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    

  10.         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd    

  11.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    

  12.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    

  13.         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd    

  14.         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    

  15.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd    

  16.         http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd    

  17.         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd    

  18.         http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd    

  19.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd    

  20.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd  

  21.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"\>

  22.     <context:component-scan base-package=”com.user.service”/>

  23.     <context:component-scan base-package=”com.user.dao”/>

  24.     <context:property-placeholder location=”/WEB-INF/properties/*.properties” />

  25.     <bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource”

  26.         destroy-method=”close”>

  27.         <property name=”driverClass” value=”${driver}”></property>

  28.         <property name=”jdbcUrl” value=”${url}”></property>

  29.         <property name=”user” value=”${user}”></property>

  30.         <property name=”password” value=”${password}”></property>

  31.     </bean>

  32.      <bean id=”film-template” class=”org.springframework.jdbc.core.JdbcTemplate”>

  33.      

  34.    </bean>

  35. </beans>

在web.xml中加入如下代码

  1. <listener>

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

  3. </listener>

  4. <context-param>

  5. <param-name>contextConfigLocation</param-name>

  6. <param-value>

  7. /WEB-INF/xmlConfig/globalApplication.xml  

  8. </param-value>

  9. </context-param>

在com.user.vo中建立类UserVo,这是一个实体类

  1. package com.user.vo;

  2. public class UserVo {

  3.     private int id;

  4.     private String name;

  5.     private String password;

  6.     public int getId() {

  7.         return id;

  8.     }  

  9.     public void setId(int id) {

  10.         this.id = id;

  11.     }  

  12.     public String getName() {

  13.         return name;

  14.     }  

  15.     public void setName(String name) {

  16.         this.name = name;

  17.     }  

  18.     public String getPassword() {

  19.         return password;

  20.     }  

  21.     public void setPassword(String password) {

  22.         this.password = password;

  23.     }  

  24. }

  

然后在com.user.dao中建立接口UserDao

  1. package com.user.dao;

  2. import com.user.vo.UserVo;

  3. public interface UserDao {

  4.     public UserVo login(UserVo u);

  5. }

  

在com.user.dao.impl中实现这个接口,类UserDaoImpl

  1. package com.user.dao.impl;

  2. import java.sql.ResultSet;

  3. import java.sql.SQLException;

  4. import java.util.List;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.beans.factory.annotation.Qualifier;

  7. import org.springframework.jdbc.core.JdbcTemplate;

  8. import org.springframework.jdbc.core.RowMapper;

  9. import org.springframework.stereotype.Repository;

  10. import com.user.dao.UserDao;

  11. import com.user.vo.UserVo;

  12. @Repository(“userDao”)

  13. public class UserDaoImpl implements UserDao{

  14.     @Autowired

  15.     @Qualifier(“film-template”)

  16.     private JdbcTemplate jdbcTemplate;

  17.     public JdbcTemplate getJdbcTemplate() {

  18.         return jdbcTemplate;

  19.     }  

  20.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

  21.         this.jdbcTemplate = jdbcTemplate;

  22.     }  

  23.     @Override

  24.     public UserVo login(UserVo u) {

  25.         String sql=”select * from user where name=? and password=?”;

  26.         Object[] param = new Object[]{u.getName(),u.getPassword()};

  27.         List la = jdbcTemplate.query(sql,param,new RowMapper() {

  28.                     public UserVo mapRow(ResultSet rs, int i)

  29.                             throws SQLException {

  30.                         UserVo vo = new UserVo();

  31.                         vo.setId(rs.getInt(“id”));

  32.                         vo.setName(rs.getString(“name”));

  33.                         vo.setPassword(rs.getString(“password”));

  34.                         return vo;

  35.                     }  

  36.                 });  

  37.         if(la!=null&&la.size()>0){

  38.             return la.get(0);

  39.         }else{

  40.             return null;

  41.         }  

  42.     }  

  43. }

  

接口类UserService

  1. package com.user.service;

  2. import com.user.vo.UserVo;

  3. public interface UserService {

  4.     public UserVo login(UserVo u);

  5. }

  

实现类UserServiceImpl

  1. package com.user.service.impl;

  2. import org.springframework.beans.factory.annotation.Autowired;

  3. import org.springframework.beans.factory.annotation.Qualifier;

  4. import org.springframework.stereotype.Service;

  5. import com.user.dao.UserDao;

  6. import com.user.service.UserService;

  7. import com.user.vo.UserVo;

  8. @Service(“userService”)

  9. public class UserServiceImpl implements UserService{

  10.     @Autowired

  11.     @Qualifier(“userDao”)

  12.     private UserDao userDao;

  13.     public UserDao getUserDao() {

  14.         return userDao;

  15.     }  

  16.     public void setUserDao(UserDao userDao) {

  17.         this.userDao = userDao;

  18.     }  

  19.     @Override

  20.     public UserVo login(UserVo u) {

  21.         return userDao.login(u);

  22.     }  

  23. }

  

在UserAction中新建一个方法

  1. package com.user.action;

  2. import java.io.IOException;

  3. import javax.servlet.http.HttpServletRequest;

  4. import org.springframework.beans.factory.annotation.Autowired;

  5. import org.springframework.beans.factory.annotation.Qualifier;

  6. import org.springframework.stereotype.Controller;

  7. import org.springframework.ui.ModelMap;

  8. import org.springframework.web.bind.annotation.RequestMapping;

  9. import org.springframework.web.bind.annotation.RequestMethod;

  10. import com.user.service.UserService;

  11. import com.user.vo.UserVo;

  12. @Controller

  13. public class UserAction {

  14.     @Autowired

  15.     @Qualifier(“userService”)

  16.     private UserService userService;

  17.     public UserService getUserService() {

  18.         return userService;

  19.     }  

  20.     public void setUserService(UserService userService) {

  21.         this.userService = userService;

  22.     }  

  23.     UserVo u=new UserVo();

  24.     @RequestMapping(value = “/toLogin.do”, method = {RequestMethod.GET,RequestMethod.POST })

  25.     public String login(ModelMap map,HttpServletRequest request) throws IOException{

  26.         return “/Login”;

  27.     }  

  28.     @RequestMapping(value=”/userLogin”, method = {RequestMethod.GET,RequestMethod.POST })

  29.     public String loginCheck(ModelMap map,HttpServletRequest request) throws IOException{

  30.         String name=request.getParameter(“userName”);

  31.         String password=request.getParameter(“loginPassword”);

  32.         u.setName(name);  

  33.         u.setPassword(password);  

  34.         UserVo vo=userService.login(u);

  35.         if(vo==null)

  36.             return “/error”;

  37.         else

  38.             System.out.println(vo.getId());  

  39.             map.addAttribute(“id”,vo.getId());

  40.         return “/success”;

  41.     }  

  42. }

  

在webPage下建一个success.jsp,登录成功跳转到该界面

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8”
  2.     pageEncoding=”UTF-8”%>
  3. <html>
  4. <head>
  5. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
  6. <title>Insert title here</title>
  7. </head>
  8. <body>
  9.     成功,用户的ID为${id}  
  10. </body>
  11. </html>

再建一个error.jsp,登录失败跳转到该界面

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8”
  2.     pageEncoding=”UTF-8”%>
  3. <html>
  4. <head>
  5. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
  6. <title>Insert title here</title>
  7. </head>
  8. <body>
  9.     失败!  
  10. </body>
  11. </html>

下面是数据库user表中的数据信息

输入用户名admin,密码123456.点击登录

获取参数用户ID是2,数据库连接成功,登录相当于一个查询操作,只要数据库能连通,其他删除,修改,添加操作都挺容易的