Spring MVC开发web project笔记

Spring真是博大精深, 之前老人让我用Spring来做一个网站服务器,当做练习,自己看书看了好几天,稍微明白了Spring的主要作用,但是说到写代码,那是绝对难以动手的,之后写了一些代码给老人看,结果也是惨不忍睹的, 还在老人觉得我比较理解了,于是把他之前的工程给我看,顿时,我学到了很多实际的代码,受益匪浅,不过Spring是相当高深的,要学好的话,必须要自己多看些源码。本人目前只是勉强能用,借此把一整套Spring开发web project的流程记录下。可能会有很多问题,希望大家能指出

MVC是一种开发的结构,它至少有三层,一、Controller层  二、Service层 三、Dao层 ,其中: controller直接处理前端的请求,service协助controller处理这些数据(复杂的数据处理一般都由service处理,service也是连接Controller和DAO的层),而持久型数据则完全由DAO层处理,这样的结构使得Web工程比较容易管理。

首先配置下web.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>	


   <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <!-- 配置DispatcherServlet -->
	<servlet>
	<servlet-name>XNote</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
	<param-name>ContextConfigLocation</param-name>
	<param-value>
	<!-- 这些是待扫描的文件,就是告诉Spring在这些xml文件里找需要的信息的-->
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">			</span>对应XNote-controller.xml,XNote-service.xml,XNote-service.xml</span>-->
	/WEB-INF/XNote-data.xml
	/WEB-INF/XNote-service.xml
	/WEB-INF/XNote-controller.xml
	/WEB-INF/XNote-servlet.xml
	</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
	</servlet>
 	<servlet-mapping>
		<servlet-name>XNote</servlet-name>
		<url-pattern>*.jsp</url-pattern>
		<url-pattern>*.json</url-pattern>
	</servlet-mapping>
	
 
<filter>


<filter-name>multipartFilter</filter-name>


<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>


</filter>


<filter-mapping>


<filter-name>multipartFilter</filter-name>


<url-pattern>/springrest/*</url-pattern>


</filter-mapping>



 <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>    
  </filter>  
 <filter-mapping>    
        <filter-name>encodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>    
 </filter-mapping>   

</web-app>


等下要用到的bean

package com.qgmobile.xnote.bean;

public class User
{

	private String userId = null;
	private String password = null;
	private String email = null;

	public User()
	{

	}

	public User(String name)
	{
		super();
		this.userId = name;
	}

	public User(String name, String password)
	{
		super();
		this.userId = name;
		this.password = password;
	}

	public User(String name, String password, String email)
	{
		super();
		this.userId = name;
		this.password = password;
		this.email = email;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public String getUserId()
	{
		return userId;
	}

	public void setUserId(String name)
	{
		this.userId = name;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}

}



先创建个处理请求的Controller

package com.qgmobile.xnote.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import com.qgmobile.xnote.bean.User;
import com.qgmobile.xnote.service.UserService;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController
{
	// 获取spring的具体实现类的接口
	public UserService userService;

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request) 
							
	{
		/* request.setCharacterEncoding("utf8"); */

		

		String userJson = request.getParameter("param");
		System.out.println(userJson);
		Gson gson = new Gson();
		User user = gson.fromJson(userJson, User.class);
		System.out.println("login 开始!");

		return userService.login(user);
		// return "success!";
	}

	@ResponseBody
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(HttpServletRequest request)
	{
		
		String userJson = request.getParameter("param");
		System.out.println("注册开始:"+userJson);
		Gson gson = new Gson();
		User user = gson.fromJson(userJson, User.class);
		String resultString = userService.register(user);
		System.out.println(resultString);
		return resultString;
	}


	

}

接着是对应的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: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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
   <!-- 配置userController  这个为上面的controlller配置了其中的<span style="font-family: Arial, Helvetica, sans-serif;">public UserService userService;其他的controller也是相同配置</span><span style="font-family: Arial, Helvetica, sans-serif;">--></span>
   <bean id = "userController" class = "com.qgmobile.xnote.controller.UserController" scope = "prototype">
   <property name = "userService" ref = "userService"></property>
   </bean>
  
  <!-- 配置noteController -->
  <bean id = "noteController" class = "com.qgmobile.xnote.controller.NoteController" scope = "prototype">
  <property name = "noteService" ref = "noteService"></property>
  </bean>
  
  <!-- 配置homeworkController -->
  <bean id="homeworkController" class = "com.qgmobile.xnote.controller.HomeworkController" scope = "prototype">
  <property name="homeworkService" ref = "homeworkService"></property>
  </bean>
  

  
	 <bean  
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
    <property name="messageConverters">  
          <list>  
                <bean  
                    class="org.springframework.http.converter.StringHttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <bean class="org.springframework.http.MediaType">  
                                <constructor-arg index="0" value="text" />  
                                <constructor-arg index="1" value="plain" />  
                                <constructor-arg index="2" value="UTF-8" />  
                            </bean>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>  
 </bean> 
  
 <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="maxUploadSize">
        <value>104857600</value>
    </property>
    <property name="maxInMemorySize">
        <value>4096</value>
    </property>
  </bean>
    
</beans>

接下来就是service层的接口了

import com.qgmobile.xnote.bean.User;

public interface UserService{
	/**
	 * 
	 * 检查前台返回的注册登陆信息
	 * */
	
