Spring MVC一个简单的实例

时间:2022-01-09 21:55:33

首先在Myeclipse10里自动导入spring3.0

然后我们继续。。

1web.xml文件的配置

代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" 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_3_0.xsd">

<display-name></display-name>

 

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:bean*.xml</param-value>

</context-param>

<listener>

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

</listener>

 

<servlet>

<servlet-name>spring</servlet-name>

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

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

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>  <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller -->

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

</servlet-mapping>

<welcome-file-list>

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

</welcome-file-list>

</web-app>

 

2,实体类文件     所在目录为com.mvc.domain

代码如下:

package com.mvc.domain;

 

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name = "study")

public class Student {

@Id

@Basic(optional = false)

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id", nullable = false)

private int id;

@Column(name = "name")

private String name;

@Column(name = "address")

private String address;

 

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 getAddress() {

return address;

}

 

public void setAddress(String address) {

this.address = address;

}

 

}

 

3,创建公共Dao接口 

 

package com.mvc.dao;

 

import java.util.List;

 

public interface BaseDao {

public List<Object> getList();

 

public void add(Object obj);

 

public void update(Object obj);

 

public void delete(int id);

 

public Object getById();

}

 

4,創建學生Dao類  實現BaseDao

 

package com.mvc.dao;

 

import java.util.ArrayList;

import java.util.List;

 

import com.mvc.domain.Student;

 

public class StudentDao implements BaseDao {

private Student student;

 

@Override

public List<Object> getList() {

List<Object> list = new ArrayList<Object>();

student.setAddress("陕西省");

student.setName("ni");

student.setId(1);

list.add(student);

 

return list;

}

 

@Override

public void add(Object obj) {

System.out.println(obj.getClass().getName());

}

 

@Override

public void update(Object obj) {

 

}

 

@Override

public void delete(int id) {

}

 

@Override

public Object getById() {

 

return null;

}

 

public Student getStudent() {

return student;

}

 

public void setStudent(Student student) {

this.student = student;

}

 

}

5,創建公共Servie類 BaseService

   代碼和BaseService基本一致

package com.mvc.service;

 

import java.util.List;

 

public interface BaseService {

public List<Object> getList();

 

public void add(Object obj);

 

public void update(Object obj);

 

public void delete(int id);

 

public Object getById();

}

 

6,創建Service的實現類 實現BaseService接口

package com.mvc.service.impl;

 

import java.util.List;

 

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

import org.springframework.stereotype.Service;

 

import com.mvc.dao.StudentDao;

import com.mvc.service.BaseService;

 

@Service

public class StudentServiceImpl implements BaseService {

@Autowired

private StudentDao studentDao;

 

@Override

public List<Object> getList() {

return studentDao.getList();

}

 

@Override

public void add(Object obj) {

studentDao.add(obj);

}

 

@Override

public void update(Object obj) {

 

}

 

@Override

public void delete(int id) {

}

 

@Override

public Object getById() {

return null;

}

 

public StudentDao getStudentDao() {

return studentDao;

}

 

public void setStudentDao(StudentDao studentDao) {

this.studentDao = studentDao;

}

 

}

 

7,創建控制器的公共類

package com.mvc.dao;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.ui.ModelMap;

 

public interface BaseController {

 

public String add(HttpServletRequest request, ModelMap modelMap);

 

public String update(HttpServletRequest request, ModelMap modelMap);

 

public String delete(HttpServletRequest request, ModelMap modelMap);

 

public String get(HttpServletRequest request, ModelMap modelMap);

 

public String getList(HttpServletRequest request, ModelMap modelMap);

}

 

 

8,創建控制器的實現類

package com.mvc.controller;

 

import java.util.List;

 

import javax.servlet.http.HttpServletRequest;

 

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

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

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

 

import com.mvc.dao.BaseController;

import com.mvc.domain.Student;

import com.mvc.service.impl.StudentServiceImpl;

 

@Controller

@RequestMapping("/student.do")

public class StudentController implements BaseController {

@Autowired

private StudentServiceImpl studentService;

 

@Override

@RequestMapping(params = "method=add")

public String add(HttpServletRequest request, ModelMap modelMap) {

Student student = new Student();

student.setId(1);

student.setName("shi");

student.setAddress("shanxishengweinanshifupingxianqicunxianganlecunhuyaozu");

studentService.add(student);

modelMap.put("message", "Wo! It's a Successly");

return "index";  

//返回值index 代表的就是  控制器会根据返回值然后自动寻找index.jsp

}

 

@Override

@RequestMapping(params = "method=update")

public String update(HttpServletRequest request, ModelMap modelMap) {

 

return null;

}

 

@Override

@RequestMapping(params = "method=delete")

public String delete(HttpServletRequest request, ModelMap modelMap) {

return null;

}

 

@Override

@RequestMapping(params = "method=get")

public String get(HttpServletRequest request, ModelMap modelMap) {

return null;

}

 

@Override

@RequestMapping(params = "method=getList")

public String getList(HttpServletRequest request, ModelMap modelMap) {

List<Object> list = studentService.getList();

// request.setAttribute("list", list);

modelMap.put("list", list);

return "my";

}

 

public StudentServiceImpl getStudentService() {

return studentService;

}

 

public void setStudentService(StudentServiceImpl studentService) {

this.studentService = studentService;

}

 

}

9,創建bean.xml spring的容器

 

<?xml version="1.0" encoding="UTF-8"?>

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

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"

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   

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

   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 

<context:annotation-config />

<context:component-scan base-package="com.mvc" />  <!-- 自动扫描所有注解该路径 -->

 

<bean id="student" class="com.mvc.domain.Student" />

<bean id="studentDao" class="com.mvc.dao.StudentDao">

<property name="student" ref="student" />

</bean>

<bean id="studentService" class="com.mvc.service.impl.StudentServiceImpl">

<property name="studentDao" ref="studentDao" />

</bean>

 

<tx:annotation-driven transaction-manager="transactionManager" />

<tx:annotation-driven mode="aspectj" />

 

<aop:aspectj-autoproxy />

</beans>

10,創建spring-servlet.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:p="http://www.springframework.org/schema/p"

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.0.xsd   

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

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

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

 

<context:annotation-config />

<!-- 把标记了@Controller注解的类转换为bean -->

<context:component-scan base-package="com.mvc.controller" />

<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->

<bean

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

 

<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix="/WEB-INF/view/" p:suffix=".jsp" />

 

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver"

p:defaultEncoding="utf-8" />

</beans>  

 

11,最後就是spring mvc中的view視圖了

WEB-INF下創建view文件夾

創建my.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My.jsp</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<body>

This is my first Spring MVC Test page!

<br>

<c:forEach items="${list}" var="student">

${student.id}

${student.name}

${student.address}

<br><br>

</c:forEach>

</body>

</html>

 

創建一個index.jsp

代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <title>index.jsp]</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">    

  </head>

  <body>

    ${message}

  </body>

</html>

 

再創建一個添加的一個視圖頁

 

Add.jsp

代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>A add page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

</head>

<body>

<form action="student.do?method=add" method="post">

id:<input type="text" name="id"><br> <br> name:<input

type="text" name="name"><br> <br> address:<input

type="text" name="address"><br> <br> <input

type="submit" value="提交"><br> <br>

</form>

</body>

</html>

 

Spring Mvc搭建好了,可以正常使用了,比起Struts2,那真算方便多了!

不用在struts2.xml里進行一個一個的配置

只需要在Spring Mvc里進行註解配置  就可以了!