您的位置:首页 > 其它

ssm框架整合(最简单的增删改查)

2019-01-22 09:44 337 查看

一、环境要求
myEclipse+jdk1.8+tomcat7+ssm框架需要jar
https://pan.baidu.com/s/1eNn658Hkncm4z28yQtEqxg
提取码:18fd
二、项目结构截图:

三、配置文件详细配置:
1、web.xml配置文件:

<!-- SpringMVC前端控制器配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 解决中文乱码	spring带的解决乱码的配置 -->
<filter>
<filter-name>charcterEncoding</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>charcterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 启动tomcat容器时候,加载spring的ioc容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 指定spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

2、mybatis.xml文件:

<!--由于mybatis已经被spring整合了,所以这里的mybatis文件只需要写一个别名就行了-->
<configuration>
<!-- 别名 -->
<typeAliases>
<package name="com.nueo.pojo"/>
</typeAliases>
</configuration>

3、applicationContext.xml文件配置

<!-- 前端视图名的配置 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀名,这里主要是指定jsp页面在什么目录下面如果在根目录下就写 / -->
<property name="prefix" value="/"></property>
<!--后缀名,视图资源的后缀名是,这里是 .jsp -->
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 配置数据源的bean,高效连接数据库 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://192.168.191.144:3306/hibernateTest?useUnicode=true&amp;characterEncoding=UTF-8">
</property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>

<!--让Spring管理mybatis中的核心对象SqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入依赖对象:dataSource  注意这里的名字,一定不能乱起 -->
<property name="dataSource" ref="dataSource"></property>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>

<!-- Mapper接口所在包名,Spring会自动查找其下的类并生成接口的实现类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.nueo.mapper"></property>
<!--sqlSessionFactory 指定SqlSessionFactoryBean 对象 -->
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
</bean>

<!--配置事务处理类 -->
<bean id="tm"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 这里会引用上面的数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务通知属性 -->
<tx:advice id="txAdvice"  transaction-manager="tm">
<!--
定义事务传播属性 这里的事务就限定了你在实现类中起名字的规定,需要事务的
增删改以update、add、delete开头
-->
<tx:attributes>
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="mycut"
expression="execution(* com.nueo.service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="mycut" />
</aop:config>

