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文件
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- 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">
- <!--处理从页面传递中文到后台而出现的中文乱码问题 -->
- <!-- encoding start -->
- <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>
- <!-- encoding ends -->
- <!-- 首页设置 -->
- <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"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <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"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>登录界面</title>
- </head>
- <body>
- <form action="userLogin.do" method="post">
- <input type="hidden" name="categoryId" value="1" />
- <div class="login">
- <div class="loginleft">
- <p class="logotext">MySpringMVC登录界面</p>
- </div>
- <div class="loginright">
- <p class="loginrighttit">用户登录</p>
- <ul>
- <li><p>用 户 名:</p> <input name="userName" id="userName" type="text"/>
- </li>
- <li><p>密 码:</p> <input name="loginPassword" id="loginPassword" type="password"/>
- </li>
- </ul>
- <p><input name="" type="submit" value="登 录" class="loginrightbutton" /></p>
- </div>
- </div>
- </form>
- </body>
- </html>
在WEB-INF下建立文件夹xmlConfig,创建webConfig.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <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
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- 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中添加配置文件
- <!-- SpringMVC DispatcherServlet配置 -->
- <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>
- <!-- springmvc 请求后缀 -->
- <servlet-mapping>
- <servlet-name>spring</servlet-name>
- <url-pattern>*.do</url-pattern><!-- 拦截所有以.do结尾的请求,交于DispatcherServlet处理 -->
- </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")
- //响应index.jsp的登录请求
- 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
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <!-- Activates scanning of @Service -->
- <context:component-scan base-package="com.user.service"/>
- <!-- Activates scanning of @Repository -->
- <context:component-scan base-package="com.user.dao"/>
- <!-- 加载属性文件,分散配置解析 -->
- <!-- ====================================================================================== -->
- <context:property-placeholder location="/WEB-INF/properties/*.properties" />
- <!-- ====================================================================================== -->
- <!-- 配置 数据源 连接池 c3p0 -->
- <!-- ====================================================================================== -->
- <!-- 读写数据源 -->
- <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>
- <!-- 配置jdbc模板类jdbcTemplate -->
- <bean id="film-template" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource"/>
- </bean>
- </beans>
在web.xml中加入如下代码
- <!-- ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息 -->
- <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")//名字跟xml中配置的id要一致
- /* 封装一个JdbcTemplate的模板对象 */
- private JdbcTemplate jdbcTemplate;
- /* 通过set方法注入进来即可 */
- 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<UserVo> la = jdbcTemplate.query(sql,param,new RowMapper<UserVo>() {
- 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) {
- // TODO Auto-generated method stub
- 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");//获取Login.jsp传送过来的参数
- 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());//向前台传送一个名字为id的参数,若能成功得到值,证明成功访问数据库
- return "/success";
- }
- }
在webPage下建一个success.jsp,登录成功跳转到该界面
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <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"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <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,数据库连接成功,登录相当于一个查询操作,只要数据库能连通,其他删除,修改,添加操作都挺容易的
SpringMVC简单项目配置的更多相关文章
- eclipse建立springMVC 简单项目
http://jinnianshilongnian.iteye.com/blog/1594806 如何通过eclipse建立springMVC的简单项目,现在简单介绍一下. 工具/原料 eclip ...
- SpringMVC+fastjson项目配置
首先这个项目得是maven项目,不是maven项目的自己引包,我就不多说了. <!-- https://mvnrepository.com/artifact/org.springframewor ...
- golang中的GOPATH使用和简单项目配置
GOPATH 是 Go 语言的工作目录,他的值可以是一个目录路径,也可以是多个目录路径,每个目录都代表 go 语言的一个工作区. 我们开发 Golang 项目时,需要依赖一些别的代码包,这些包的存放路 ...
- 多个SpringMVC项目配置统一管理(来自于springCloud的统一配置思路)
因公司项目分多个系统进行开发,而系统架构几乎完全一样,所以同样的配置文件会存在不同的系统中 当其中的某些配置需要修改时,就需要依次把所有系统中相关的配置都修改掉 纯耗时且没技术含量的体力活 所以借鉴S ...
- springMVC初探--环境搭建和第一个HelloWorld简单项目
注:此篇为学习springMVC时,做的笔记整理. MVC框架要做哪些事情? a,将url映射到java类,或者java类的方法上 b,封装用户提交的数据 c,处理请求->调用相关的业务处理—& ...
- SpringMVC框架入门配置 IDEA下搭建Maven项目
初衷:本人初学SpringMVC的时候遇到各种稀奇古怪的问题,网上各种技术论坛上的帖子又参差不齐,难以一步到位达到配置好的效果,这里我将我配置的总结写到这里供大家初学SpringMVC的同僚们共同学习 ...
- SpringMVC简单配置
SpringMVC简单配置 一.eclipse安装Spring插件 打开help下的Install New Software 点击add,location中输入http://dist.springso ...
- IntelliJ IDEA maven springmvc+shiro简单项目
搭建springmvc简单步骤如:http://www.cnblogs.com/grasp/p/9045242.html,这点就不在描述了. 新建和设置完工程的目录后,结构如下: pom.xml文件内 ...
- SpringMVC框架入门配置 IDEA下搭建Maven项目(zz)
SpringMVC框架入门配置 IDEA下搭建Maven项目 这个不错哦 http://www.cnblogs.com/qixiaoyizhan/p/5819392.html
随机推荐
- 配置 Django
Django项目的设置文件位于项目同名目录下,名叫settings.py.这个模块,集合了整个项目方方面面的设置属性,是项目启动和提供服务的根本保证. 一.简述 settings.py文件本质上是一个 ...
- winFormToMysql&&几个控件的数据绑定
运行图: 代码: private void button1_Click(object sender, EventArgs e) { string str = "database=csharp ...
- 使用脚本调用maven命令后脚本直接退出问题
在带有maven命令的bat脚本执行的时候,执行完一个mvn 目标后会自动退出,pause命令也无效. 原因:mvn本身是一个bat命令,因此在exit退出的时候,整个脚本进程将退出,加入call命令 ...
- python 机械学习之sklearn的数据正规化
from sklearn import preprocessing #导入sklearn的处理函数用于处理一些大值数据 x_train, x_test, y_train, y_test = tr ...
- AtCoder Regular Contest 102 E Stop. Otherwise...
题目链接:atcoder 大意:有\(n\)个骰子,每个骰子上面有\(k\)个数,分别是\(1\text ~ k\),现在求\(\forall i\in[2...2k]\),求出有多少种骰子点数的组合 ...
- Android客户端与数据库交互数据的简单学习
Ø 数据库整理方案如下: 一.Android+ webservices+SQLServer : 通过webservices客户端向指定服务器发送请求,服务器响应返回指定格式的数据,如json或者x ...
- 「POJ3696」The Luckiest number【数论,欧拉函数】
# 题解 一道数论欧拉函数和欧拉定理的入门好题. 虽然我提交的时候POJ炸掉了,但是在hdu里面A掉了,应该是一样的吧. 首先我们需要求的这个数一定可以表示成\(\frac{(10^x-1)}{9}\ ...
- ubuntu “无法获得锁 /var/lib/dpkg/lock -open”
在ubuntu系统终端下,用apt-get install 安装软件的时候,如果在未完成下载的情况下将终端中断,此时 apt-get进程可能没有结束.结果,如果再次运行apt-get install ...
- poj2431(优先队列+贪心)
题目链接:http://poj.org/problem?id=2431 题目大意:一辆卡车,初始时,距离终点L,油量为P,在起点到终点途中有n个加油站,每个加油站油量有限,而卡车的油箱容量无限,卡车在 ...
- 前端JS Excel解析导入
本文转载自:https://www.cnblogs.com/yinqingvip/p/6743213.html 需要用到js-xlsx:下载地址:js-xlsx <!DOCTYPE html&g ...