前言
本文所述完整可运行项目程序托管在本人的github:https://github.com/Wuchenwcf/springDemo
本文所述网站发布在本人的服务器:http://www.chongfer.cn/springDemo/
本文所述涉及到Spring依赖注入的基础知识,http://blog.csdn.net/luchengtao11/article/details/67632383
本文将按照《Spring in action》书本上第五章的部分逐步构建一个简单的微博网站。对于一些知识点只是简要说明,仅作参考。想要更深入地了解,读者们可以阅读原书。
本文所述程序是通过Eclipse建立的标准Maven Web工程,因为用到Spring Mvc,所以需要在Maven pom.xml添加依赖的Spring jar包,如下图所示
一、Spring MVC起步
1.配置DispatcherServlet
package spittr.config;2.启用Spring MVC
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] {WebConfig.class};
}
//将DispatcherServlet映射到了“/”
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
package spittr.config;3.编写RootConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
//启用Mvc
@EnableWebMvc
//启用组件扫描
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
//配置JSP视图解析器
@Bean
public ViewResolver viewResolver()
{
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
//配置静态资源的处理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan(basePackages={"spitter"},excludeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {
}
二、编写基本的控制器
1.最简单的控制器
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//声明一个控制器
@Controller
public class HomeController {
//处理对“/”的GET请求
@RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
return "home";
}
}
2.在WEB-INF/view/下定义一个简单的jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Spittr</title>
</head>
<body>
<h1>Welcome to spittr</h1>
<a href="/spittles"> Spittles</a>|<a href="/spitter/register" > Register</a>
</body>
</html>
到这里,Spring web程序已经能跑起来了,如图所示:
3.传递模型数据到视图中
设计Spittle类
package spittr.Spittle;
import java.util.Date;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Spittle {
private final Long id;
private final String message;
private final Date time;
private Double latitude;
private Double longitude;
public Spittle(String message ,Date time,Double longitude,Double latitude)
{
this.id=null;
this.message=message;
this.time=time;
this.longitude=longitude;
this.latitude=latitude;
}
public long getId()
{
return this.id;
}
public String getMessage()
{
return this.message;
}
public Double getLongitude()
{
return this.latitude;
}
public Double getLatitude()
{
return this.latitude;
}
public boolean equals(Object That)
{
//应用此处代码需要comment-lang依赖
return EqualsBuilder.reflectionEquals(this,That);
}
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}
}
定义一个数据访问的Repository
package spittr.data;
import java.util.List;
import spittr.Spittle.Spittle;
public interface SpittleRepository {
List<Spittle> findSpittles(long max,int count);
}
书本上没有给出这个接口的实现,导致,不能进行前一阶段的测试,这里我写了一个简单的实现累,并在config中添加@bean注解生成Bean
package spittr.data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import spittr.Spittle.Spittle;
public class SpittleRepositoryImp implements SpittleRepository{
public List<Spittle> findSpittles(long max, int count) {
// TODO Auto-generated method stub
List<Spittle> list=new ArrayList<Spittle>();
for(int i=0;i<count;i++)
list.add(new Spittle("spittle"+i,new Date()));
return list;
}
}
然后编写SpittleController类
package spittr.web;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spittr.data.SpittleRepository;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
private SpittleRepository spittleRepository;
@Autowired
public SpittleController(SpittleRepository s)
{
this.spittleRepository=s;
}
@RequestMapping(method=RequestMethod.GET)
public String spittles(Model model)
{
model.addAttribute("spittleList",spittleRepository.findSpittles(Long.MAX_VALUE, 20));
model.addAttribute("s", 12345);
System.out.println(model.toString());
return "spittles";
}
}
编写JSP脚本Spittles.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${spittleList}" var="spittle">
<li id="spittle_<c:out value="spittle.id"/>">
<div class="spittleMessage">
<c:out value="${spittle.message}" />
</div>
<div>
<span class="spittleTime"><c:out value="${spittle.time}" /></span>
<span class="spittleLocation"> (<c:out
value="${spittle.latitude}" />, <c:out
value="${spittle.longitude}" />)
</span>
</div>
</li>
</c:forEach>
</body>
</html>
此时,整个网站又可以运行了,如下:
三、处理表单,接受用户输入
1.首先编写SpitterController,展现一个表单,允许用户注册该应用
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/spitter")
public class SpitterController {
//处理对“/spitter/register”的请求
@RequestMapping(value="/register",method=RequestMethod.GET)
public String showRegistrationForm()
{
System.out.println("REgisterForm");
return "registerForm";
}
}
2.然后编写registerForm.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css"/>" >
</head>
<body>
<h1>Register</h1>
<form method="post">
First Name:<input type="text" name="firstName" /><br/>
Last Name:<input type="text" name="lastName" /><br/>
User Name:<input type="text" name="userName" /><br/>
Password :<input type="password" name="password" /><br/>
<input type="submit" value="Register" />
</form>
</body>
</html>
此时,网站又可以完整地运行了,效果如下:
2.处理所提交的表单并注册新用户
创建SpitterController类
package spittr.web;2.添加Profile 用来显示用户信息
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spittr.Spitter;
import spittr.data.SpitterRepository;
@Controller
@RequestMapping("/spitter")
public class SpitterController {
private SpitterRepository spitterRepository;
//自动注入
@Autowired
public SpitterController(SpitterRepository sp)
{
this.spitterRepository=sp;
}
//处理对“/spitter/register”的请求
@RequestMapping(value="/register",method=RequestMethod.GET)
public String showRegistrationForm()
{
System.out.println("REgisterForm");
return "registerForm";
}
@RequestMapping(value="/register",method=RequestMethod.POST)
public String processRegistration(Spitter spitter)
{
spitterRepository.save(spitter);
return "redirect:/spitter/"+spitter.getUserName();
}
@RequestMapping(value="/{username}",method=RequestMethod.GET)
public String showSpitterProfile(@PathVariable String username,Model model)
{
Spitter spitter=spitterRepository.findByUserName(username);
model.addAttribute(spitter);
return "profile";
}
}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page isELIgnored="false" %>
<!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=ISO-8859-1">
<title>Your Profile</title>
</head>
<body>
<h1>Your Profile</h1>
<c:out value="${spitter.userName}"></c:out><br/>
<c:out value="${spitter.firstName}"></c:out>
<c:out value="${spitter.lastName}"></c:out>
</html>
到现在,网站又可以运行了。效果如下: