zoukankan      html  css  js  c++  java
  • SpringMVC简单项目配置

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

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    3.     xmlns="http://java.sun.com/xml/ns/javaee"   
    4.     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    6.     id="WebApp_ID" version="3.0">  
    7.     <!--处理从页面传递中文到后台而出现的中文乱码问题 -->  
    8.       <!-- encoding start -->  
    9.   <filter>  
    10.     <filter-name>encodingFilter</filter-name>  
    11.     <filter-class>                      
    12.             org.springframework.web.filter.CharacterEncodingFilter    
    13.         </filter-class>  
    14.     <init-param>  
    15.       <param-name>encoding</param-name>  
    16.       <param-value>UTF-8</param-value>  
    17.     </init-param>  
    18.     <init-param>  
    19.       <param-name>forceEncoding</param-name>  
    20.       <param-value>true</param-value>  
    21.     </init-param>  
    22.   </filter>   
    23.   <filter-mapping>  
    24.     <filter-name>encodingFilter</filter-name>  
    25.     <url-pattern>/*</url-pattern><!-- 对所有文件过滤 -->  
    26.   </filter-mapping>  
    27.   <!-- encoding ends -->  
    28.   <!-- 首页设置 -->  
    29. <welcome-file-list>  
    30.     <welcome-file>index.jsp</welcome-file>  
    31. </welcome-file-list>  
    32. </web-app>  

    在WebContent下建一个index.jsp

    [html] view plain copy
     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7. <title>welcome</title>  
    8. </head>  
    9. <body>  
    10.     This is MySpringMVC!  
    11. </body>  
    12. </html>  

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

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

    [html] view plain copy
     
    1. <href="toLogin.do">登录</a>  

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

    [html] view plain copy
     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7. <title>登录界面</title>  
    8. </head>  
    9. <body>  
    10. <form action="userLogin.do" method="post">  
    11. <input type="hidden" name="categoryId" value="1" />  
    12.   
    13.   
    14. <div class="login">  
    15.   <div class="loginleft">  
    16.      <class="logotext">MySpringMVC登录界面</p>  
    17.    </div>  
    18.    <div class="loginright">  
    19.      <class="loginrighttit">用户登录</p>  
    20.      <ul>  
    21.        <li><p>用&nbsp;&nbsp;户&nbsp;&nbsp;名:</p<input name="userName" id="userName" type="text"/>  
    22.        </li>  
    23.        <li><p>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</p<input name="loginPassword" id="loginPassword" type="password"/>  
    24.        </li>  
    25. </ul>  
    26.      <p><input name="" type="submit" value="登&nbsp;&nbsp;录" class="loginrightbutton" /></p>  
    27.    </div>   
    28. </div>  
    29. </form>  
    30. </body>  
    31. </html>  

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

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:context="http://www.springframework.org/schema/context"  
    4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    5.     xsi:schemaLocation="  
    6.         http://www.springframework.org/schema/beans       
    7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    8.         http://www.springframework.org/schema/context   
    9.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    10.     <!-- 视图解释类 -->    
    11.     <bean id="viewResolver"  
    12.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    13.         <property name="viewClass"   
    14.         value="org.springframework.web.servlet.view.JstlView"/>  
    15.         <property name="prefix">  
    16.             <value>/WEB-INF/webPage/</value>  
    17.         </property>  
    18.         <property name="suffix">  
    19.             <value>.jsp</value>  
    20.         </property>  
    21.     </bean>  
    22. </beans>  

    在web.xml中添加配置文件

    [html] view plain copy
     
    1. <!-- SpringMVC  DispatcherServlet配置 -->  
    2. <servlet>  
    3.     <servlet-name>spring</servlet-name>  
    4.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    5.     <init-param>  
    6.         <param-name>contextConfigLocation</param-name>  
    7.         <param-value>/WEB-INF/xmlConfig/webConfig.xml</param-value>  
    8.     </init-param>  
    9.     <load-on-startup>1</load-on-startup>  
    10. </servlet>  
    11. <!-- springmvc 请求后缀 -->  
    12. <servlet-mapping>  
    13.     <servlet-name>spring</servlet-name>  
    14.     <url-pattern>*.do</url-pattern><!-- 拦截所有以.do结尾的请求,交于DispatcherServlet处理 -->  
    15. </servlet-mapping>  

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

    [java] view plain copy
     
    1. package com.user.action;  
    2.   
    3. import org.springframework.stereotype.Controller;  
    4. import org.springframework.ui.ModelMap;  
    5. import org.springframework.web.bind.annotation.RequestMapping;  
    6.   
    7. @Controller  
    8. //标明这是一个控制层类  
    9. public class UserAction {  
    10.     @RequestMapping(value = "/toLogin.do")  
    11.     //响应index.jsp的登录请求  
    12.     public String login(ModelMap map){    
    13.         return "/Login";  
    14.     }  
    15. }  

    在webConfig里添加

    [html] view plain copy
     
    1. <!-- 自动扫描的包名 ,扫描控制层-->    
    2.    <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三个字段

    [html] view plain copy
     
    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

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:security="http://www.springframework.org/schema/security"  
    4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
    6.     xmlns:context="http://www.springframework.org/schema/context"  
    7.     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    8.     xsi:schemaLocation="    
    9.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    10.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
    11.         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd    
    12.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
    13.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    
    14.         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd    
    15.         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    
    16.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd    
    17.         http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd    
    18.         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd    
    19.         http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd    
    20.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd    
    21.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd  
    22.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
    23.     <!-- Activates scanning of @Service -->    
    24.     <context:component-scan base-package="com.user.service"/>   
    25.     <!-- Activates scanning of @Repository -->    
    26.     <context:component-scan base-package="com.user.dao"/>  
    27.     <!-- 加载属性文件,分散配置解析 -->  
    28.     <!-- ====================================================================================== -->  
    29.     <context:property-placeholder location="/WEB-INF/properties/*.properties" />  
    30.     <!-- ====================================================================================== -->  
    31.     <!-- 配置 数据源 连接池 c3p0 -->  
    32.     <!-- ====================================================================================== -->  
    33.     <!-- 读写数据源 -->  
    34.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
    35.         destroy-method="close">  
    36.         <property name="driverClass" value="${driver}"></property>  
    37.         <property name="jdbcUrl" value="${url}"></property>  
    38.         <property name="user" value="${user}"></property>  
    39.         <property name="password" value="${password}"></property>  
    40.     </bean>  
    41.     <!-- 配置jdbc模板类jdbcTemplate -->  
    42.      <bean id="film-template" class="org.springframework.jdbc.core.JdbcTemplate">    
    43.      <property name="dataSource" ref="dataSource"/>    
    44.    </bean>    
    45. </beans>  

    在web.xml中加入如下代码

    [html] view plain copy
     
    1.     <!-- ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息 -->  
    2. <listener>  
    3.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    4. </listener>  
    5. <!-- 加载配置文件 -->  
    6. <context-param>  
    7. <param-name>contextConfigLocation</param-name>  
    8. <param-value>  
    9. /WEB-INF/xmlConfig/globalApplication.xml  
    10. </param-value>  
    11. </context-param>  

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

    [java] view plain copy
     
    1. package com.user.vo;  
    2.   
    3. public class UserVo {  
    4.     private int id;  
    5.     private String name;  
    6.     private String password;  
    7.     public int getId() {  
    8.         return id;  
    9.     }  
    10.     public void setId(int id) {  
    11.         this.id = id;  
    12.     }  
    13.     public String getName() {  
    14.         return name;  
    15.     }  
    16.     public void setName(String name) {  
    17.         this.name = name;  
    18.     }  
    19.     public String getPassword() {  
    20.         return password;  
    21.     }  
    22.     public void setPassword(String password) {  
    23.         this.password = password;  
    24.     }  
    25.       
    26. }  

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

    [java] view plain copy
     
    1. package com.user.dao;  
    2.   
    3. import com.user.vo.UserVo;  
    4.   
    5. public interface UserDao {  
    6.     public UserVo login(UserVo u);  
    7. }  

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

    [java] view plain copy
     
    1. package com.user.dao.impl;  
    2.   
    3. import java.sql.ResultSet;  
    4. import java.sql.SQLException;  
    5. import java.util.List;  
    6.   
    7. import org.springframework.beans.factory.annotation.Autowired;  
    8. import org.springframework.beans.factory.annotation.Qualifier;  
    9. import org.springframework.jdbc.core.JdbcTemplate;  
    10. import org.springframework.jdbc.core.RowMapper;  
    11. import org.springframework.stereotype.Repository;  
    12.   
    13. import com.user.dao.UserDao;  
    14. import com.user.vo.UserVo;  
    15. @Repository("userDao")  
    16. public class UserDaoImpl implements UserDao{  
    17.     @Autowired  
    18.     @Qualifier("film-template")//名字跟xml中配置的id要一致  
    19.        /* 封装一个JdbcTemplate的模板对象 */    
    20.     private JdbcTemplate jdbcTemplate;    
    21.     
    22.     /* 通过set方法注入进来即可 */    
    23.     public JdbcTemplate getJdbcTemplate() {  
    24.         return jdbcTemplate;  
    25.     }  
    26.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
    27.         this.jdbcTemplate = jdbcTemplate;  
    28.     }  
    29.     @Override  
    30.     public UserVo login(UserVo u) {  
    31.         String sql="select * from user where name=? and password=?";  
    32.         Object[] param = new Object[]{u.getName(),u.getPassword()};  
    33.         List<UserVo> la = jdbcTemplate.query(sql,param,new RowMapper<UserVo>() {  
    34.                     public UserVo mapRow(ResultSet rs, int i)  
    35.                             throws SQLException {  
    36.                         UserVo vo = new UserVo();  
    37.                         vo.setId(rs.getInt("id"));  
    38.                         vo.setName(rs.getString("name"));  
    39.                         vo.setPassword(rs.getString("password"));  
    40.                         return vo;  
    41.                     }  
    42.                 });  
    43.         if(la!=null&&la.size()>0){  
    44.             return la.get(0);  
    45.         }else{  
    46.             return null;  
    47.         }  
    48.     }  
    49.   
    50. }  

    接口类UserService

    [java] view plain copy
     
    1. package com.user.service;  
    2.   
    3. import com.user.vo.UserVo;  
    4.   
    5. public interface UserService {  
    6.     public UserVo login(UserVo u);  
    7. }  

    实现类UserServiceImpl

    [java] view plain copy
     
    1. package com.user.service.impl;  
    2.   
    3. import org.springframework.beans.factory.annotation.Autowired;  
    4. import org.springframework.beans.factory.annotation.Qualifier;  
    5. import org.springframework.stereotype.Service;  
    6.   
    7. import com.user.dao.UserDao;  
    8. import com.user.service.UserService;  
    9. import com.user.vo.UserVo;  
    10. @Service("userService")  
    11. public class UserServiceImpl implements UserService{  
    12.     @Autowired  
    13.     @Qualifier("userDao")  
    14.     private UserDao userDao;  
    15.     public UserDao getUserDao() {  
    16.         return userDao;  
    17.     }  
    18.     public void setUserDao(UserDao userDao) {  
    19.         this.userDao = userDao;  
    20.     }  
    21.     @Override  
    22.     public UserVo login(UserVo u) {  
    23.         // TODO Auto-generated method stub  
    24.         return userDao.login(u);  
    25.     }  
    26.   
    27. }  

    在UserAction中新建一个方法

    [java] view plain copy
     
    1. package com.user.action;  
    2.   
    3. import java.io.IOException;  
    4.   
    5. import javax.servlet.http.HttpServletRequest;  
    6. import org.springframework.beans.factory.annotation.Autowired;  
    7. import org.springframework.beans.factory.annotation.Qualifier;  
    8. import org.springframework.stereotype.Controller;  
    9. import org.springframework.ui.ModelMap;  
    10. import org.springframework.web.bind.annotation.RequestMapping;  
    11. import org.springframework.web.bind.annotation.RequestMethod;  
    12.   
    13. import com.user.service.UserService;  
    14. import com.user.vo.UserVo;  
    15. @Controller  
    16. public class UserAction {  
    17.     @Autowired   
    18.     @Qualifier("userService")  
    19.     private UserService userService;  
    20.       
    21.     public UserService getUserService() {  
    22.         return userService;  
    23.     }  
    24.     public void setUserService(UserService userService) {  
    25.         this.userService = userService;  
    26.     }  
    27.     UserVo u=new UserVo();  
    28.     @RequestMapping(value = "/toLogin.do", method = {RequestMethod.GET,RequestMethod.POST })  
    29.     public String login(ModelMap map,HttpServletRequest request) throws IOException{      
    30.         return "/Login";  
    31.     }  
    32.     @RequestMapping(value="/userLogin", method = {RequestMethod.GET,RequestMethod.POST })  
    33.     public String loginCheck(ModelMap map,HttpServletRequest request) throws IOException{  
    34.         String name=request.getParameter("userName");//获取Login.jsp传送过来的参数  
    35.         String password=request.getParameter("loginPassword");  
    36.         u.setName(name);  
    37.         u.setPassword(password);  
    38.         UserVo vo=userService.login(u);//通过业务层实现对数据访问层的访问  
    39.         if(vo==null)  
    40.             return "/error";  
    41.         else  
    42.             System.out.println(vo.getId());  
    43.             map.addAttribute("id",vo.getId());//向前台传送一个名字为id的参数,若能成功得到值,证明成功访问数据库  
    44.         return "/success";  
    45.           
    46.     }  
    47. }  

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

    [html] view plain copy
     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7. <title>Insert title here</title>  
    8. </head>  
    9. <body>  
    10.     成功,用户的ID为${id}  
    11. </body>  
    12. </html>  

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

    [html] view plain copy
     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7. <title>Insert title here</title>  
    8. </head>  
    9. <body>  
    10.     失败!  
    11. </body>  
    12. </html>  

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

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

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

  • 相关阅读:
    深入理解计算机系统 第六章 存储器层次结构 第二遍
    深入理解计算机系统 第六章 存储器层次结构
    深入理解计算机系统 第八章 异常控制流 Part2 第二遍
    深入理解计算机系统 第八章 异常控制流 part2
    深入理解计算机系统 第八章 异常控制流 Part1 第二遍
    深入理解计算机系统 第八章 异常控制流 part1
    深入理解计算机系统 第三章 程序的机器级表示 Part2 第二遍
    深入理解计算机系统 第三章 程序的机器级表示 part2
    深入理解计算机系统 第三章 程序的机器级表示 Part1 第二遍
    深入理解计算机系统 第三章 程序的机器级表示 part1
  • 原文地址:https://www.cnblogs.com/zhaoyan001/p/7513781.html
Copyright © 2011-2022 走看看