`
zjnbshifox
  • 浏览: 315717 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

第一次实际应用Spring MVC

    博客分类:
  • Java
阅读更多
要做一个简单的投票的东西,看spring mvc的文章已经很久了,但是没有实际用过,决定试试看,
首先是web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd" version="2.5">
    <display-name>Spring Annotation MVC Sample</display-name>
    <!--  Spring 服务层的配置文件 -->
    <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>
     
    <!--  Spring 容器启动监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
	
	<filter>
		<filter-name>Set Character Encoding</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>
	</filter>
	<filter-mapping>
		<filter-name>Set Character Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
    <!-- 
    	Spring MVC 的Servlet,
    	它将加载WEB-INF/annomvc-servlet.xml 的
    	配置文件,以启动Spring MVC模块
    -->
    <servlet>
        <servlet-name>pollmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>pollmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

在spring的applicationContext.xml中配置数据源等一些信息,这个网上很多了,主要是pollmvc-servlet.xml配置文件里面写mvc的配置,使用annotation配置就简单很多
<?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-2.5.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">
     
    <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com.fox.poll"/>

    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
	-->
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>

在代码里面只需要进行如下配置既可:
package com.nbrc.poll.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.nbrc.poll.service.PollService;
import com.nbrc.poll.vo.Candidate;
@Controller
@RequestMapping("/managecandidate.do")
public class CandidateManageController {
        @Resource
	private PollService service;
}

也可以在方法上用annotation进行声明,这样一来配置文件大大减少
如果页面上有form需要绑定到对象可以通过以下的方式
<form:form commandName="candidate">
    	候选人姓名:<form:input id="name"  path="name"/><br/>
    	候选人英文名:<form:input id="ename"  path="ename"/><br/>
		单位名称:<form:input id="corp"  path="corp"/><br/>
		小图片:<form:input id="simage"  path="simage"/><br/>
		大图片:<form:input id="bimage"  path="bimage"/><br/>
		点击后的URL:<form:input id="url"  path="url"/><br/>
		详细信息:<form:textarea path="info" id="info"/><br/>
		<input type="submit" value="保存" />
		<input type="reset" value="重置" /> 
    </form:form>

commandName制定的是要显示的对象的在Model中绑定的键的名称,如
model.put("candidate", new Candidate());

最后,当form提交的时候,可以通过标注
public String submitForm(@ModelAttribute("candidate") Candidate c){
进行绑定到对象

自己的感觉来说,spring mvc相对来说比struts2更加灵活一点,strut2对request,response这些进行了封装,但是给我的感觉就是有点不方便了,因为要取原生的这些对象需要很大的精力。例如要生成一个图图形验证码,在spring mvc里感觉就比较好一点,是我感觉问题吗?呵呵
package com.nbrc.poll.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/captcha.do")
public class CaptchaImageController {
	@RequestMapping(method = RequestMethod.GET)
	public void draw(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();

		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			int width = 60, height = 20;
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			OutputStream os = response.getOutputStream();
			Graphics g = image.getGraphics();
			Random random = new Random();
			g.setColor(getRandColor(200, 250));
			g.fillRect(0, 0, width, height);

			g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
			g.setColor(getRandColor(160, 200));
			for (int i = 0; i < 155; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}
			String sRand = "";
			for (int i = 0; i < 4; i++) {
				String rand = String.valueOf(random.nextInt(10));
				sRand += rand;
				g.setColor(new Color(20 + random.nextInt(110), 20 + random
						.nextInt(110), 20 + random.nextInt(110)));
				g.drawString(rand, 13 * i + 6, 16);
			}
			session.setAttribute("rand", sRand);
			g.dispose();

			ImageIO.write(image, "JPEG", os);
			os.flush();
			os.close();
			os = null;

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);		
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics