`

spring mvc+ibatis+freemarker+postgres框架

 
阅读更多
spring mvc+ibatis+freemarker+postgres框架实现一个简单的登陆功能

IDE工具为Eclipse

系统代码结构为:





LoginController.java代码如下:
package com.springmvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.springmvc.domain.User;
import com.springmvc.pojo.LoginCommand;
import com.springmvc.service.UserService;

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;

	@RequestMapping("/add")
	public ModelAndView loginCheck(HttpServletRequest request,@Valid LoginCommand loginCommand,BindingResult result){
		String username = loginCommand.getUsername();
		String password = loginCommand.getPassword();
        if(result.hasErrors()){
        	return new ModelAndView("login");
        }
		boolean bool = userService.isLoginSuccess(username, password);
		ModelAndView mav = new ModelAndView();
		if(bool){
			User user = userService.getUserByName(username);
			HttpSession session = request.getSession();
			session.setAttribute("userInfo", user);
			mav.setViewName("main");
			mav.addObject("user", user);
			return mav;
		}else{
			mav.setViewName("login");
			return mav;
		}
	}
	
	@RequestMapping("/")
	public String loginPage(){
		return "login";
	}
}



UserController.java代码如下:
package com.springmvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.springmvc.domain.User;
import com.springmvc.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/formAddress",method=RequestMethod.GET)
	public ModelAndView formAddress(HttpServletRequest request){
		ModelAndView mav = new ModelAndView(); 
		mav.setViewName("updateAddressForm");
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("userInfo");
		mav.addObject("user",user);
		return mav;
	}
	
	@RequestMapping(value="/updateAddress",method=RequestMethod.POST)
	public ModelAndView updateAddress(HttpServletRequest request,@RequestParam("newAddress")String newAddress){
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("userInfo");
		user.setAddress(newAddress);
		userService.updateUser(user);
		System.out.println(user.getAddress());
		ModelAndView mav = new ModelAndView();
		mav.setViewName("main");
		mav.addObject("user", user);
		return mav;
	}
}



UserDao.java代码如下:
package com.springmvc.dao;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.springmvc.domain.User;

@Repository
public class UserDao {

	@Autowired
	private SqlSessionTemplate sessionTemplate;
	
	public List<User> getMatchUsers(String username){
		return sessionTemplate.selectList("UserDaoMapping.getMatchUser", username);
	}
	
	public void update(User user){
		sessionTemplate.update("UserDaoMapping.updateUser", user);
	}
	
}



User.java代码如下:
package com.springmvc.domain;

public class User {
    //用户id
	private Integer id;
	//用户名
	private String username;
	//登录密码
	private String password;
	//用户地址
	private String address;
	
	public User(){
		
	}
	/**
	 * 由于ibatis配置文件的需要,所以写了这个构造函数
	 * @param id
	 * @param username
	 * @param password
	 * @param address
	 */
	public User(Integer id,String username,String password,String address){
		this.id = id;
		this.username = username;
		this.password = password;
		this.address = address;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

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

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	
	
}



User.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="UserDaoMapping">
	<resultMap type="User" id="user">
		<constructor>
			<idArg column="id" javaType="int" />
			<arg column="username" javaType="string" />
			<arg column="password" javaType="string" />
			<arg column="address" javaType="string" />
		</constructor>
	</resultMap> 
	<select id="selectUser" parameterType="int" resultType="User">
		select * from pg_userInfo where id=#{id}
	</select>
  
	<update id="updateUser" parameterType="User">
		update pg_userInfo
		set
		username = #{username},
		password = #{password},
		address = #{address}
		where id= #{id};
	</update>

	<select id="getMatchUser" parameterType="string" resultMap="user">
	  select * from pg_userInfo where username=#{username} 
	</select>

</mapper>


ibatis.xml配置文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true"/>  
		<setting name="lazyLoadingEnabled" value="true"/>  
		<setting name="multipleResultSetsEnabled" value="true"/>  
		<setting name="useColumnLabel" value="true"/>  
		<setting name="useGeneratedKeys" value="true"/>  
		<setting name="defaultExecutorType" value="SIMPLE"/>  
		<setting name="defaultStatementTimeout" value="25000"/>  
	</settings>
	<typeAliases>
		<typeAlias type="com.springmvc.domain.User"
			alias="User" />
	</typeAliases>
	
	<mappers>	
		<mapper resource="com/springmvc/domain/User.xml"/>
	</mappers>
</configuration>


GlobalInterceptor.java代码如下:
package com.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class GlobalInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception e)
			throws Exception {
		System.out.println("after handle");
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj, ModelAndView mav) throws Exception {
		System.out.println("post handle");
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Exception {
		System.out.println("before handle");
		
		return true;
	}

}



LoginCommand.java代码如下:
package com.springmvc.po;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

public class LoginCommand {
	
	@NotNull(message="username is null")
	private String username;
	
	@NotNull(message="password is null")
	private String password;

	@Min(value=34)
	private int num;
	
	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

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

	

}



UserService.java代码如下:
package com.springmvc.service;


import java.util.List;

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

import com.springmvc.dao.UserDao;
import com.springmvc.domain.User;

@Service
public class UserService {

	@Autowired
	private UserDao userDao;
	
	public boolean isLoginSuccess(String username,String password){
		List<User> listUser = userDao.getMatchUsers(username);
		if(listUser.size()==1&&listUser.get(0).getPassword().equals(password)){
			return true;
		}else{
			return false;
		}
	}
	
	public User getUserByName(String username){
		List<User> listUser = userDao.getMatchUsers(username);
		return listUser.get(0);
	}
	
	public void updateUser(User user){
		 userDao.update(user);
	}
}



Test.java代码如下:
package com.springmvc.test;


import static org.junit.Assert.*;
import java.util.List;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.springmvc.dao.UserDao;
import com.springmvc.domain.User;
import com.springmvc.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
public class Test {

	@Autowired
	private UserService userService;
	
	@Autowired
	private UserDao userDao;
	
	@org.junit.Test
	public void testUserDao(){
		List<User> userList = userDao.getMatchUsers("yangjianzhou");
		//assertEquals(userList.get(0).getAddress(),"shanghai-songjiang");
		
		User user = userList.get(0);
		user.setAddress("hubei-xiaogan");
		userDao.update(user);
		userList = userDao.getMatchUsers("yangjianzhou");
		user = userList.get(0);
		assertEquals(user.getAddress(), "hubei-xiaogan");
	}
	
}



applicationContext.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"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="com.springmvc.dao*"/>
    <context:component-scan base-package="com.springmvc.service*"/>
    <context:component-scan base-package="com.springmvc.controller*"/>
    
    <!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" 
		p:driverClassName="org.postgresql.Driver"
		p:url="jdbc:postgresql://localhost:5432/springmvc" 
		p:username="postgres"
		p:password="admin" />

	<!-- 配置SqlSessionFactoryBean工厂产生SqlSession对象 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	   <property name="dataSource" ref="dataSource"/>
	   <property name="configLocation" value="classpath:com/springmvc/ibatis/ibatis.xml"/>
	</bean>
		
	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />
		
	<bean class="org.mybatis.spring.SqlSessionTemplate">
	 <constructor-arg ref="sqlSessionFactory"/>
	</bean>
	<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
	<aop:config proxy-target-class="true">
		<aop:pointcut id="serviceMethod"
			expression=" execution(* com.springmvc.service..*(..))" />
		<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
	</aop:config>
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" />
		</tx:attributes>
	</tx:advice>
</beans>



log4j.properties文件的内容如下:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n


log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout




login.ftl代码如下:
<html>
<body>
<div style="height:20px; text-align=center"></div>
 <form action="${rc.contextPath}/add" method="post">
  <table align="center">
    <tr>
      <td>username:</td>
      <td><input type="text" name="username"></td>
    </tr>
       <tr>
      <td>password:</td>
      <td><input type="password" name="password"></td>
    </tr>
    <tr>
    <td></td>
     <td>
       <input type="submit" value="submit">
     </td>
    </tr>
  </table>
 </form>
</body>
</html>


main.ftl代码如下:
<html>
<body>

<div style="height:100px; text-align=center">主页</div>
<div style="height:20px; text-align=center">恭喜,用户${user.username}登录成功!</div>
<div><a href="${rc.contextPath}/user/formAddress">修改地址!</div>
</body>
</html>


updateAddressForm.ftl代码如下:
  
  <div> update address</div>
  
  <form method="POST" action="${rc.contextPath}/user/updateAddress">
    <p><br>old adress:</br>${user.address}
    <p>Your new address:<br>
    <input type="text" name="newAddress" size=60>
    <p><input type="submit" value="Submit">
  </form>


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

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

    <mvc:interceptors>
        <bean class="com.springmvc.interceptor.GlobalInterceptor" />
    </mvc:interceptors>

    <!-- freemarker 配置 -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    </bean>
    <!-- FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
        <property name="suffix" value=".ftl" />
        <property name="contentType" value="text/html;charset=utf-8" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="requestContextAttribute" value="rc" />
    </bean>
    <!-- 配置两种视图资源,先查找在/WEB-INF/ftl/下查找.ftl的视图,然后在/WEB-INF/jsp/下面查找.jsp的视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>


web.xml内容如下:
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>spring mvc</display-name>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
     <servlet-name>freemarker</servlet-name>
     <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
     <init-param>
      <param-name>TemplatePath</param-name>
      <param-value>/</param-value>
     </init-param>
     <load-on-startup>2</load-on-startup>
    </servlet>
    
    <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
    </servlet-mapping>
</web-app>


数据库表springmvc.pg_userInfo:




运行结果:


  • 大小: 42.6 KB
  • 大小: 5.4 KB
  • 大小: 70.3 KB
分享到:
评论

相关推荐

    Spring MVC+ibatis+oracle框架整合

    Spring MVC是Spring框架的一部分,是一个用于构建Web应用程序的模型-视图-控制器(MVC)架构。它提供了丰富的功能,如依赖注入、数据验证、本地化、国际化等。通过使用Spring MVC,开发者可以将业务逻辑、用户界面和...

    spring mvc+ibatiS+mysql代码

    通过这个"Spring MVC+iBATIS+MySQL"的DEMO,你可以深入理解这三个组件如何协同工作,形成一个完整的Web应用系统。这个项目为你提供了实践这些技术的基础,你可以在此基础上扩展和优化,以适应更复杂的业务需求。

    spring mvc+ibatis+mysql+easyui简单demo

    Spring MVC是Spring框架的一部分,用于构建Web应用程序。它提供了模型-视图-控制器(MVC)架构,使开发者能够将业务逻辑、数据处理和用户界面分离,从而实现更清晰的代码结构。Spring MVC通过DispatcherServlet作为...

    spring mvc+ibatis+spring2.5注解

    Spring MVC、iBatis 和 Spring 2.5 注解是构建高效、可扩展的企业级 Java 应用程序的常用技术组合。这篇详细的文章将深入探讨这三个组件的核心概念、它们如何协同工作以及如何在实际项目中应用。 首先,Spring MVC ...

    spring mvc+ibatis 框架 简单demo

    Spring MVC作为Spring框架的一部分,负责处理HTTP请求和响应,而iBatis则是一个轻量级的持久层框架,它简化了数据库操作。下面我们将深入探讨这两个框架以及如何结合使用它们创建一个简单的DEMO。 1. **Spring MVC...

    spring MVC + Ibatis

    Spring MVC 和 iBatis 是两个在 Java Web 开发中广泛使用的框架。Spring MVC 作为 Model-View-Controller 模式的实现,负责处理 HTTP 请求、转发数据到服务层,并将结果呈现给用户。而 iBatis 是一个轻量级的持久层...

    spring mvc+ibatis+spring注解

    Spring框架中的注解大大减少了XML配置,提高了代码的可读性和可维护性。例如,`@Component`、`@Service`、`@Repository`和`@Controller`用于标记不同的bean,它们都继承自`@Component`,并由Spring自动扫描和管理。`...

    Spring.net + iBatis.net + asp.net MVC 整合文档

    关于Spring.net + iBatis.net + asp.net MVC 整合的文档,值!

    搭建spring mvc+spring+ibatis所需所有jar包

    Spring MVC作为Spring框架的一部分,主要用于处理Web请求,Spring则提供全面的依赖注入和面向切面编程功能,而iBatis则是一个优秀的持久层框架,它简化了数据库操作。以下是关于这三个框架及其集成使用的关键知识点...

    spring mvc + ibatis + Oracle + ajax 轻量级架构搭建及详解

    Spring MVC是Spring框架的一个模块,它提供了MVC(Model-View-Controller)设计模式的实现。在Spring MVC中,Controller负责接收请求并调用业务逻辑,Model代表应用数据,View则负责呈现结果。Spring MVC通过...

    struts2+spring3+ibatis项目整合案例

    Struts2、Spring3和iBATIS是Java Web开发中常用的三大框架,它们各自负责不同的职责,协同工作可以构建出高效、松耦合的Web应用。在这个“struts2+spring3+ibatis项目整合案例”中,我们将深入探讨这三个框架如何...

    struts2+spring+Ibatis框架包

    Spring框架则是一个全面的企业级应用开发框架,它的核心特性包括依赖注入(DI)和面向切面编程(AOP)。依赖注入帮助解耦组件,使得代码更易于测试和维护。Spring还提供了对事务管理、数据访问、Web应用的支持,以及...

    spring MVC+ibatis+ehcache开发包集合

    自己项目的开发包集合,其中包括:缓存处理ehcache相关jar,spring MVC4.0 jar,ehcache依赖jar,以及其他jar(图像处理thumbnailator-0.4.2),包虽然不是很新但可用。实际使用时找包较为麻烦,现在整理出来,希望...

    spring mvc+ibatis+dwr实现dispatchservlet

    首先,Spring MVC是Spring框架的一部分,它是一个用于构建Web应用程序的模型-视图-控制器(MVC)架构。DispatchServlet是Spring MVC的核心组件,它负责接收HTTP请求并将其分派到相应的处理器。DispatchServlet根据...

    spring mvc+ibatis+oracle单表增删改(有包)

    Spring MVC是Spring框架的一个模块,专门处理Web应用程序的模型-视图-控制器(MVC)架构。iBATIS则是一个SQL映射框架,它允许开发者将SQL查询与Java代码分离,提高代码的可读性和可维护性。而Oracle是一种广泛使用的...

    struts2+spring+ibatis+mysql

    这个组合集成了强大的MVC(Model-View-Controller)框架Struts2、依赖注入与面向切面编程的Spring框架、轻量级持久层框架Ibatis以及关系型数据库管理系统MySQL。 1. **Struts2**:Struts2是Apache软件基金会下的一...

    Spring MVC+Hibernate&Ibatis学习 例子 教程

    **Spring MVC** 是Spring框架的一部分,用于构建MVC(Model-View-Controller)结构的Web应用。它提供了一个灵活的架构,允许开发者通过注解或配置来处理请求、映射视图和管理模型数据。Spring MVC的核心组件包括...

    spring3mvc+ibatis+demo

    Spring MVC是Spring框架的一部分,专门用于构建Web应用程序的Model-View-Controller(MVC)架构。它的主要优点包括解耦、可测试性和灵活性。在Spring MVC中,Controller处理HTTP请求,Model负责业务逻辑,而View则...

Global site tag (gtag.js) - Google Analytics