	public String login(User user);
	public String register(User user);   
	public String findE_mail(String userId);
	
}

具体实现是

package com.qgmobile.xnote.serviceImpl;

import com.qgmobile.xnote.bean.User;
import com.qgmobile.xnote.dao.UserDao;
import com.qgmobile.xnote.service.UserService;

public class UserServiceImpl implements UserService
{

	public UserDao userDao;

	public void setUserDao(UserDao userDao)
	{
		this.userDao = userDao;
	}

	public String register(User user)
	{

		if (NotNull(user) == true)
		{
			if (user.getEmail() != null)
			{
				if (userDao.exitUser(user.getUserId()) < 1)
				{
					userDao.insert(user);
					return "success";
				}

			}
		}

		return "fail";
	}

	public String login(User user)
	{

		if (NotNull(user) == true)
		{
			if (userDao.findUser(user) == 1)

			return "success";
		}

		return "fail";
	}

	public Boolean NotNull(User user)
	{
		// TODO Auto-generated method stub

		if (user.getUserId() != null)
		{
			if (user.getPassword() != null)
			{

				return true;

			}
		}
		return false;
	}

	public String findE_mail(String userId)
	{
		return userDao.findE_mail(userId);
	}

}
对应的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: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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<!-- 配置userService -->
<span style="white-space:pre">	</span><!--这边把具体类实现了,还设置了使用的Dao-->
	<bean id = "userService" class = "com.qgmobile.xnote.serviceImpl.UserServiceImpl">
	<property name="userDao" ref="userDao"></property>
	</bean>
	
	<!-- 配置noteService -->
	<bean id = "noteService" class = "com.qgmobile.xnote.serviceImpl.NoteServiceImpl">
	<property name="noteDao" ref="noteDao"></property>
	</bean>
	 
	 <!-- 配置homeworkService -->
	 <bean id="homeworkService" class = "com.qgmobile.xnote.serviceImpl.HomeworkServiceImpl">
	 <property name="homeworkDao" ref ="homeworkDao"></property>
	 </bean>
</beans>

Dao层也是类似的,首先是接口

package com.qgmobile.xnote.dao;



import com.qgmobile.xnote.bean.User;


public interface UserDao {  
  
    public void insert(User user);  
  
    public void update(User user);  
  
    public void delete(User user);  
  
    public int findUser(User user);   
  
    public int count();  
    
    public String findE_mail(String userId);
    
    public int exitUser(String userId);
}  

接着是实现类

package com.qgmobile.xnote.daoImpl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.qgmobile.xnote.dao.UserDao;
import com.qgmobile.xnote.bean.User;


public class UserDaoImpl extends SimpleJdbcDaoSupport implements UserDao
{

	@Override
	public void insert(User user)
	{

		String sql = "insert into user(userId,password,e_mail)values(?, password(?),?)";
		getSimpleJdbcTemplate().update(sql, user.getUserId(),
				user.getPassword(), user.getEmail());

	}

	@Override
	public void update(User user)
	{
		String sql = "update user set name=? where userId=?";
		getSimpleJdbcTemplate().update(sql, user.getPassword(),
				user.getUserId());
	}

	@Override
	public void delete(User user)
	{
		String sql = "delete from user where userId=?";
		getSimpleJdbcTemplate().update(sql, user.getUserId());
	}

	@Override
	public int findUser(User user)
	{
		String sql = "select count(*) from user where (userId=? and password=password(?))";
		return getSimpleJdbcTemplate().queryForInt(sql,
				user.getUserId(), user.getPassword());

	}

	@Override
	public int count()
	{
		String sql = "select count(*) from user";
		return getSimpleJdbcTemplate().queryForInt(sql);
	}

	public String findE_mail(String userId)
	{
		String sql = "select e_mail from user where userId=?";
		Map<String, Object> map = new HashMap<String, Object>();
		map = getSimpleJdbcTemplate().queryForMap(sql, userId);
		return map.get("e_mail").toString();
	}

	public int exitUser(String userId)
	{
		String sql = "select count(*) from user where(userId = ?)";
		return getSimpleJdbcTemplate().queryForInt(sql, userId);
	}

	/*
	 * StringBuffer sql= new StringBuffer("select * from user where 1=1");
	 * sql.append();
	 */

}

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: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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 配置userDao 设置了实现类 -->
	<bean id="userDao" class="com.qgmobile.xnote.daoImpl.UserDaoImpl">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置noteDao -->
	<bean id="noteDao" class="com.qgmobile.xnote.daoImpl.NoteDaoImpl">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置homeworkDao -->
	<bean id="homeworkDao" class="com.qgmobile.xnote.daoImpl.HomeworkDaoImpl">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://127.0.0.1:3306/xnote?characterEncoding=UTF-8
			</value>
		</property>
		<property name="username">
			<value>root数据库名</value>
		</property>
		<property name="password">
			<value>你的数据库密码</value>
		</property>
	</bean>
</beans>

到此,一条基本流程就弄好了,就等前端访问了,既然配置了数据库就需要数据库对应得上哦,那些sql语句还是非常浅显的,就不详细写咯!

大家还是要多注意理解吧,有空可以看下源代码,这个也是我以后深入所必须学习的,不过最近还是要忙些其他东西,另附整个工程的下载,大家还是尽量别下载吧,先自己理解多些,那些不懂再慢慢吃透

完整的工程在这里,放在tomcat中就可以运行了




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值