<!-- 扫描包中的注解,实现依赖注入 -->
<context:component-scan base-package="com.nueo.controller,com.nueo.service.impl"></context:component-scan>
<!-- 开启注解功能 -->
<mvc:annotation-driven />
<!-- 开启静态资源功能 -->
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/jq/" mapping="/jq/**"/>

4、log4j文件的配置:

log4j.rootLogger=info, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

四|、实体类的创建和数据库表的设计:
1、实体类的创建:
Answer.java:

public class Answer {
private int a_id;
private String a_content;
private String a_date;
private int a_q_id;
private Question question;
......get/set方法...构造函数.....自己去生成......
}

2、Question.java:

public class Question {
private int q_id;
private String q_title;
private String q_detailDesc;
private int q_answerCount;
private String q_lastModify;
......get/set方法...构造函数.....自己去生成......
}

3、数据库设计:

五、mapper层(数据访问层)代码:
Answer:

//接口类
public interface AnswerMapper {
//	回答问题,就是添加answer
int addAnswer(Answer answer);
//	查询出问题下面的回答
List<Answer> selAllAnswer(@Param("q_Id") int q_Id);
//	查询最后一条记录
Answer selAnswerByLastId();
}

//映射文件:
<mapper namespace="com.nueo.mapper.AnswerMapper">
<!-- 添加答案 -->
<insert id="addAnswer" parameterType="Answer" useGeneratedKeys="true">
INSERT INTO answer (a_content,a_date,a_q_id) VALUES (#{a_content},#{a_date},#{a_q_id})
</insert>
<!-- 查询出问题下面的所有答案 -->
<select id="selAllAnswer" resultType="Answer" parameterType="int">
SELECT * from answer where a_q_id=#{q_Id}
</select>
<!-- 查询最后一条记录 -->
<select id="selAnswerByLastId" resultType="Answer">
select * from answer order by a_id desc limit 1
</select>
</map
27d1b
per>

Question:

//接口
public interface QuestionMapper {
//	查询得出所有的问题
List<Question> selAllQuestion ();
//	添加一个问题
int addQuestion(Question question);
//	通过编号查询出问题
Question selQuestionById(@Param("q_id") int q_id);
//	修改问题
int updateQuestion(Question question);
}

//映射文件
<mapper namespace="com.nueo.mapper.QuestionMapper">
<!-- 查询得出所有的问题 -->
<select id="selAllQuestion" resultType="Question">
select * from question
</select>

<!-- 添加一个问题 -->
<insert id="addQuestion" parameterType="Question"
useGeneratedKeys="true">
INSERT INTO question
(q_title,q_detailDesc,q_answerCount,q_lastModify)
VALUES
(#{q_title},#{q_detailDesc},#{q_answerCount},#{q_lastModify})
</insert>
<!-- 通过问题编号查询出问题 -->
<select id="selQuestionById" resultType="Question"
parameterType="int">
SELECT * from question where q_id=#{q_id}
</select>
<!-- 修改问题信息的动态SQL -->
<update id="updateQuestion" parameterType="Question">
UPDATE question
<set>
<if test="q_title !=null and q_title !=''">
q_title=#{q_title},
</if>
<if test="q_detailDesc !=null and q_detailDesc !=''">
q_detailDesc=#{q_detailDesc},
</if>
<if test="q_answerCount !=null and q_answerCount !=''">
q_answerCount=#{q_answerCount},
</if>
<if test="q_lastModify !=null and q_lastModify !=''">
q_lastModify=#{q_lastModify},
</if>
</set>
where q_id = #{q_id}
</update>
</mapper>

六、service层与其实现类:
Answer

//AnswerService.java
public interface AnswerService {
//	回答问题,就是添加answer
int addAnswer(Answer answer);
//	查询出问题下面的回答
List<Answer> selAllAnswer(@Param("q_Id") int q_Id);
//	查询最后一条记录
Answer selAnswerByLastId();
}

//AnswerServiceImpl.java
@Service("answerServiceImpl")
public class AnswerServiceImpl implements AnswerService{
@Resource
private AnswerMapper answerMapper;
@Resource
private QuestionMapper questionMapper;
/**
* 回答问题,就是添加answer
* @param answer
* @return
*/
@Override
public int addAnswer(Answer answer) {
answer.setA_date(MyUtil.getDate());
int addAnswerIndex = answerMapper.addAnswer(answer);
Question selQuestionById = questionMapper.selQuestionById(answer.getA_q_id());
selQuestionById.setQ_answerCount(selQuestionById.getQ_answerCount()+1);
int updateQuestionIndex = questionMapper.updateQuestion(selQuestionById);
return addAnswerIndex+updateQuestionIndex;
}

/**
* 查询出问题下面的回答
* @param q_Id 问题编号
*/
@Override
public List<Answer> selAllAnswer(int q_Id) {
List<Answer> selAllAnswer = answerMapper.selAllAnswer(q_Id);
return selAllAnswer;
}

@Override
public Answer selAnswerByLastId() {
Answer selAnswerByLastId = answerMapper.selAnswerByLastId();
return selAnswerByLastId;
}
}

Question:

//QuestionService.java
public interface QuestionService {
//	查询得出所有的问题
List<Question> selAllQuestion ();
//	添加一个问题
int addQuestion(Question question);
//	通过编号查询出问题
Question selQuestionById(@Param("q_id") int q_id);
}

//QuestionServiceImpl.java
@Service("questionServiceImpl")
public class QuestionServiceImpl implements QuestionService{
@Resource
private QuestionMapper questionMapper;

/**
* 查询得出所有的问题
*/
@Override
public List<Question> selAllQuestion() {
List<Question> selAllQuestion = questionMapper.selAllQuestion();
return selAllQuestion;
}

/**
* 添加一个问题
*/
@Override
public int addQuestion(Question question) {
question.setQ_lastModify(MyUtil.getDate());
int addQuestionIndex = questionMapper.addQuestion(question);
return addQuestionIndex;
}

/**
* 通过编号查询出问题
*/
@Override
public Question selQuestionById(int q_id) {
Question selQuestionById = questionMapper.selQuestionById(q_id);
return selQuestionById;
}
}

七、controller层(控制器层)的实现
1、AnswerController.java

@Controller
public class AnswerController {
@Resource
private AnswerService answerService;
@Resource
private QuestionService questionService;

@RequestMapping("/showQuestionAnswer/{q_id}")
public String showQuestionAnswer(@PathVariable("q_id") int q_id,ModelMap modelMap){
List<Answer> answers = answerService.selAllAnswer(q_id);
Question question = questionService.selQuestionById(q_id);
modelMap.put("question", question);
modelMap.put("answers", answers);
return "showQuestionAnswer";
}
/**
* 回答问题的controller
* 就是添加回答
* 需要:问题编号、回答问题的时间(实现类添加)、问题正文、添加成功在问题回答的数量加1
* @return
*/
@RequestMapping("/answerQuestion")
@ResponseBody
public String answerQuestion(String q_id,String a_content){
JSONObject obj=new JSONObject();
int addAnswerIndex = answerService.addAnswer(new Answer(a_content,Integer.parseInt(q_id)));
if(addAnswerIndex>=2){
Answer lastAnswer = answerService.selAnswerByLastId();
obj.put("lastAnswer",lastAnswer);
}
return obj.toJSONString();
}
}

2、QuestionController.java

@Controller
public class QuestionController {
@Resource
private QuestionService questionService;
@RequestMapping("/listQuestion")
public String listQuestion(ModelMap modelMap){
List<Question> questions = questionService.selAllQuestion();
modelMap.put("questions", questions);
return "listQuestion";
}
}

八、前端页面层:
1、listQuestion.jsp(该页面显示所有信息)

<body>
<div style="position: relative; left: 30%;top: 50px;">
<h1>在线问答</h1>
<!-- 添加问题 -->
<a href="addQuestion.jsp" style="position: relative; left: 250px;">我要提问</a>
<table	border="1px">
<tr>
<th>序号</th>
<th>问题</th>
<th>回答次数</th>
<th>最后修改时间</th>
</tr>
<c:forEach items="${requestScope.questions}" var="question">
<c:if test="${question.q_answerCount==0}">
<tr>
<td style="color: red;">${question.q_id}</td>
<td ><a href="showQuestionAnswer/${question.q_id}" style="color: red;">${question.q_title}</a></td>
<td style="color: red;">${question.q_answerCount}</td>
<td style="color: red;">${question.q_lastModify}</td>
</tr>
</c:if>
<c:if test="${question.q_answerCount ne 0}">
<tr>
<td>${question.q_id}</td>
<td ><a href="showQuestionAnswer/${question.q_id}">${question.q_title}</a></td>
<td>${question.q_answerCount}</td>
<td>${question.q_lastModify}</td>
</tr>
</c:if>
</c:forEach>
</table>
</div>
</body>

2、showQuestionAnswer.jsp 点击问题时,跳转的回答问题界面

<body>
<div style="position: relative; left: 30%;top: 50px;">
<h1>在线问答</h1>
<!-- 返回首页
<form action="answerQuestion">
-->
<a href="listQuestion" style="position: relative; left: 250px;">返回首页</a>

<table id="showAnswer">
<tr>
<td >问题:</td>
<td >${requestScope.question.q_title}</td>
</tr>
<tr>
<td >问题描述:</td>
<td >${requestScope.question.q_detailDesc}</td>
</tr>
<tr><td >网友回答:</td></tr>
<c:forEach items="${requestScope.answers}" var="answer">
<tr>
<td ></td>
<td >${answer.a_date}</td>
</tr>
<tr>
<td ></td>
<td >${answer.a_content}</td>
</tr>
</c:forEach>

</table>
<table>
<tr>
<td >我来回答</td>
<td >
<input type="hidden" value="${requestScope.question.q_id}" id="q_id">
<input type="text" style="width: 200px;height: 100px" id="a_content">
</td>
</tr>
<tr>
<td ><input type="button" value="提交答案" onclick="confirmAnswer()"></td>
</tr>
</table>
</div>
</body>

//ajax 代码,实现局部刷新(局部添加问题)
<script type="text/javascript">
function confirmAnswer(){
var q_id=$("#q_id").val();
var a_content=$("#a_content").val();
alert(q_id+"-----"+a_content);
$.ajax({
url : "answerQuestion",
type: "GET",
dataType : "json",
data: {
q_id:q_id,
a_content:a_content
},
async : true,
timeout : 50000,
success : function(data) {
alert(data.lastAnswer.a_content+"--"+data.lastAnswer.a_date+"---"+data.lastAnswer.a_id);
var str="<tr>"+
"<td ></td>"+
"<td >"+data.lastAnswer.a_date+"</td>"+
"</tr>"+
"<tr>"+
"<td ></td>"+
"<td >"+data.lastAnswer.a_content+"</td>"+
"</tr>";
$("#showAnswer").append(str);
},
error : function() {
}
});
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: